File: ReliableRequestSessionChannel.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 (1164 lines) | stat: -rw-r--r-- 42,615 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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
    using System.Runtime;
    using System.Threading;
    using System.Xml;
    using System.ServiceModel.Diagnostics.Application;

    sealed class ReliableRequestSessionChannel : RequestChannel, IRequestSessionChannel
    {
        IClientReliableChannelBinder binder;
        ChannelParameterCollection channelParameters;
        ReliableRequestor closeRequestor;
        ReliableOutputConnection connection;
        bool isLastKnown = false;
        Exception maxRetryCountException = null;
        static AsyncCallback onPollingComplete = Fx.ThunkCallback(new AsyncCallback(OnPollingComplete));
        SequenceRangeCollection ranges = SequenceRangeCollection.Empty;
        Guard replyAckConsistencyGuard;
        ClientReliableSession session;
        IReliableFactorySettings settings;
        InterruptibleWaitObject shutdownHandle;
        ReliableRequestor terminateRequestor;

        public ReliableRequestSessionChannel(
            ChannelManagerBase factory,
            IReliableFactorySettings settings,
            IClientReliableChannelBinder binder,
            FaultHelper faultHelper,
            LateBoundChannelParameterCollection channelParameters,
            UniqueId inputID)
            : base(factory, binder.RemoteAddress, binder.Via, true)
        {
            this.settings = settings;
            this.binder = binder;
            this.session = new ClientReliableSession(this, settings, binder, faultHelper, inputID);
            this.session.PollingCallback = this.PollingCallback;
            this.session.UnblockChannelCloseCallback = this.UnblockClose;

            if (this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
            {
                this.shutdownHandle = new InterruptibleWaitObject(false);
            }
            else
            {
                this.replyAckConsistencyGuard = new Guard(Int32.MaxValue);
            }

            this.binder.Faulted += OnBinderFaulted;
            this.binder.OnException += OnBinderException;

            this.channelParameters = channelParameters;
            channelParameters.SetChannel(this);
        }

        public IOutputSession Session
        {
            get
            {
                return this.session;
            }
        }

        void AddAcknowledgementHeader(Message message, bool force)
        {
            if (this.ranges.Count == 0)
            {
                return;
            }

            WsrmUtilities.AddAcknowledgementHeader(this.settings.ReliableMessagingVersion, message,
                this.session.InputID, this.ranges, this.isLastKnown);
        }

        IAsyncResult BeginCloseBinder(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return this.binder.BeginClose(timeout, MaskingMode.Handled, callback, state);
        }

        IAsyncResult BeginTerminateSequence(TimeSpan timeout, AsyncCallback callback, object state)
        {
            this.CreateTerminateRequestor();
            return this.terminateRequestor.BeginRequest(timeout, callback, state);
        }

        void CloseSequence(TimeSpan timeout)
        {
            this.CreateCloseRequestor();
            Message closeReply = this.closeRequestor.Request(timeout);
            this.ProcessCloseOrTerminateReply(true, closeReply);
        }

        IAsyncResult BeginCloseSequence(TimeSpan timeout, AsyncCallback callback, object state)
        {
            this.CreateCloseRequestor();
            return this.closeRequestor.BeginRequest(timeout, callback, state);
        }

        void EndCloseSequence(IAsyncResult result)
        {
            Message closeReply = this.closeRequestor.EndRequest(result);
            this.ProcessCloseOrTerminateReply(true, closeReply);
        }

        void ConfigureRequestor(ReliableRequestor requestor)
        {
            ReliableMessagingVersion reliableMessagingVersion = this.settings.ReliableMessagingVersion;
            requestor.MessageVersion = this.settings.MessageVersion;
            requestor.Binder = this.binder;
            requestor.SetRequestResponsePattern();
            requestor.MessageHeader = new WsrmAcknowledgmentHeader(reliableMessagingVersion, this.session.InputID,
                this.ranges, true, -1);
        }

        Message CreateAckRequestedMessage()
        {
            Message request = WsrmUtilities.CreateAckRequestedMessage(this.settings.MessageVersion,
                this.settings.ReliableMessagingVersion, this.session.OutputID);
            this.AddAcknowledgementHeader(request, true);
            return request;
        }

        protected override IAsyncRequest CreateAsyncRequest(Message message, AsyncCallback callback, object state)
        {
            return new AsyncRequest(this, callback, state);
        }

        void CreateCloseRequestor()
        {
            RequestReliableRequestor temp = new RequestReliableRequestor();

            this.ConfigureRequestor(temp);
            temp.TimeoutString1Index = SR.TimeoutOnClose;
            temp.MessageAction = WsrmIndex.GetCloseSequenceActionHeader(
                this.settings.MessageVersion.Addressing);
            temp.MessageBody = new CloseSequence(this.session.OutputID, this.connection.Last);

            lock (this.ThisLock)
            {
                this.ThrowIfClosed();
                this.closeRequestor = temp;
            }
        }

        protected override IRequest CreateRequest(Message message)
        {
            return new SyncRequest(this);
        }

        void CreateTerminateRequestor()
        {
            RequestReliableRequestor temp = new RequestReliableRequestor();

            this.ConfigureRequestor(temp);
            temp.MessageAction = WsrmIndex.GetTerminateSequenceActionHeader(
                this.settings.MessageVersion.Addressing, this.settings.ReliableMessagingVersion);
            temp.MessageBody = new TerminateSequence(this.settings.ReliableMessagingVersion,
                this.session.OutputID, this.connection.Last);

            lock (this.ThisLock)
            {
                this.ThrowIfClosed();
                this.terminateRequestor = temp;
                this.session.CloseSession();
            }
        }

        void EndCloseBinder(IAsyncResult result)
        {
            this.binder.EndClose(result);
        }

        void EndTerminateSequence(IAsyncResult result)
        {
            Message terminateReply = this.terminateRequestor.EndRequest(result);

            if (terminateReply != null)
            {
                this.ProcessCloseOrTerminateReply(false, terminateReply);
            }
        }

        Exception GetInvalidAddException()
        {
            if (this.State == CommunicationState.Faulted)
                return this.GetTerminalException();
            else
                return this.CreateClosedException();
        }

        public override T GetProperty<T>()
        {
            if (typeof(T) == typeof(IRequestSessionChannel))
            {
                return (T)(object)this;
            }

            if (typeof(T) == typeof(ChannelParameterCollection))
            {
                return (T)(object)this.channelParameters;
            }

            T baseProperty = base.GetProperty<T>();

            if (baseProperty != null)
            {
                return baseProperty;
            }

            T innerProperty = this.binder.Channel.GetProperty<T>();
            if ((innerProperty == null) && (typeof(T) == typeof(FaultConverter)))
            {
                return (T)(object)FaultConverter.GetDefaultFaultConverter(this.settings.MessageVersion);
            }
            else
            {
                return innerProperty;
            }
        }

        protected override void OnAbort()
        {
            if (this.connection != null)
            {
                this.connection.Abort(this);
            }

            if (this.shutdownHandle != null)
            {
                this.shutdownHandle.Abort(this);
            }

            ReliableRequestor tempRequestor = this.closeRequestor;
            if (tempRequestor != null)
            {
                tempRequestor.Abort(this);
            }

            tempRequestor = this.terminateRequestor;
            if (tempRequestor != null)
            {
                tempRequestor.Abort(this);
            }

            this.session.Abort();
            base.OnAbort();
        }

        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            bool wsrm11 = this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11;

            OperationWithTimeoutBeginCallback[] beginCallbacks = new OperationWithTimeoutBeginCallback[] {
                this.connection.BeginClose,
                this.BeginWaitForShutdown,
                wsrm11 ? this.BeginCloseSequence : default(OperationWithTimeoutBeginCallback),
                this.BeginTerminateSequence,
                this.session.BeginClose,
                this.BeginCloseBinder
            };

            OperationEndCallback[] endCallbacks = new OperationEndCallback[] {
                this.connection.EndClose,
                this.EndWaitForShutdown,
                wsrm11 ? this.EndCloseSequence : default(OperationEndCallback),
                this.EndTerminateSequence,
                this.session.EndClose,
                this.EndCloseBinder
            };

            return OperationWithTimeoutComposer.BeginComposeAsyncOperations(timeout, beginCallbacks, endCallbacks, callback, state);
        }

        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return new ReliableChannelOpenAsyncResult(this.binder, this.session, timeout,
                callback, state);
        }

        void OnBinderException(IReliableChannelBinder sender, Exception exception)
        {
            if (exception is QuotaExceededException)
            {
                if (this.State == CommunicationState.Opening ||
                    this.State == CommunicationState.Opened ||
                    this.State == CommunicationState.Closing)
                {
                    this.session.OnLocalFault(exception, SequenceTerminatedFault.CreateQuotaExceededFault(this.session.OutputID), null);
                }
            }
            else
            {
                this.AddPendingException(exception);
            }
        }

        void OnBinderFaulted(IReliableChannelBinder sender, Exception exception)
        {
            this.binder.Abort();

            if (this.State == CommunicationState.Opening ||
                this.State == CommunicationState.Opened ||
                this.State == CommunicationState.Closing)
            {
                exception = new CommunicationException(SR.GetString(SR.EarlySecurityFaulted), exception);
                this.session.OnLocalFault(exception, (Message)null, null);
            }
        }

        protected override void OnClose(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            this.connection.Close(timeoutHelper.RemainingTime());
            this.WaitForShutdown(timeoutHelper.RemainingTime());

            if (this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
            {
                this.CloseSequence(timeoutHelper.RemainingTime());
            }

            this.TerminateSequence(timeoutHelper.RemainingTime());
            this.session.Close(timeoutHelper.RemainingTime());
            this.binder.Close(timeoutHelper.RemainingTime(), MaskingMode.Handled);
        }

        protected override void OnClosed()
        {
            base.OnClosed();
            this.binder.Faulted -= this.OnBinderFaulted;
        }

        IAsyncResult OnConnectionBeginSend(MessageAttemptInfo attemptInfo, TimeSpan timeout,
            bool maskUnhandledException, AsyncCallback callback, object state)
        {
            if (attemptInfo.RetryCount > this.settings.MaxRetryCount)
            {
                if (TD.MaxRetryCyclesExceededIsEnabled())
                {
                    TD.MaxRetryCyclesExceeded(SR.GetString(SR.MaximumRetryCountExceeded));
                }
                this.session.OnLocalFault(new CommunicationException(SR.GetString(SR.MaximumRetryCountExceeded), this.maxRetryCountException),
                       SequenceTerminatedFault.CreateMaxRetryCountExceededFault(this.session.OutputID), null);
                return new CompletedAsyncResult(callback, state);
            }
            else
            {
                this.session.OnLocalActivity();
                this.AddAcknowledgementHeader(attemptInfo.Message, false);

                ReliableBinderRequestAsyncResult result = new ReliableBinderRequestAsyncResult(callback, state);
                result.Binder = this.binder;
                result.MessageAttemptInfo = attemptInfo;
                result.MaskingMode = maskUnhandledException ? MaskingMode.Unhandled : MaskingMode.None;

                if (attemptInfo.RetryCount < this.settings.MaxRetryCount)
                {
                    result.MaskingMode |= MaskingMode.Handled;
                    result.SaveHandledException = false;
                }
                else
                {
                    result.SaveHandledException = true;
                }

                result.Begin(timeout);
                return result;
            }
        }

        void OnConnectionEndSend(IAsyncResult result)
        {
            if (result is CompletedAsyncResult)
            {
                CompletedAsyncResult.End(result);
            }
            else
            {
                Exception handledException;
                Message reply = ReliableBinderRequestAsyncResult.End(result, out handledException);
                ReliableBinderRequestAsyncResult requestResult = (ReliableBinderRequestAsyncResult)result;
                if (requestResult.MessageAttemptInfo.RetryCount == this.settings.MaxRetryCount)
                {
                    this.maxRetryCountException = handledException;
                }

                if (reply != null)
                {
                    this.ProcessReply(reply, (IReliableRequest)requestResult.MessageAttemptInfo.State,
                        requestResult.MessageAttemptInfo.GetSequenceNumber());
                }
            }
        }

        void OnConnectionSend(MessageAttemptInfo attemptInfo, TimeSpan timeout, bool maskUnhandledException)
        {
            using (attemptInfo.Message)
            {
                if (attemptInfo.RetryCount > this.settings.MaxRetryCount)
                {
                    if (TD.MaxRetryCyclesExceededIsEnabled())
                    {
                        TD.MaxRetryCyclesExceeded(SR.GetString(SR.MaximumRetryCountExceeded));
                    }
                    this.session.OnLocalFault(new CommunicationException(SR.GetString(SR.MaximumRetryCountExceeded), this.maxRetryCountException),
                        SequenceTerminatedFault.CreateMaxRetryCountExceededFault(this.session.OutputID), null);
                    return;
                }

                this.AddAcknowledgementHeader(attemptInfo.Message, false);
                this.session.OnLocalActivity();

                Message reply = null;
                MaskingMode maskingMode = maskUnhandledException ? MaskingMode.Unhandled : MaskingMode.None;

                if (attemptInfo.RetryCount < this.settings.MaxRetryCount)
                {
                    maskingMode |= MaskingMode.Handled;
                    reply = this.binder.Request(attemptInfo.Message, timeout, maskingMode);
                }
                else
                {
                    try
                    {
                        reply = this.binder.Request(attemptInfo.Message, timeout, maskingMode);
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                            throw;

                        if (this.binder.IsHandleable(e))
                        {
                            this.maxRetryCountException = e;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                if (reply != null)
                    ProcessReply(reply, (IReliableRequest)attemptInfo.State, attemptInfo.GetSequenceNumber());
            }
        }

        void OnConnectionSendAckRequested(TimeSpan timeout)
        {
            // do nothing, only replies to sequence messages alter the state of the reliable output connection
        }

        IAsyncResult OnConnectionBeginSendAckRequested(TimeSpan timeout, AsyncCallback callback, object state)
        {
            // do nothing, only replies to sequence messages alter the state of the reliable output connection
            return new CompletedAsyncResult(callback, state);
        }

        void OnConnectionEndSendAckRequested(IAsyncResult result)
        {
            CompletedAsyncResult.End(result);
        }

        void OnComponentFaulted(Exception faultException, WsrmFault fault)
        {
            this.session.OnLocalFault(faultException, fault, null);
        }

        void OnComponentException(Exception exception)
        {
            this.session.OnUnknownException(exception);
        }

        protected override void OnEndClose(IAsyncResult result)
        {
            OperationWithTimeoutComposer.EndComposeAsyncOperations(result);
        }

        protected override void OnEndOpen(IAsyncResult result)
        {
            ReliableChannelOpenAsyncResult.End(result);
        }

        protected override void OnFaulted()
        {
            this.session.OnFaulted();
            this.UnblockClose();
            base.OnFaulted();
        }

        protected override void OnOpen(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            bool throwing = true;

            try
            {
                this.binder.Open(timeoutHelper.RemainingTime());
                this.session.Open(timeoutHelper.RemainingTime());
                throwing = false;
            }
            finally
            {
                if (throwing)
                {
                    this.binder.Close(timeoutHelper.RemainingTime());
                }
            }
        }

        protected override void OnOpened()
        {
            base.OnOpened();
            this.connection = new ReliableOutputConnection(this.session.OutputID, this.settings.MaxTransferWindowSize,
                this.settings.MessageVersion, this.settings.ReliableMessagingVersion, this.session.InitiationTime,
                false, this.DefaultSendTimeout);
            this.connection.Faulted += OnComponentFaulted;
            this.connection.OnException += OnComponentException;
            this.connection.BeginSendHandler = OnConnectionBeginSend;
            this.connection.EndSendHandler = OnConnectionEndSend;
            this.connection.SendHandler = OnConnectionSend;
            this.connection.BeginSendAckRequestedHandler = OnConnectionBeginSendAckRequested;
            this.connection.EndSendAckRequestedHandler = OnConnectionEndSendAckRequested;
            this.connection.SendAckRequestedHandler = OnConnectionSendAckRequested;
        }

        static void OnPollingComplete(IAsyncResult result)
        {
            if (!result.CompletedSynchronously)
            {
                ReliableRequestSessionChannel channel = (ReliableRequestSessionChannel)result.AsyncState;
                channel.EndSendAckRequestedMessage(result);
            }
        }

        void PollingCallback()
        {
            IAsyncResult result = this.BeginSendAckRequestedMessage(this.DefaultSendTimeout, MaskingMode.All,
                onPollingComplete, this);

            if (result.CompletedSynchronously)
            {
                this.EndSendAckRequestedMessage(result);
            }
        }

        void ProcessCloseOrTerminateReply(bool close, Message reply)
        {
            if (reply == null)
            {
                // In the close case, the requestor is configured to throw TimeoutException instead of returning null.
                // In the terminate case, this value can be null, but the caller should not call this method.
                throw Fx.AssertAndThrow("Argument reply cannot be null.");
            }

            ReliableMessagingVersion reliableMessagingVersion = this.settings.ReliableMessagingVersion;

            if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
            {
                if (close)
                {
                    throw Fx.AssertAndThrow("Close does not exist in Feb2005.");
                }

                reply.Close();
            }
            else if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
            {
                WsrmMessageInfo info = this.closeRequestor.GetInfo();

                // Close - Final ack made it.
                // Terminate - UnknownSequence.
                // Either way, message has been verified and does not belong to this thread.
                if (info != null)
                {
                    return;
                }

                try
                {
                    info = WsrmMessageInfo.Get(this.settings.MessageVersion, reliableMessagingVersion,
                        this.binder.Channel, this.binder.GetInnerSession(), reply);
                    this.session.ProcessInfo(info, null, true);
                    this.session.VerifyDuplexProtocolElements(info, null, true);

                    WsrmFault fault = close
                        ? WsrmUtilities.ValidateCloseSequenceResponse(this.session, this.closeRequestor.MessageId, info,
                        this.connection.Last)
                        : WsrmUtilities.ValidateTerminateSequenceResponse(this.session, this.terminateRequestor.MessageId,
                        info, this.connection.Last);

                    if (fault != null)
                    {
                        this.session.OnLocalFault(null, fault, null);
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(fault.CreateException());
                    }
                }
                finally
                {
                    reply.Close();
                }
            }
            else
            {
                throw Fx.AssertAndThrow("Reliable messaging version not supported.");
            }
        }

        void ProcessReply(Message reply, IReliableRequest request, Int64 requestSequenceNumber)
        {
            WsrmMessageInfo messageInfo = WsrmMessageInfo.Get(this.settings.MessageVersion,
                this.settings.ReliableMessagingVersion, this.binder.Channel, this.binder.GetInnerSession(), reply);

            if (!this.session.ProcessInfo(messageInfo, null))
                return;

            if (!this.session.VerifyDuplexProtocolElements(messageInfo, null))
                return;

            bool wsrm11 = this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11;

            if (messageInfo.WsrmHeaderFault != null)
            {
                // Close message now, going to stop processing in all cases.
                messageInfo.Message.Close();

                if (!(messageInfo.WsrmHeaderFault is UnknownSequenceFault))
                {
                    throw Fx.AssertAndThrow("Fault must be UnknownSequence fault.");
                }

                if (this.terminateRequestor == null)
                {
                    throw Fx.AssertAndThrow("If we start getting UnknownSequence, terminateRequestor cannot be null.");
                }

                this.terminateRequestor.SetInfo(messageInfo);

                return;
            }

            if (messageInfo.AcknowledgementInfo == null)
            {
                WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(this.session.InputID,
                    SR.GetString(SR.SequenceTerminatedReplyMissingAcknowledgement),
                    SR.GetString(SR.ReplyMissingAcknowledgement));
                messageInfo.Message.Close();
                this.session.OnLocalFault(fault.CreateException(), fault, null);
                return;
            }

            if (wsrm11 && (messageInfo.TerminateSequenceInfo != null))
            {
                UniqueId faultId = (messageInfo.TerminateSequenceInfo.Identifier == this.session.OutputID)
                    ? this.session.InputID
                    : this.session.OutputID;

                WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(faultId,
                    SR.GetString(SR.SequenceTerminatedUnsupportedTerminateSequence),
                    SR.GetString(SR.UnsupportedTerminateSequenceExceptionString));
                messageInfo.Message.Close();
                this.session.OnLocalFault(fault.CreateException(), fault, null);
                return;
            }
            else if (wsrm11 && messageInfo.AcknowledgementInfo.Final)
            {
                // Close message now, going to stop processing in all cases.
                messageInfo.Message.Close();

                if (this.closeRequestor == null)
                {
                    // Remote endpoint signaled Close, this is not allowed so we fault.
                    string exceptionString = SR.GetString(SR.UnsupportedCloseExceptionString);
                    string faultString = SR.GetString(SR.SequenceTerminatedUnsupportedClose);

                    WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(this.session.OutputID, faultString,
                        exceptionString);
                    this.session.OnLocalFault(fault.CreateException(), fault, null);
                }
                else
                {
                    WsrmFault fault = WsrmUtilities.ValidateFinalAck(this.session, messageInfo, this.connection.Last);

                    if (fault == null)
                    {
                        // Received valid final ack after sending Close, inform the close thread.
                        this.closeRequestor.SetInfo(messageInfo);
                    }
                    else
                    {
                        // Received invalid final ack after sending Close, fault.
                        this.session.OnLocalFault(fault.CreateException(), fault, null);
                    }
                }

                return;
            }

            int bufferRemaining = -1;

            if (this.settings.FlowControlEnabled)
                bufferRemaining = messageInfo.AcknowledgementInfo.BufferRemaining;

            // We accept no more than MaxSequenceRanges ranges to limit the serialized ack size and
            // the amount of memory taken up by the ack ranges. Since request reply uses the presence of
            // a reply as an acknowledgement we cannot call ProcessTransferred (which stops retrying the
            // request) if we intend to drop the message. This means the limit is not strict since we do
            // not check for the limit and merge the ranges atomically. The limit + the number of
            // concurrent threads is a sufficient mitigation.
            if ((messageInfo.SequencedMessageInfo != null) &&
                !ReliableInputConnection.CanMerge(messageInfo.SequencedMessageInfo.SequenceNumber, this.ranges))
            {
                messageInfo.Message.Close();
                return;
            }

            bool exitGuard = this.replyAckConsistencyGuard != null ? this.replyAckConsistencyGuard.Enter() : false;

            try
            {
                this.connection.ProcessTransferred(requestSequenceNumber,
                    messageInfo.AcknowledgementInfo.Ranges, bufferRemaining);

                this.session.OnRemoteActivity(this.connection.Strategy.QuotaRemaining == 0);

                if (messageInfo.SequencedMessageInfo != null)
                {
                    lock (this.ThisLock)
                    {
                        this.ranges = this.ranges.MergeWith(messageInfo.SequencedMessageInfo.SequenceNumber);
                    }
                }
            }
            finally
            {
                if (exitGuard)
                {
                    this.replyAckConsistencyGuard.Exit();
                }
            }

            if (request != null)
            {
                if (WsrmUtilities.IsWsrmAction(this.settings.ReliableMessagingVersion, messageInfo.Action))
                {
                    messageInfo.Message.Close();
                    request.Set(null);
                }
                else
                {
                    request.Set(messageInfo.Message);
                }
            }

            // The termination mechanism in the TerminateSequence fails with RequestReply.
            // Since the ack ranges are updated after ProcessTransferred is called and
            // ProcessTransferred potentially signals the Termination process, this channel 
            // winds up sending a message with the ack for last message missing.
            // Thus we send the termination after we update the ranges.

            if ((this.shutdownHandle != null) && this.connection.CheckForTermination())
            {
                this.shutdownHandle.Set();
            }

            if (request != null)
                request.Complete();
        }

        IAsyncResult BeginSendAckRequestedMessage(TimeSpan timeout, MaskingMode maskingMode, AsyncCallback callback,
            object state)
        {
            this.session.OnLocalActivity();
            ReliableBinderRequestAsyncResult requestResult = new ReliableBinderRequestAsyncResult(callback, state);
            requestResult.Binder = this.binder;
            requestResult.MaskingMode = maskingMode;
            requestResult.Message = this.CreateAckRequestedMessage();
            requestResult.Begin(timeout);

            return requestResult;
        }

        void EndSendAckRequestedMessage(IAsyncResult result)
        {
            Message reply = ReliableBinderRequestAsyncResult.End(result);

            if (reply != null)
            {
                this.ProcessReply(reply, null, 0);
            }
        }

        void TerminateSequence(TimeSpan timeout)
        {
            this.CreateTerminateRequestor();
            Message terminateReply = this.terminateRequestor.Request(timeout);

            if (terminateReply != null)
            {
                this.ProcessCloseOrTerminateReply(false, terminateReply);
            }
        }

        void UnblockClose()
        {
            FaultPendingRequests();

            if (this.connection != null)
            {
                this.connection.Fault(this);
            }

            if (this.shutdownHandle != null)
            {
                this.shutdownHandle.Fault(this);
            }

            ReliableRequestor tempRequestor = this.closeRequestor;
            if (tempRequestor != null)
            {
                tempRequestor.Fault(this);
            }

            tempRequestor = this.terminateRequestor;
            if (tempRequestor != null)
            {
                tempRequestor.Fault(this);
            }
        }

        void WaitForShutdown(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            if (this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
            {
                this.shutdownHandle.Wait(timeoutHelper.RemainingTime());
            }
            else
            {
                this.isLastKnown = true;

                // We already closed the connection so we know everything was acknowledged.
                // Make sure the reply acknowledgement ranges are current.
                this.replyAckConsistencyGuard.Close(timeoutHelper.RemainingTime());
            }
        }

        IAsyncResult BeginWaitForShutdown(TimeSpan timeout, AsyncCallback callback, object state)
        {
            if (this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
            {
                return this.shutdownHandle.BeginWait(timeout, callback, state);
            }
            else
            {
                this.isLastKnown = true;

                // We already closed the connection so we know everything was acknowledged.
                // Make sure the reply acknowledgement ranges are current.
                return this.replyAckConsistencyGuard.BeginClose(timeout, callback, state);
            }
        }

        void EndWaitForShutdown(IAsyncResult result)
        {
            if (this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
            {
                this.shutdownHandle.EndWait(result);
            }
            else
            {
                this.replyAckConsistencyGuard.EndClose(result);
            }
        }

        interface IReliableRequest : IRequestBase
        {
            void Set(Message reply);
            void Complete();
        }

        class SyncRequest : IReliableRequest, IRequest
        {
            bool aborted = false;
            bool completed = false;
            ManualResetEvent completedHandle;
            bool faulted = false;
            TimeSpan originalTimeout;
            Message reply;
            ReliableRequestSessionChannel parent;
            object thisLock = new object();

            public SyncRequest(ReliableRequestSessionChannel parent)
            {
                this.parent = parent;
            }

            object ThisLock
            {
                get
                {
                    return this.thisLock;
                }
            }

            public void Abort(RequestChannel channel)
            {
                lock (this.ThisLock)
                {
                    if (!this.completed)
                    {
                        this.aborted = true;
                        this.completed = true;

                        if (this.completedHandle != null)
                            this.completedHandle.Set();
                    }
                }
            }

            public void Fault(RequestChannel channel)
            {
                lock (this.ThisLock)
                {
                    if (!this.completed)
                    {
                        this.faulted = true;
                        this.completed = true;

                        if (this.completedHandle != null)
                            this.completedHandle.Set();
                    }
                }
            }

            public void Complete()
            {
            }

            public void SendRequest(Message message, TimeSpan timeout)
            {
                this.originalTimeout = timeout;
                if (!parent.connection.AddMessage(message, timeout, this))
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.parent.GetInvalidAddException());
            }

            public void Set(Message reply)
            {
                lock (this.ThisLock)
                {
                    if (!this.completed)
                    {
                        this.reply = reply;
                        this.completed = true;

                        if (this.completedHandle != null)
                            this.completedHandle.Set();

                        return;
                    }
                }
                if (reply != null)
                {
                    reply.Close();
                }
            }

            public Message WaitForReply(TimeSpan timeout)
            {
                bool throwing = true;

                try
                {
                    bool expired = false;

                    if (!this.completed)
                    {
                        bool wait = false;

                        lock (this.ThisLock)
                        {
                            if (!this.completed)
                            {
                                wait = true;
                                this.completedHandle = new ManualResetEvent(false);
                            }
                        }

                        if (wait)
                        {
                            expired = !TimeoutHelper.WaitOne(this.completedHandle, timeout);

                            lock (this.ThisLock)
                            {
                                if (!this.completed)
                                {
                                    this.completed = true;
                                }
                                else
                                {
                                    expired = false;
                                }
                            }

                            this.completedHandle.Close();
                        }
                    }

                    if (this.aborted)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.parent.CreateClosedException());
                    }
                    else if (this.faulted)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.parent.GetTerminalException());
                    }
                    else if (expired)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.GetString(SR.TimeoutOnRequest, this.originalTimeout)));
                    }
                    else
                    {
                        throwing = false;
                        return this.reply;
                    }
                }
                finally
                {
                    if (throwing)
                    {
                        WsrmFault fault = SequenceTerminatedFault.CreateCommunicationFault(this.parent.session.InputID,
                            SR.GetString(SR.SequenceTerminatedReliableRequestThrew), null);
                        this.parent.session.OnLocalFault(null, fault, null);
                        if (this.completedHandle != null)
                            this.completedHandle.Close();
                    }
                }
            }

            public void OnReleaseRequest()
            {                
            }
        }

        class AsyncRequest : AsyncResult, IReliableRequest, IAsyncRequest
        {
            bool completed = false;
            ReliableRequestSessionChannel parent;
            Message reply;
            bool set = false;
            object thisLock = new object();

            public AsyncRequest(ReliableRequestSessionChannel parent, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.parent = parent;
            }

            object ThisLock
            {
                get
                {
                    return this.thisLock;
                }
            }

            public void Abort(RequestChannel channel)
            {
                if (this.ShouldComplete())
                {
                    this.Complete(false, parent.CreateClosedException());
                }
            }

            public void Fault(RequestChannel channel)
            {
                if (this.ShouldComplete())
                {
                    this.Complete(false, parent.GetTerminalException());
                }
            }

            void AddCompleted(IAsyncResult result)
            {
                Exception completeException = null;

                try
                {
                    if (!parent.connection.EndAddMessage(result))
                        completeException = this.parent.GetInvalidAddException();
                }
#pragma warning suppress 56500 // covered by FxCOP
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                        throw;

                    completeException = e;
                }

                if (completeException != null && this.ShouldComplete())
                    this.Complete(result.CompletedSynchronously, completeException);
            }

            public void BeginSendRequest(Message message, TimeSpan timeout)
            {
                parent.connection.BeginAddMessage(message, timeout, this, Fx.ThunkCallback(new AsyncCallback(AddCompleted)), null);
            }

            public void Complete()
            {
                if (this.ShouldComplete())
                {
                    this.Complete(false, null);
                }
            }

            public Message End()
            {
                AsyncResult.End<AsyncRequest>(this);
                return this.reply;
            }

            public void Set(Message reply)
            {
                lock (this.ThisLock)
                {
                    if (!this.set)
                    {
                        this.reply = reply;
                        this.set = true;
                        return;
                    }
                }

                if (reply != null)
                {
                    reply.Close();
                }
            }

            bool ShouldComplete()
            {
                lock (this.ThisLock)
                {
                    if (this.completed)
                    {
                        return false;
                    }

                    this.completed = true;
                }

                return true;
            }

            public void OnReleaseRequest()
            {                
            }
        }
    }
}