summaryrefslogtreecommitdiff
path: root/csharp/src/Ice/OutgoingAsync.cs
blob: cc119f6a7dd853a500d1e6c2f0acdc09441e4fe4 (plain)
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
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
// **********************************************************************
//
// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

namespace IceInternal
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Threading;

    public class OutgoingAsyncBase : AsyncResultI
    {
        public virtual Ice.AsyncCallback sent()
        {
            return sent(true);
        }

        public virtual Ice.AsyncCallback completed(Ice.Exception ex)
        {
            return finished(ex);
        }

        public virtual Ice.AsyncCallback completed()
        {
            Debug.Assert(false); // Must be implemented by classes that handle responses
            return null;
        }

        public void attachRemoteObserver(Ice.ConnectionInfo info, Ice.Endpoint endpt, int requestId)
        {
            if(observer_ != null)
            {
                int size = os_.size() - Protocol.headerSize - 4;
                childObserver_ = getObserver().getRemoteObserver(info, endpt, requestId, size);
                if(childObserver_ != null)
                {
                    childObserver_.attach();
                }
            }
        }

        public void attachCollocatedObserver(Ice.ObjectAdapter adapter, int requestId)
        {
            if(observer_ != null)
            {
                int size = os_.size() - Protocol.headerSize - 4;
                childObserver_ = getObserver().getCollocatedObserver(adapter, requestId, size);
                if(childObserver_ != null)
                {
                    childObserver_.attach();
                }
            }
        }

        public Ice.OutputStream getOs()
        {
            return os_;
        }

        public virtual Ice.InputStream getIs()
        {
            return null; // Must be implemented by classes that handle responses
        }

        protected OutgoingAsyncBase(Ice.Communicator com, Instance instance, string op, object cookie) :
            base(com, instance, op, cookie)
        {
            os_ = new Ice.OutputStream(instance, Ice.Util.currentProtocolEncoding);
        }

        protected OutgoingAsyncBase(Ice.Communicator com, Instance instance, string op, object cookie,
                                    Ice.OutputStream os) :
            base(com, instance, op, cookie)
        {
            os_ = os;
        }

        protected new Ice.AsyncCallback sent(bool done)
        {
            if(done)
            {
                if(childObserver_ != null)
                {
                    childObserver_.detach();
                    childObserver_ = null;
                }
            }
            return base.sent(done);
        }

        protected new Ice.AsyncCallback finished(Ice.Exception ex)
        {
            if(childObserver_ != null)
            {
                childObserver_.failed(ex.ice_id());
                childObserver_.detach();
                childObserver_ = null;
            }
            return base.finished(ex);
        }

        protected Ice.OutputStream os_;
        protected Ice.Instrumentation.ChildInvocationObserver childObserver_;
    }

    //
    // Base class for proxy based invocations. This class handles the
    // retry for proxy invocations. It also ensures the child observer is
    // correct notified of failures and make sure the retry task is
    // correctly canceled when the invocation completes.
    //
    public abstract class ProxyOutgoingAsyncBase : OutgoingAsyncBase, TimerTask
    {
        public static ProxyOutgoingAsyncBase check(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation)
        {
            return ProxyOutgoingAsyncBase.check<ProxyOutgoingAsyncBase>(r, prx, operation);
        }

        public abstract bool invokeRemote(Ice.ConnectionI con, bool compress, bool resp, out Ice.AsyncCallback cb);

        public abstract bool invokeCollocated(CollocatedRequestHandler handler, out Ice.AsyncCallback cb);

        public override Ice.ObjectPrx getProxy()
        {
            return proxy_;
        }

        public override Ice.AsyncCallback completed(Ice.Exception exc)
        {
            if(childObserver_ != null)
            {
                childObserver_.failed(exc.ice_id());
                childObserver_.detach();
                childObserver_ = null;
            }

            cachedConnection_ = null;
            if(proxy_.reference__().getInvocationTimeout() == -2)
            {
                instance_.timer().cancel(this);
            }

            //
            // NOTE: at this point, synchronization isn't needed, no other threads should be
            // calling on the callback.
            //
            try
            {
                //
                // It's important to let the retry queue do the retry even if
                // the retry interval is 0. This method can be called with the
                // connection locked so we can't just retry here.
                //
                instance_.retryQueue().add(this, handleException(exc));
                return null;
            }
            catch(Ice.Exception ex)
            {
                return finished(ex); // No retries, we're done
            }
        }

        public void retryException(Ice.Exception ex)
        {
            try
            {
                //
                // It's important to let the retry queue do the retry. This is
                // called from the connect request handler and the retry might
                // require could end up waiting for the flush of the
                // connection to be done.
                //
                proxy_.updateRequestHandler__(handler_, null); // Clear request handler and always retry.
                instance_.retryQueue().add(this, 0);
            }
            catch(Ice.Exception exc)
            {
                Ice.AsyncCallback cb = completed(exc);
                if(cb != null)
                {
                    invokeCompletedAsync(cb);
                }
            }
        }

        public override void cancelable(CancellationHandler handler)
        {
            if(proxy_.reference__().getInvocationTimeout() == -2 && cachedConnection_ != null)
            {
                int timeout = cachedConnection_.timeout();
                if(timeout > 0)
                {
                    instance_.timer().schedule(this, timeout);
                }
            }
            base.cancelable(handler);
        }

        public void retry()
        {
            invokeImpl(false);
        }

        public virtual void abort(Ice.Exception ex)
        {
            Debug.Assert(childObserver_ == null);
            Ice.AsyncCallback cb = finished(ex);
            if(cb != null)
            {
                invokeCompletedAsync(cb);
            }
            else if(ex is Ice.CommunicatorDestroyedException)
            {
                //
                // If it's a communicator destroyed exception, don't swallow
                // it but instead notify the user thread. Even if no callback
                // was provided.
                //
                throw ex;
            }
        }

        public void runTimerTask()
        {
            if(proxy_.reference__().getInvocationTimeout() == -2)
            {
                cancel(new Ice.ConnectionTimeoutException());
            }
            else
            {
                cancel(new Ice.InvocationTimeoutException());
            }
        }

        protected ProxyOutgoingAsyncBase(Ice.ObjectPrxHelperBase prx, string op, object cookie) :
            base(prx.ice_getCommunicator(), prx.reference__().getInstance(), op, cookie)
        {
            proxy_ = prx;
            mode_ = Ice.OperationMode.Normal;
            _cnt = 0;
            _sent = false;
        }

        protected ProxyOutgoingAsyncBase(Ice.ObjectPrxHelperBase prx, string op, object cookie, Ice.OutputStream os) :
            base(prx.ice_getCommunicator(), prx.reference__().getInstance(), op, cookie, os)
        {
            proxy_ = prx;
            mode_ = Ice.OperationMode.Normal;
            _cnt = 0;
            _sent = false;
        }

        protected static T check<T>(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation)
        {
            if(r != null && r.getProxy() != prx)
            {
                throw new System.ArgumentException("Proxy for call to end_" + operation +
                                                   " does not match proxy that was used to call corresponding begin_" +
                                                   operation + " method");
            }
            return check<T>(r, operation);
        }

        protected void invokeImpl(bool userThread)
        {
            try
            {
                if(userThread)
                {
                    int invocationTimeout = proxy_.reference__().getInvocationTimeout();
                    if(invocationTimeout > 0)
                    {
                        instance_.timer().schedule(this, invocationTimeout);
                    }
                }
                else // If not called from the user thread, it's called from the retry queue
                {
                    if(observer_ != null)
                    {
                        observer_.retried();
                    }
                }

                while(true)
                {
                    try
                    {
                        _sent = false;
                        handler_ = proxy_.getRequestHandler__();
                        Ice.AsyncCallback sentCallback;
                        if(handler_.sendAsyncRequest(this, out sentCallback))
                        {
                            if(userThread)
                            {
                                sentSynchronously_ = true;
                                if(sentCallback != null)
                                {
                                    invokeSent(sentCallback); // Call from the user thread.
                                }
                            }
                            else
                            {
                                if(sentCallback != null)
                                {
                                    invokeSentAsync(sentCallback); // Call from a client thread pool thread.
                                }
                            }
                        }
                        return; // We're done!
                    }
                    catch(RetryException)
                    {
                        proxy_.updateRequestHandler__(handler_, null); // Clear request handler and always retry.
                    }
                    catch(Ice.Exception ex)
                    {
                        if(childObserver_ != null)
                        {
                            childObserver_.failed(ex.ice_id());
                            childObserver_.detach();
                            childObserver_ = null;
                        }
                        int interval = handleException(ex);
                        if(interval > 0)
                        {
                            instance_.retryQueue().add(this, interval);
                            return;
                        }
                        else if(observer_ != null)
                        {
                            observer_.retried();
                        }
                    }
                }
            }
            catch(Ice.Exception ex)
            {
                //
                // If called from the user thread we re-throw, the exception
                // will be catch by the caller and abort() will be called.
                //
                if(userThread)
                {
                    throw ex;
                }
                Ice.AsyncCallback cb = finished(ex); // No retries, we're done
                if(cb != null)
                {
                    invokeCompletedAsync(cb);
                }
            }
        }

        protected new Ice.AsyncCallback sent(bool done)
        {
            _sent = true;
            if(done)
            {
                if(proxy_.reference__().getInvocationTimeout() != -1)
                {
                    instance_.timer().cancel(this);
                }
            }
            return base.sent(done);
        }

        protected new Ice.AsyncCallback finished(Ice.Exception ex)
        {
            if(proxy_.reference__().getInvocationTimeout() != -1)
            {
                instance_.timer().cancel(this);
            }
            return base.finished(ex);
        }

        protected new Ice.AsyncCallback finished(bool ok)
        {
            if(proxy_.reference__().getInvocationTimeout() != -1)
            {
                instance_.timer().cancel(this);
            }
            return base.finished(ok);
        }

        protected virtual int handleException(Ice.Exception exc)
        {
            return proxy_.handleException__(exc, handler_, mode_, _sent, ref _cnt);
        }

        protected Ice.ObjectPrxHelperBase proxy_;
        protected RequestHandler handler_;
        protected Ice.OperationMode mode_;

        private int _cnt;
        private bool _sent;
    }

    public class OutgoingAsync : ProxyOutgoingAsyncBase
    {
        public new static OutgoingAsync check(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation)
        {
            return ProxyOutgoingAsyncBase.check<OutgoingAsync>(r, prx, operation);
        }

        public OutgoingAsync(Ice.ObjectPrx prx, string operation, object cookie) :
            base((Ice.ObjectPrxHelperBase)prx, operation, cookie)
        {
            _encoding = Protocol.getCompatibleEncoding(proxy_.reference__().getEncoding());
            _is = null;
        }

        public OutgoingAsync(Ice.ObjectPrx prx, string operation, object cookie, Ice.InputStream istr,
                             Ice.OutputStream ostr) :
            base((Ice.ObjectPrxHelperBase)prx, operation, cookie, ostr)
        {
            _encoding = Protocol.getCompatibleEncoding(proxy_.reference__().getEncoding());
            _is = istr;
        }

        public void prepare(string operation, Ice.OperationMode mode, Dictionary<string, string> ctx,
                            bool explicitCtx, bool synchronous)
        {
            Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(proxy_.reference__().getProtocol()));

            mode_ = mode;
            _synchronous = synchronous;

            if(explicitCtx && ctx == null)
            {
                ctx = _emptyContext;
            }
            observer_ = ObserverHelper.get(proxy_, operation, ctx);

            switch(proxy_.reference__().getMode())
            {
                case Reference.Mode.ModeTwoway:
                case Reference.Mode.ModeOneway:
                case Reference.Mode.ModeDatagram:
                {
                    os_.writeBlob(Protocol.requestHdr);
                    break;
                }

                case Reference.Mode.ModeBatchOneway:
                case Reference.Mode.ModeBatchDatagram:
                {
                    proxy_.getBatchRequestQueue__().prepareBatchRequest(os_);
                    break;
                }
            }

            Reference rf = proxy_.reference__();

            rf.getIdentity().write__(os_);

            //
            // For compatibility with the old FacetPath.
            //
            string facet = rf.getFacet();
            if(facet == null || facet.Length == 0)
            {
                os_.writeStringSeq(null);
            }
            else
            {
                string[] facetPath = { facet };
                os_.writeStringSeq(facetPath);
            }

            os_.writeString(operation);

            os_.writeByte((byte)mode);

            if(ctx != null)
            {
                //
                // Explicit context
                //
                Ice.ContextHelper.write(os_, ctx);
            }
            else
            {
                //
                // Implicit context
                //
                Ice.ImplicitContextI implicitContext = rf.getInstance().getImplicitContext();
                Dictionary<string, string> prxContext = rf.getContext();

                if(implicitContext == null)
                {
                    Ice.ContextHelper.write(os_, prxContext);
                }
                else
                {
                    implicitContext.write(prxContext, os_);
                }
            }
        }

        public override Ice.AsyncCallback sent()
        {
            return sent(!proxy_.ice_isTwoway()); // done = true if not a two-way proxy (no response expected)
        }

        public override bool invokeRemote(Ice.ConnectionI con, bool compress, bool resp, out Ice.AsyncCallback sentCB)
        {
            cachedConnection_ = con;
            return con.sendAsyncRequest(this, compress, resp, 0, out sentCB);
        }

        public override bool invokeCollocated(CollocatedRequestHandler handler, out Ice.AsyncCallback sentCB)
        {
            // The stream cannot be cached if the proxy is not a twoway or there is an invocation timeout set.
            if(!proxy_.ice_isTwoway() || proxy_.reference__().getInvocationTimeout() != -1)
            {
                // Disable caching by marking the streams as cached!
                state_ |= StateCachedBuffers;
            }
            return handler.invokeAsyncRequest(this, 0, _synchronous, out sentCB);
        }

        public override void abort(Ice.Exception ex)
        {
            Reference.Mode mode = proxy_.reference__().getMode();
            if(mode == Reference.Mode.ModeBatchOneway || mode == Reference.Mode.ModeBatchDatagram)
            {
                proxy_.getBatchRequestQueue__().abortBatchRequest(os_);
            }

            base.abort(ex);
        }

        public void invoke()
        {
            Reference.Mode mode = proxy_.reference__().getMode();
            if(mode == Reference.Mode.ModeBatchOneway || mode == Reference.Mode.ModeBatchDatagram)
            {
                sentSynchronously_ = true;
                proxy_.getBatchRequestQueue__().finishBatchRequest(os_, proxy_, getOperation());
                finished(true);
                return; // Don't call sent/completed callback for batch AMI requests
            }

            //
            // NOTE: invokeImpl doesn't throw so this can be called from the
            // try block with the catch block calling abort() in case of an
            // exception.
            //
            invokeImpl(true); // userThread = true
        }

        override public Ice.AsyncCallback completed()
        {
            Debug.Assert(_is != null); // _is has been initialized prior to this call

            //
            // NOTE: this method is called from ConnectionI.parseMessage
            // with the connection locked. Therefore, it must not invoke
            // any user callbacks.
            //

            Debug.Assert(proxy_.ice_isTwoway()); // Can only be called for twoways.

            if(childObserver_ != null)
            {
                childObserver_.reply(_is.size() - Protocol.headerSize - 4);
                childObserver_.detach();
                childObserver_ = null;
            }

            byte replyStatus;
            try
            {
                replyStatus = _is.readByte();

                switch(replyStatus)
                {
                case ReplyStatus.replyOK:
                {
                    break;
                }

                case ReplyStatus.replyUserException:
                {
                    if(observer_ != null)
                    {
                        observer_.userException();
                    }
                    break;
                }

                case ReplyStatus.replyObjectNotExist:
                case ReplyStatus.replyFacetNotExist:
                case ReplyStatus.replyOperationNotExist:
                {
                    Ice.Identity id = new Ice.Identity();
                    id.read__(_is);

                    //
                    // For compatibility with the old FacetPath.
                    //
                    string[] facetPath = _is.readStringSeq();
                    string facet;
                    if(facetPath.Length > 0)
                    {
                        if(facetPath.Length > 1)
                        {
                            throw new Ice.MarshalException();
                        }
                        facet = facetPath[0];
                    }
                    else
                    {
                        facet = "";
                    }

                    string operation = _is.readString();

                    Ice.RequestFailedException ex = null;
                    switch(replyStatus)
                    {
                    case ReplyStatus.replyObjectNotExist:
                    {
                        ex = new Ice.ObjectNotExistException();
                        break;
                    }

                    case ReplyStatus.replyFacetNotExist:
                    {
                        ex = new Ice.FacetNotExistException();
                        break;
                    }

                    case ReplyStatus.replyOperationNotExist:
                    {
                        ex = new Ice.OperationNotExistException();
                        break;
                    }

                    default:
                    {
                        Debug.Assert(false);
                        break;
                    }
                    }

                    ex.id = id;
                    ex.facet = facet;
                    ex.operation = operation;
                    throw ex;
                }

                case ReplyStatus.replyUnknownException:
                case ReplyStatus.replyUnknownLocalException:
                case ReplyStatus.replyUnknownUserException:
                {
                    string unknown = _is.readString();

                    Ice.UnknownException ex = null;
                    switch(replyStatus)
                    {
                    case ReplyStatus.replyUnknownException:
                    {
                        ex = new Ice.UnknownException();
                        break;
                    }

                    case ReplyStatus.replyUnknownLocalException:
                    {
                        ex = new Ice.UnknownLocalException();
                        break;
                    }

                    case ReplyStatus.replyUnknownUserException:
                    {
                        ex = new Ice.UnknownUserException();
                        break;
                    }

                    default:
                    {
                        Debug.Assert(false);
                        break;
                    }
                    }

                    ex.unknown = unknown;
                    throw ex;
                }

                default:
                {
                    throw new Ice.UnknownReplyStatusException();
                }
                }

                return finished(replyStatus == ReplyStatus.replyOK);
            }
            catch(Ice.Exception ex)
            {
                return completed(ex);
            }
        }

        public Ice.OutputStream startWriteParams(Ice.FormatType format)
        {
            os_.startEncapsulation(_encoding, format);
            return os_;
        }

        public void endWriteParams()
        {
            os_.endEncapsulation();
        }

        public void writeEmptyParams()
        {
            os_.writeEmptyEncapsulation(_encoding);
        }

        public void writeParamEncaps(byte[] encaps)
        {
            if(encaps == null || encaps.Length == 0)
            {
                os_.writeEmptyEncapsulation(_encoding);
            }
            else
            {
                os_.writeEncapsulation(encaps);
            }
        }

        public Ice.InputStream startReadParams()
        {
            _is.startEncapsulation();
            return _is;
        }

        public void endReadParams()
        {
            _is.endEncapsulation();
        }

        public void readEmptyParams()
        {
            _is.skipEmptyEncapsulation();
        }

        public byte[] readParamEncaps()
        {
            Ice.EncodingVersion encoding;
            return _is.readEncapsulation(out encoding);
        }

        override public Ice.InputStream getIs()
        {
            // _is can already be initialized if the invocation is retried
            if(_is == null)
            {
                _is = new Ice.InputStream(instance_, Ice.Util.currentProtocolEncoding);
            }
            return _is;
        }

        public void throwUserException()
        {
            try
            {
                _is.startEncapsulation();
                _is.throwException(null);
            }
            catch(Ice.UserException ex)
            {
                _is.endEncapsulation();
                throw ex;
            }
        }

        public override void cacheMessageBuffers()
        {
            if(proxy_.reference__().getInstance().cacheMessageBuffers() > 0)
            {
                lock(this)
                {
                    if((state_ & StateCachedBuffers) > 0)
                    {
                        return;
                    }
                    state_ |= StateCachedBuffers;
                }

                if(_is != null)
                {
                    _is.reset();
                }
                os_.reset();

                proxy_.cacheMessageBuffers(_is, os_);

                _is = null;
                os_ = null;
            }
        }

        private Ice.EncodingVersion _encoding;
        private Ice.InputStream _is;

        //
        // If true this AMI request is being used for a generated synchronous invocation.
        //
        private bool _synchronous;

        private static Dictionary<string, string> _emptyContext = new Dictionary<string, string>();
    }

    public class CommunicatorFlushBatch : IceInternal.AsyncResultI
    {
        public static CommunicatorFlushBatch check(Ice.AsyncResult r, Ice.Communicator com, string operation)
        {
            if(r != null && r.getCommunicator() != com)
            {
                throw new System.ArgumentException("Communicator for call to end_" + operation +
                                                   " does not match communicator that was used to call " +
                                                   "corresponding begin_" + operation + " method");
            }
            return AsyncResultI.check<CommunicatorFlushBatch>(r, operation);
        }

        public CommunicatorFlushBatch(Ice.Communicator communicator, Instance instance, string op, object cookie) :
            base(communicator, instance, op, cookie)
        {

            observer_ = ObserverHelper.get(instance, op);

            //
            // _useCount is initialized to 1 to prevent premature callbacks.
            // The caller must invoke ready() after all flush requests have
            // been initiated.
            //
            _useCount = 1;
        }

        public void flushConnection(Ice.ConnectionI con)
        {
            lock(this)
            {
                ++_useCount;
            }

            try
            {
                Ice.AsyncCallback sentCB = null;
                FlushBatch flush = new FlushBatch(this);
                int batchRequestNum = con.getBatchRequestQueue().swap(flush.getOs());
                if(batchRequestNum == 0)
                {
                    flush.sent();
                }
                else
                {
                    con.sendAsyncRequest(flush, false, false, batchRequestNum, out sentCB);
                }
                Debug.Assert(sentCB == null);
            }
            catch(Ice.LocalException ex)
            {
                doCheck(false);
                throw ex;
            }
        }

        public void ready()
        {
            doCheck(true);
        }

        private void doCheck(bool userThread)
        {
            lock(this)
            {
                Debug.Assert(_useCount > 0);
                if(--_useCount > 0)
                {
                    return;
                }
            }

            Ice.AsyncCallback sentCB = sent(true);
            if(userThread)
            {
                sentSynchronously_ = true;
                if(sentCB != null)
                {
                    invokeSent(sentCB);
                }
            }
            else
            {
                if(sentCB != null)
                {
                    invokeSentAsync(sentCB);
                }
            }
        }

        class FlushBatch : OutgoingAsyncBase
        {
            public FlushBatch(CommunicatorFlushBatch outAsync) :
                base(outAsync.getCommunicator(), outAsync.instance_, outAsync.getOperation(), null)
            {
                _outAsync = outAsync;
            }

            public override Ice.AsyncCallback sent()
            {
                if(childObserver_ != null)
                {
                    childObserver_.detach();
                    childObserver_ = null;
                }
                _outAsync.doCheck(false);
                return null;
            }

            public override Ice.AsyncCallback completed(Ice.Exception ex)
            {
                if(childObserver_ != null)
                {
                    childObserver_.failed(ex.ice_id());
                    childObserver_.detach();
                    childObserver_ = null;
                }
                _outAsync.doCheck(false);
                return null;
            }

            protected override Ice.Instrumentation.InvocationObserver getObserver()
            {
                return _outAsync.getObserver();
            }

            private CommunicatorFlushBatch _outAsync;
        }
        private int _useCount;
    }


    public class ConnectionFlushBatch : OutgoingAsyncBase
    {
        public static ConnectionFlushBatch check(Ice.AsyncResult r, Ice.Connection con, string operation)
        {
            if(r != null && r.getConnection() != con)
            {
                throw new System.ArgumentException("Connection for call to end_" + operation +
                                                   " does not match connection that was used to call " +
                                                   "corresponding begin_" + operation + " method");
            }
            return AsyncResultI.check<ConnectionFlushBatch>(r, operation);
        }

        public ConnectionFlushBatch(Ice.ConnectionI con, Ice.Communicator communicator, Instance instance, string op,
                                    object cookie) :
            base(communicator, instance, op, cookie)
        {
            _connection = con;
        }

        public override Ice.Connection getConnection()
        {
            return _connection;
        }

        public void invoke()
        {
            try
            {
                int batchRequestNum = _connection.getBatchRequestQueue().swap(os_);

                bool isSent = false;
                Ice.AsyncCallback sentCB;
                if(batchRequestNum == 0)
                {
                    isSent = true;
                    sentCB = sent();
                }
                else
                {
                    isSent = _connection.sendAsyncRequest(this, false, false, batchRequestNum, out sentCB);
                }

                if(isSent)
                {
                    sentSynchronously_ = true;
                    if(sentCB != null)
                    {
                        invokeSent(sentCB);
                    }
                }
            }
            catch(RetryException ex)
            {
                Ice.AsyncCallback cb = completed(ex.get());
                if(cb != null)
                {
                    invokeCompletedAsync(cb);
                }
            }
            catch(Ice.Exception ex)
            {
                Ice.AsyncCallback cb = completed(ex);
                if(cb != null)
                {
                    invokeCompletedAsync(cb);
                }
            }
        }

        private Ice.ConnectionI _connection;
    }

    public class ProxyFlushBatch : ProxyOutgoingAsyncBase
    {
        public new static ProxyFlushBatch check(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation)
        {
            return ProxyOutgoingAsyncBase.check<ProxyFlushBatch>(r, prx, operation);
        }

        public ProxyFlushBatch(Ice.ObjectPrxHelperBase prx, string operation, object cookie) :
            base(prx, operation, cookie)
        {
            observer_ = ObserverHelper.get(prx, operation);
            _batchRequestNum = prx.getBatchRequestQueue__().swap(os_);
        }

        public override bool invokeRemote(Ice.ConnectionI con, bool compress, bool resp, out Ice.AsyncCallback sentCB)
        {
            if(_batchRequestNum == 0)
            {
                sentCB = sent();
                return true;
            }
            cachedConnection_ = con;
            return con.sendAsyncRequest(this, compress, false, _batchRequestNum, out sentCB);
        }

        public override bool invokeCollocated(CollocatedRequestHandler handler, out Ice.AsyncCallback sentCB)
        {
            if(_batchRequestNum == 0)
            {
                sentCB = sent();
                return true;
            }
            return handler.invokeAsyncRequest(this, _batchRequestNum, false, out sentCB);
        }

        public void invoke()
        {
            Protocol.checkSupportedProtocol(Protocol.getCompatibleProtocol(proxy_.reference__().getProtocol()));
            invokeImpl(true); // userThread = true
        }

        private int _batchRequestNum;
    }

    public class ProxyGetConnection : ProxyOutgoingAsyncBase, Ice.AsyncResult<Ice.Callback_Object_ice_getConnection>
    {
        public new static ProxyGetConnection check(Ice.AsyncResult r, Ice.ObjectPrx prx, string operation)
        {
            return ProxyOutgoingAsyncBase.check<ProxyGetConnection>(r, prx, operation);
        }

        public ProxyGetConnection(Ice.ObjectPrxHelperBase prx, string operation,
                                  ProxyTwowayCallback<Ice.Callback_Object_ice_getConnection> cb, object cookie) :
            base(prx, operation, cookie)
        {
            observer_ = ObserverHelper.get(prx, operation);
            _completed = cb;
        }

        public override bool invokeRemote(Ice.ConnectionI con, bool compress, bool resp, out Ice.AsyncCallback sentCB)
        {
            sentCB = null;
            cachedConnection_ = con;
            Ice.AsyncCallback cb = finished(true);
            if(cb != null)
            {
                invokeCompletedAsync(cb);
            }
            return true;
        }

        public override bool invokeCollocated(CollocatedRequestHandler handler, out Ice.AsyncCallback sentCB)
        {
            sentCB = null;
            Ice.AsyncCallback cb = finished(true);
            if(cb != null)
            {
                invokeCompletedAsync(cb);
            }
            return true;
        }

        public void invoke()
        {
            invokeImpl(true); // userThread = true
        }

        new public Ice.AsyncResult<Ice.Callback_Object_ice_getConnection> whenCompleted(Ice.ExceptionCallback excb)
        {
            base.whenCompleted(excb);
            return this;
        }

        virtual public Ice.AsyncResult<Ice.Callback_Object_ice_getConnection>
        whenCompleted(Ice.Callback_Object_ice_getConnection cb, Ice.ExceptionCallback excb)
        {
            if(cb == null && excb == null)
            {
                throw new System.ArgumentException("callback is null");
            }
            lock(this)
            {
                if(_responseCallback != null || exceptionCallback_ != null)
                {
                    throw new System.ArgumentException("callback already set");
                }
                _responseCallback = cb;
                exceptionCallback_ = excb;
            }
            setCompletedCallback(getCompletedCallback());
            return this;
        }

        new public Ice.AsyncResult<Ice.Callback_Object_ice_getConnection> whenSent(Ice.SentCallback cb)
        {
            base.whenSent(cb);
            return this;
        }

        protected override Ice.AsyncCallback getCompletedCallback()
        {
            return (Ice.AsyncResult result) => { _completed(this, _responseCallback, exceptionCallback_); };
        }

        private ProxyTwowayCallback<Ice.Callback_Object_ice_getConnection> _completed;
        private Ice.Callback_Object_ice_getConnection _responseCallback = null;
    }

    public abstract class OutgoingAsync<T> : OutgoingAsync, Ice.AsyncResult<T>
    {
        public OutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, object cookie) :
            base(prx, operation, cookie)
        {
        }

        public OutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, object cookie, Ice.InputStream iss,
                             Ice.OutputStream os) :
            base(prx, operation, cookie, iss, os)
        {
        }

        new public Ice.AsyncResult<T> whenCompleted(Ice.ExceptionCallback excb)
        {
            base.whenCompleted(excb);
            return this;
        }

        virtual public Ice.AsyncResult<T> whenCompleted(T cb, Ice.ExceptionCallback excb)
        {
            if(cb == null && excb == null)
            {
                throw new System.ArgumentException("callback is null");
            }
            lock(this)
            {
                if(responseCallback_ != null || exceptionCallback_ != null)
                {
                    throw new System.ArgumentException("callback already set");
                }
                responseCallback_ = cb;
                exceptionCallback_ = excb;
            }
            setCompletedCallback(getCompletedCallback());
            return this;
        }

        new public Ice.AsyncResult<T> whenSent(Ice.SentCallback cb)
        {
            base.whenSent(cb);
            return this;
        }

        protected T responseCallback_;
    }

    public class TwowayOutgoingAsync<T> : OutgoingAsync<T>
    {
        public TwowayOutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, ProxyTwowayCallback<T> cb,
                                   object cookie) :
            base(prx, operation, cookie)
        {
            Debug.Assert(cb != null);
            _completed = cb;
        }

        public TwowayOutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, ProxyTwowayCallback<T> cb,
                                   object cookie, Ice.InputStream iss, Ice.OutputStream os) :
            base(prx, operation, cookie, iss, os)
        {
            Debug.Assert(cb != null);
            _completed = cb;
        }

        override protected Ice.AsyncCallback getCompletedCallback()
        {
            return (Ice.AsyncResult result) => { _completed(this, responseCallback_, exceptionCallback_); };
        }

        private ProxyTwowayCallback<T> _completed;
    }

    public class OnewayOutgoingAsync<T> : OutgoingAsync<T>
    {
        public OnewayOutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, ProxyOnewayCallback<T> cb,
                                   object cookie) :
            base(prx, operation, cookie)
        {
            Debug.Assert(cb != null);
            _completed = cb;
        }

        public OnewayOutgoingAsync(Ice.ObjectPrxHelperBase prx, string operation, ProxyOnewayCallback<T> cb,
                                   object cookie, Ice.InputStream iss, Ice.OutputStream os) :
            base(prx, operation, cookie, iss, os)
        {
            Debug.Assert(cb != null);
            _completed = cb;
        }

        override protected Ice.AsyncCallback getCompletedCallback()
        {
            return (Ice.AsyncResult result) =>
            {
                try
                {
                    IceInternal.OutgoingAsync outAsync__ = (IceInternal.OutgoingAsync)result;
                    ((Ice.ObjectPrxHelperBase)(outAsync__.getProxy())).end__(outAsync__, outAsync__.getOperation());
                }
                catch(Ice.Exception ex__)
                {
                    if(exceptionCallback_ != null)
                    {
                        exceptionCallback_(ex__);
                    }
                    return;
                }
                _completed(responseCallback_);
            };
        }

        private ProxyOnewayCallback<T> _completed;
    }
}