<p>I have create a WCF service and am utilising netMsmqBinding binding.</p>
<p>This is a simple service that passes a Dto to my service method and does not expect a response. The message is placed in an MSMQ, and once picked up inserted into a database.</p>
<p>What is the best method to make sure no data is being lost.</p>
<p>I have tried the 2 following methods:</p>
<ol>
<li><p>Throw an exception</p>
<p>This places the message in a dead letter queue for manual perusal. I can process this when my strvice starts</p>
</li>
<li><p>set the receiveRetryCount=&quot;3&quot; on the binding</p>
<p>After 3 tries - which happen instantanously, this seems to leave the message in queue, but fault my service. Restarting my service repeats this process.</p>
</li>
</ol>
<p>Ideally I would like to do the follow:</p>
<p>Try process the message</p>
<ul>
<li>If this fails, wait 5 minutes for that message and try again.</li>
<li>If that process fails 3 times, move the message to a dead letter queue.</li>
<li>Restarting the service will push all messages from the dead letter queue back into the queue so that it can be processed.</li>
</ul>
<p>Can I achieve this? If so how?
Can you point me to any good articles on how best to utilize WCF and MSMQ for my given sceneria.</p>
<p>Any help would be much appreciated. Thanks!</p>
<p><strong>Some additional information</strong></p>
<p>I am using MSMQ 3.0 on Windows XP and Windows Server 2003.
Unfortunately I can't use the built in poison message support targeted at MSMQ 4.0 and Vista/2008.</p>

[{'answer_id': 82586, 'author': 'aogan', 'author_id': 4795, 'author_profile': 'https://Stackoverflow.com/users/4795', 'pm_score': 4, 'selected': False, 'text': '<p>I think with MSMQ (avaiable only on Vista) you might be able to to do like this:</p>\n\n<pre><code>&lt;bindings&gt;\n    &lt;netMsmqBinding&gt;\n        &lt;binding name="PosionMessageHandling"\n             receiveRetryCount="3"\n             retryCycleDelay="00:05:00"\n             maxRetryCycles="3"\n             receiveErrorHandling="Move" /&gt;\n    &lt;/netMsmqBinding&gt;\n&lt;/bindings&gt;\n</code></pre>\n\n<p>WCF will immediately retry for ReceiveRetryCount times after the first call failure. After the batch has failed the message is moved\nto the retry queue. After a delay of RetryCycleDelay minute, the message moved from the retry queue to the endpoint queue and the batch is retried. This will be repeated \nMaxRetryCycle time. If all that fails the message is handled according to receiveErrorHandling which can be move \n(to poison queue), reject, drop or fault</p>\n\n<p>By the way a good text about WCF and MSMQ is the chapther 9 of Progammig WCF book from Juval Lowy</p>\n'}, {'answer_id': 82715, 'author': 'WebDude', 'author_id': 15360, 'author_profile': 'https://Stackoverflow.com/users/15360', 'pm_score': 1, 'selected': False, 'text': "<p>Unfortunately I'm stuck on Windows XP and Windows Server 2003 so that isn't an option for me. - (I will re-clarify that in my question as I found this solution after posting and realised i couldn't use it)</p>\n\n<p>I found that one solution was to setup a custom handler which would move my message onto another queue or poison queue and restart my service.\nThis seemed crazy to me. Imagine my Sql Server was down how often the service would be restarted.</p>\n\n<p>SO what I've ended up doing is allowing the Line to fault and leave messages on the queue.\nI also log a fatal message to my system logging service that this has happened.\nOnce our issue is resolved, I restart the service and all the messages start getting processed again.</p>\n\n<p>I realised re-processing this message or any other will all fail, so why the need to move this message and the others to another queue. I may as well stop my service, and start it again when all is operating as expected.</p>\n\n<p>aogan, you had the perfect answer for MSMQ 4.0, but unfortunately not for me</p>\n"}, {'answer_id': 82822, 'author': 'Chris Wenham', 'author_id': 5548, 'author_profile': 'https://Stackoverflow.com/users/5548', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re using SQL-Server then you should use a distributed transaction, since both MSMQ and SQL-Server support it. What happens is you wrap your database write in a TransactionScope block and call scope.Complete() only if it succeeds. If it fails, then when your WCF method returns the message will be placed back into the queue to be tried again. Here\'s a trimmed version of code I use:</p>\n\n<pre><code>    [OperationBehavior(TransactionScopeRequired=true, TransactionAutoComplete=true)]\n    public void InsertRecord(RecordType record)\n    {\n        try\n        {\n            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))\n            {\n                SqlConnection InsertConnection = new SqlConnection(ConnectionString);\n                InsertConnection.Open();\n\n                // Insert statements go here\n\n                InsertConnection.Close();\n\n                // Vote to commit the transaction if there were no failures\n                scope.Complete();\n            }\n        }\n        catch (Exception ex)\n        {\n            logger.WarnException(string.Format("Distributed transaction failure for {0}", \n                Transaction.Current.TransactionInformation.DistributedIdentifier.ToString()),\n                ex);\n        }\n     }\n</code></pre>\n\n<p>I test this by queueing up a large but known number of records, let WCF start lots of threads to handle many of them simultaneously (reaches 16 threads--16 messages off the queue at once), then kill the process in the middle of operations. When the program is restarted the messages are read back from the queue and processed again as if nothing happened, and at the conclusion of the test the database is consistent and has no missing records.</p>\n\n<p>The Distributed Transaction Manager has an ambient presence, and when you create a new instance of TransactionScope it automatically searches for the current transaction within the scope of the method invokation--which should have been created already by WCF when it popped the message off the queue and invoked your method.</p>\n'}, {'answer_id': 85683, 'author': 'tomasr', 'author_id': 10292, 'author_profile': 'https://Stackoverflow.com/users/10292', 'pm_score': 4, 'selected': True, 'text': '<p>There\'s a sample in the SDK that might be useful in your case. Basically, what it does is attach an IErrorHandler implementation to your service that will catch the error when WCF declares the message to be "poison" (i.e. when all configured retries have been exhausted). What the sample does is move the message to another queue and then restart the ServiceHost associated with the message (since it will have faulted when the poison message was found).</p>\n\n<p>It\'s not a very pretty sample, but it can be useful. There are a couple of limitations, though:</p>\n\n<p>1- If you have multiple endpoints associated with your service (i.e. exposed through several queues), there\'s no way to know which queue the poison message arrived in. If you only have a single queue, this won\'t be a problem. I haven\'t seen any official workaround for this, but I\'ve experimented with one possible alternative which I\'ve documented here: <a href="http://winterdom.com/weblog/2008/05/27/NetMSMQAndPoisonMessages.aspx" rel="noreferrer">http://winterdom.com/weblog/2008/05/27/NetMSMQAndPoisonMessages.aspx</a></p>\n\n<p>2- Once the problem message is moved to another queue, it becomes your responsibility, so it\'s up to you to move it back to the processing queue once the timeout is done (or attach a new service to that queue to handle it).</p>\n\n<p>To be honest, in either case, you\'re looking at some "manual" work here that WCF just doesn\'t cover on it\'s own. </p>\n\n<p>I\'ve been recently working on a different project where I have a requirement to explicitly control how often retries happen, and my current solution was to create a set of retry queues and manually move messages between the retry queues and the main processing queue based on a set of timers and some heuristics, just using the raw System.Messaging stuff to handle the MSMQ queues. It seems to work pretty nicely, though there are a couple of gotchas if you go this way.</p>\n'}]
['https://Stackoverflow.com/questions/82099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15360/']