|
using System;
using System.Diagnostics;
using System.Messaging;
using System.Threading;
namespace Cogin.Msmq
{
public class MessageReceiver
{
protected MessageQueue incomingQueue;
public MessageReceiver( MessageQueue incomingQueue )
{
this.incomingQueue = incomingQueue;
incomingQueue.MessageReadPropertyFilter.SetAll();
}
public void receiveMessage( IFailedMessageHandler failedMessageHandler )
{
MessageQueueTransaction transaction = new MessageQueueTransaction();
transaction.Begin();
Message message = null;
try
{
message = incomingQueue.Receive( TimeSpan.Zero, transaction );
Trace.WriteLine( "Received message ID: " + message.Id );
processMessage( message );
transaction.Commit();
Trace.WriteLine( "Message processed OK" );
}
catch (Exception e)
{
Trace.WriteLine( "Message failed" );
TransactionAction transactionAction = TransactionAction.ROLLBACK;
if ( message == null )
{
Trace.WriteLine( "Message couldn't be received: " + e.Message );
}
else
{
try
{
transactionAction = failedMessageHandler.HandleFailedMessage( message, transaction );
} catch( Exception failureHandlerException )
{
Trace.WriteLine( "Error during failure handling: " + failureHandlerException.Message );
}
}
if ( transactionAction == TransactionAction.ROLLBACK )
{
transaction.Abort();
Trace.WriteLine( "Transaction rolled back" );
}
else
{
transaction.Commit();
Trace.WriteLine( "Transaction commited - message removed from queue" );
}
}
}
private void processMessage( Message message )
{
if ( message.Label != "OK" )
{
// simulate failure for poison messages
throw new ApplicationException( "Simulated failure" );
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
Developing software since 1985. Hobby turned into profession even before graduating on Computer Science. Main interest was Internet development in Java, but since 2002. focus shifted toward .Net. With experience as lead developer on several larger applications for financial industry, Dejan is currently mostly dealing with agile development of distributed applications. He is also developing tools for MSMQ community.
See more on
www.cogin.com