File: MsmqReceiveHelper.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (483 lines) | stat: -rw-r--r-- 18,343 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
    using System.Runtime;
    using System.ServiceModel.Diagnostics;
    using System.Threading;
    using System.Transactions;
    using System.ComponentModel;
    using System.Runtime.Versioning;

    // PostRollbackErrorStrategy
    interface IPostRollbackErrorStrategy
    {
        bool AnotherTryNeeded();
    }

    // SimplePostRollbackErrorStrategy
    class SimplePostRollbackErrorStrategy : IPostRollbackErrorStrategy
    {
        const int Attempts = 50;
        const int MillisecondsToSleep = 100;

        int attemptsLeft = Attempts;
        long lookupId;

        internal SimplePostRollbackErrorStrategy(long lookupId)
        {
            this.lookupId = lookupId;
        }

        public bool AnotherTryNeeded()
        {
            if (--this.attemptsLeft > 0)
            {
                if (attemptsLeft == (Attempts - 1))
                    MsmqDiagnostics.MessageLockedUnderTheTransaction(lookupId);
                Thread.Sleep(TimeSpan.FromMilliseconds(MillisecondsToSleep));
                return true;
            }
            else
            {
                MsmqDiagnostics.MoveOrDeleteAttemptFailed(lookupId);
                return false;
            }
        }
    }

    sealed class MsmqReceiveHelper
    {
        IPoisonHandlingStrategy poisonHandler;
        string queueName;
        MsmqQueue queue;
        MsmqReceiveParameters receiveParameters;
        Uri uri;
        string instanceId;
        IMsmqMessagePool pool;
        MsmqInputChannelBase channel;
        MsmqChannelListenerBase listener;
        ServiceModelActivity activity;
        string msmqRuntimeNativeLibrary;

        internal MsmqReceiveHelper(MsmqReceiveParameters receiveParameters, Uri uri, IMsmqMessagePool messagePool, MsmqInputChannelBase channel, MsmqChannelListenerBase listener)
        {
            this.queueName = receiveParameters.AddressTranslator.UriToFormatName(uri);
            this.receiveParameters = receiveParameters;
            this.uri = uri;
            this.instanceId = uri.ToString().ToUpperInvariant();
            this.pool = messagePool;
            this.poisonHandler = Msmq.CreatePoisonHandler(this);
            this.channel = channel;
            this.listener = listener;
            this.queue = Msmq.CreateMsmqQueue(this);
        }

        internal ServiceModelActivity Activity
        {
            get { return this.activity; }
        }

        IPoisonHandlingStrategy PoisonHandler
        {
            get { return this.poisonHandler; }
        }

        internal MsmqReceiveParameters MsmqReceiveParameters
        {
            get { return this.receiveParameters; }
        }

        internal MsmqInputChannelBase Channel
        {
            get { return this.channel; }
        }

        internal MsmqChannelListenerBase ChannelListener
        {
            get { return this.listener; }
        }

        internal Uri ListenUri
        {
            get { return this.uri; }
        }

        internal string InstanceId
        {
            get { return this.instanceId; }
        }

        internal MsmqQueue Queue
        {
            get { return this.queue; }
        }

        internal bool Transactional
        {
            get { return this.receiveParameters.ExactlyOnce; }
        }

        internal string MsmqRuntimeNativeLibrary
        {
            get
            {
                if (this.msmqRuntimeNativeLibrary == null)
                {
                    this.msmqRuntimeNativeLibrary = Environment.SystemDirectory + "\\" + UnsafeNativeMethods.MQRT;
                }
                return this.msmqRuntimeNativeLibrary;
            }
        }

        internal void Open()
        {
            this.activity = MsmqDiagnostics.StartListenAtActivity(this);
            using (MsmqDiagnostics.BoundOpenOperation(this))
            {
                this.queue.EnsureOpen();
                this.poisonHandler.Open();
            }
        }

        internal void Close()
        {
            using (ServiceModelActivity.BoundOperation(this.Activity))
            {
                this.poisonHandler.Dispose();
                this.queue.Dispose();
            }
            ServiceModelActivity.Stop(this.activity);
        }

        internal MsmqInputMessage TakeMessage()
        {
            return this.pool.TakeMessage();
        }

        internal void ReturnMessage(MsmqInputMessage message)
        {
            this.pool.ReturnMessage(message);
        }

        internal static void TryAbortTransactionCurrent()
        {
            if (null != Transaction.Current)
            {
                try
                {
                    Transaction.Current.Rollback();
                }
                catch (TransactionAbortedException ex)
                {
                    MsmqDiagnostics.ExpectedException(ex);
                }
                catch (ObjectDisposedException ex)
                {
                    MsmqDiagnostics.ExpectedException(ex);
                }
            }
        }

        internal void DropOrRejectReceivedMessage(MsmqMessageProperty messageProperty, bool reject)
        {
            this.DropOrRejectReceivedMessage(this.Queue, messageProperty, reject);
        }

        internal void DropOrRejectReceivedMessage(MsmqQueue queue, MsmqMessageProperty messageProperty, bool reject)
        {
            if (this.Transactional)
            {
                TryAbortTransactionCurrent();
                IPostRollbackErrorStrategy postRollback = new SimplePostRollbackErrorStrategy(messageProperty.LookupId);
                MsmqQueue.MoveReceiveResult result = MsmqQueue.MoveReceiveResult.Unknown;
                do
                {
                    using (MsmqEmptyMessage emptyMessage = new MsmqEmptyMessage())
                    {
                        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
                        {
                            result = queue.TryReceiveByLookupId(messageProperty.LookupId, emptyMessage, MsmqTransactionMode.CurrentOrThrow);
                            if (MsmqQueue.MoveReceiveResult.Succeeded == result && reject)
                                queue.MarkMessageRejected(messageProperty.LookupId);
                            scope.Complete();
                        }
                    }

                    if (result == MsmqQueue.MoveReceiveResult.Succeeded)
                        // If 'Reject' supported and 'Reject' requested, put reject in the trace, otherwise put 'Drop'
                        MsmqDiagnostics.MessageConsumed(instanceId, messageProperty.MessageId, (Msmq.IsRejectMessageSupported && reject));

                    if (result != MsmqQueue.MoveReceiveResult.MessageLockedUnderTransaction)
                        break;
                }
                while (postRollback.AnotherTryNeeded());
            }
            else
            {
                MsmqDiagnostics.MessageConsumed(instanceId, messageProperty.MessageId, false);
            }
        }

        //
        internal static void MoveReceivedMessage(MsmqQueue queueFrom, MsmqQueue queueTo, long lookupId)
        {
            TryAbortTransactionCurrent();

            IPostRollbackErrorStrategy postRollback = new SimplePostRollbackErrorStrategy(lookupId);
            MsmqQueue.MoveReceiveResult result = MsmqQueue.MoveReceiveResult.Unknown;
            do
            {
                result = queueFrom.TryMoveMessage(lookupId, queueTo, MsmqTransactionMode.Single);

                if (result != MsmqQueue.MoveReceiveResult.MessageLockedUnderTransaction)
                    break;
            }
            while (postRollback.AnotherTryNeeded());
        }

        internal void FinalDisposition(MsmqMessageProperty messageProperty)
        {
            this.poisonHandler.FinalDisposition(messageProperty);
        }

        // WaitForMessage
        internal bool WaitForMessage(TimeSpan timeout)
        {
            using (MsmqEmptyMessage message = new MsmqEmptyMessage())
            {
                return (MsmqQueue.ReceiveResult.Timeout != this.queue.TryPeek(message, timeout));
            }
        }
        //
        internal IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return new WaitForMessageAsyncResult(this.queue, timeout, callback, state);
        }
        //
        public bool EndWaitForMessage(IAsyncResult result)
        {
            return WaitForMessageAsyncResult.End(result);
        }

        internal bool TryReceive(MsmqInputMessage msmqMessage, TimeSpan timeout, MsmqTransactionMode transactionMode, out MsmqMessageProperty property)
        {
            property = null;

            MsmqQueue.ReceiveResult receiveResult = this.Queue.TryReceive(msmqMessage, timeout, transactionMode);
            if (MsmqQueue.ReceiveResult.OperationCancelled == receiveResult)
                return true;
            if (MsmqQueue.ReceiveResult.Timeout == receiveResult)
                return false;
            else
            {
                property = new MsmqMessageProperty(msmqMessage);
                if (this.Transactional)
                {
                    if (this.PoisonHandler.CheckAndHandlePoisonMessage(property))
                    {
                        long lookupId = property.LookupId;
                        property = null;
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new MsmqPoisonMessageException(lookupId));
                    }
                }
                return true;
            }
        }
        //
        internal IAsyncResult BeginTryReceive(MsmqInputMessage msmqMessage, TimeSpan timeout, MsmqTransactionMode transactionMode, AsyncCallback callback, object state)
        {
            if (this.receiveParameters.ExactlyOnce || this.queue is ILockingQueue)
                return new TryTransactedReceiveAsyncResult(this, msmqMessage, timeout, transactionMode, callback, state);
            else
                return new TryNonTransactedReceiveAsyncResult(this, msmqMessage, timeout, callback, state);
        }
        //
        internal bool EndTryReceive(IAsyncResult result, out MsmqInputMessage msmqMessage, out MsmqMessageProperty msmqProperty)
        {
            msmqMessage = null;
            msmqProperty = null;

            if (null == result)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");

            if (this.receiveParameters.ExactlyOnce)
            {
                TryTransactedReceiveAsyncResult receiveResult = result as TryTransactedReceiveAsyncResult;
                if (null == receiveResult)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.InvalidAsyncResult));
                return TryTransactedReceiveAsyncResult.End(receiveResult, out msmqMessage, out msmqProperty);
            }
            else
            {
                TryNonTransactedReceiveAsyncResult receiveResult = result as TryNonTransactedReceiveAsyncResult;
                if (null == receiveResult)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.InvalidAsyncResult));
                return TryNonTransactedReceiveAsyncResult.End(receiveResult, out msmqMessage, out msmqProperty);
            }
        }

        // TryReceiveAsyncResult (tx version)
        class TryTransactedReceiveAsyncResult : AsyncResult
        {
            bool expired;
            MsmqReceiveHelper receiver;
            TimeoutHelper timeoutHelper;
            Transaction txCurrent;
            MsmqInputMessage msmqMessage;
            MsmqMessageProperty messageProperty;
            MsmqTransactionMode transactionMode;
            static Action<object> onComplete = new Action<object>(OnComplete);

            internal TryTransactedReceiveAsyncResult(MsmqReceiveHelper receiver, MsmqInputMessage msmqMessage,
                TimeSpan timeout, MsmqTransactionMode transactionMode, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.timeoutHelper = new TimeoutHelper(timeout);
                this.txCurrent = Transaction.Current;
                this.receiver = receiver;
                this.msmqMessage = msmqMessage;
                this.transactionMode = transactionMode;
                ActionItem.Schedule(onComplete, this);
            }

            static void OnComplete(object parameter)
            {
                TryTransactedReceiveAsyncResult result = parameter as TryTransactedReceiveAsyncResult;
                Transaction savedTransaction = Transaction.Current;
                Transaction.Current = result.txCurrent;
                try
                {
                    Exception ex = null;
                    try
                    {
                        result.expired = !result.receiver.TryReceive(result.msmqMessage, result.timeoutHelper.RemainingTime(), result.transactionMode, out result.messageProperty);
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                            throw;
                        ex = e;
                    }
                    result.Complete(false, ex);
                }
                finally
                {
                    Transaction.Current = savedTransaction;
                }
            }

            internal static bool End(IAsyncResult result, out MsmqInputMessage msmqMessage, out MsmqMessageProperty property)
            {
                TryTransactedReceiveAsyncResult receiveResult = AsyncResult.End<TryTransactedReceiveAsyncResult>(result);
                msmqMessage = receiveResult.msmqMessage;
                property = receiveResult.messageProperty;
                return !receiveResult.expired;
            }
        }

        // TryReceiveAsyncResult (non-tx version)
        class TryNonTransactedReceiveAsyncResult : AsyncResult
        {
            MsmqQueue.ReceiveResult receiveResult;
            MsmqReceiveHelper receiver;
            MsmqInputMessage msmqMessage;
            static AsyncCallback onCompleteStatic = Fx.ThunkCallback(new AsyncCallback(OnCompleteStatic));


            internal TryNonTransactedReceiveAsyncResult(MsmqReceiveHelper receiver, MsmqInputMessage msmqMessage, TimeSpan timeout, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.receiver = receiver;
                this.msmqMessage = msmqMessage;
                receiver.Queue.BeginTryReceive(msmqMessage, timeout, onCompleteStatic, this);
            }

            static void OnCompleteStatic(IAsyncResult result)
            {
                (result.AsyncState as TryNonTransactedReceiveAsyncResult).OnComplete(result);
            }

            void OnComplete(IAsyncResult result)
            {
                Exception ex = null;
                try
                {
                    receiveResult = receiver.Queue.EndTryReceive(result);
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                        throw;
                    ex = e;
                }
                Complete(result.CompletedSynchronously, ex);
            }

            internal static bool End(IAsyncResult result, out MsmqInputMessage msmqMessage, out MsmqMessageProperty property)
            {
                TryNonTransactedReceiveAsyncResult asyncResult = AsyncResult.End<TryNonTransactedReceiveAsyncResult>(result);
                msmqMessage = asyncResult.msmqMessage;
                property = null;
                if (MsmqQueue.ReceiveResult.Timeout == asyncResult.receiveResult)
                    return false;
                else if (MsmqQueue.ReceiveResult.OperationCancelled == asyncResult.receiveResult)
                    return true;
                else
                {
                    property = new MsmqMessageProperty(msmqMessage);
                    return true;
                }
            }
        }

        // WaitForMessageAsyncResult
        class WaitForMessageAsyncResult : AsyncResult
        {
            MsmqQueue msmqQueue;
            MsmqEmptyMessage msmqMessage;
            bool successResult;
            static AsyncCallback onCompleteStatic = Fx.ThunkCallback(new AsyncCallback(OnCompleteStatic));

            public WaitForMessageAsyncResult(MsmqQueue msmqQueue, TimeSpan timeout, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.msmqMessage = new MsmqEmptyMessage();
                this.msmqQueue = msmqQueue;
                this.msmqQueue.BeginPeek(this.msmqMessage, timeout, onCompleteStatic, this);
            }

            static void OnCompleteStatic(IAsyncResult result)
            {
                ((WaitForMessageAsyncResult)result.AsyncState).OnComplete(result);
            }

            void OnComplete(IAsyncResult result)
            {
                this.msmqMessage.Dispose();
                MsmqQueue.ReceiveResult receiveResult = MsmqQueue.ReceiveResult.Unknown;
                Exception completionException = null;
                try
                {
                    receiveResult = this.msmqQueue.EndPeek(result);
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                        throw;
                    completionException = e;
                }

                this.successResult = receiveResult != MsmqQueue.ReceiveResult.Timeout;
                base.Complete(result.CompletedSynchronously, completionException);
            }

            public static bool End(IAsyncResult result)
            {
                WaitForMessageAsyncResult thisPtr = AsyncResult.End<WaitForMessageAsyncResult>(result);
                return thisPtr.successResult;
            }
        }
    }
}