Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ClientClassGenerator.cs « Description « ServiceModel « System « System.ServiceModel « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5712afbf7bad20d83f766653f9fbe00cd30795b7 (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
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

namespace System.ServiceModel.Description
{
    using System;
    using System.CodeDom;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Globalization;
    using System.Reflection;
    using System.Runtime;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Threading;

    class ClientClassGenerator : IServiceContractGenerationExtension
    {
        bool tryAddHelperMethod = false;
        bool generateEventAsyncMethods = false;

        internal ClientClassGenerator(bool tryAddHelperMethod)
            : this(tryAddHelperMethod, false)
        {
        }

        internal ClientClassGenerator(bool tryAddHelperMethod, bool generateEventAsyncMethods)
        {
            this.tryAddHelperMethod = tryAddHelperMethod;
            this.generateEventAsyncMethods = generateEventAsyncMethods;
        }

        static Type clientBaseType = typeof(ClientBase<>);
        static Type duplexClientBaseType = typeof(DuplexClientBase<>);
        static Type instanceContextType = typeof(InstanceContext);
        static Type objectType = typeof(object);
        static Type objectArrayType = typeof(object[]);
        static Type exceptionType = typeof(Exception);
        static Type boolType = typeof(bool);
        static Type stringType = typeof(string);
        static Type endpointAddressType = typeof(EndpointAddress);
        static Type uriType = typeof(Uri);
        static Type bindingType = typeof(Binding);
        static Type sendOrPostCallbackType = typeof(SendOrPostCallback);
        static Type asyncCompletedEventArgsType = typeof(AsyncCompletedEventArgs);
        static Type eventHandlerType = typeof(EventHandler<>);
        static Type voidType = typeof(void);
        static Type asyncResultType = typeof(IAsyncResult);
        static Type asyncCallbackType = typeof(AsyncCallback);
        
        static CodeTypeReference voidTypeRef = new CodeTypeReference(typeof(void));
        static CodeTypeReference asyncResultTypeRef = new CodeTypeReference(typeof(IAsyncResult));

        static string inputInstanceName = "callbackInstance";
        static string invokeAsyncCompletedEventArgsTypeName = "InvokeAsyncCompletedEventArgs";
        static string invokeAsyncMethodName = "InvokeAsync";
        static string raiseExceptionIfNecessaryMethodName = "RaiseExceptionIfNecessary";
        static string beginOperationDelegateTypeName = "BeginOperationDelegate";
        static string endOperationDelegateTypeName = "EndOperationDelegate";
        static string getDefaultValueForInitializationMethodName = "GetDefaultValueForInitialization";

        // IMPORTANT: this table tracks the set of .ctors in ClientBase and DuplexClientBase. 
        // This table must be kept in sync
        // for DuplexClientBase, the initial InstanceContext param is assumed; ctor overloads must match between ClientBase and DuplexClientBase
        static Type[][] ClientCtorParamTypes = new Type[][]
            {
                new Type[] { },
                new Type[] { stringType, },
                new Type[] { stringType, stringType, },
                new Type[] { stringType, endpointAddressType, },
                new Type[] { bindingType, endpointAddressType, },
            };

        static string[][] ClientCtorParamNames = new string[][]
            {
                new string[] { },
                new string[] { "endpointConfigurationName", },
                new string[] { "endpointConfigurationName", "remoteAddress", },
                new string[] { "endpointConfigurationName", "remoteAddress", },
                new string[] { "binding", "remoteAddress", },
            };

        static Type[] EventArgsCtorParamTypes = new Type[] 
        { 
            objectArrayType, 
            exceptionType, 
            boolType, 
            objectType 
        };

        static string[] EventArgsCtorParamNames = new string[] 
        {
            "results",
            "exception",
            "cancelled",
            "userState"
        };

        static string[] EventArgsPropertyNames = new string[]
        {
            "Results",
            "Error",
            "Cancelled",
            "UserState"
        };

#if DEBUG
        static BindingFlags ctorBindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
        static string DebugCheckTable_errorString = "Client code generation table out of sync with ClientBase and DuplexClientBase ctors. Please investigate.";

        // check the table against what we would get from reflection
        static void DebugCheckTable()
        {
            Fx.Assert(ClientCtorParamNames.Length == ClientCtorParamTypes.Length, DebugCheckTable_errorString);

            for (int i = 0; i < ClientCtorParamTypes.Length; i++)
            {
                DebugCheckTable_ValidateCtor(clientBaseType.GetConstructor(ctorBindingFlags, null, ClientCtorParamTypes[i], null), ClientCtorParamNames[i]);

                Type[] duplexCtorTypes1 = DebugCheckTable_InsertAtStart(ClientCtorParamTypes[i], objectType);
                Type[] duplexCtorTypes2 = DebugCheckTable_InsertAtStart(ClientCtorParamTypes[i], instanceContextType);
                string[] duplexCtorNames = DebugCheckTable_InsertAtStart(ClientCtorParamNames[i], inputInstanceName);

                DebugCheckTable_ValidateCtor(duplexClientBaseType.GetConstructor(ctorBindingFlags, null, duplexCtorTypes1, null), duplexCtorNames);
                DebugCheckTable_ValidateCtor(duplexClientBaseType.GetConstructor(ctorBindingFlags, null, duplexCtorTypes2, null), duplexCtorNames);
            }

            // ClientBase<> has extra InstanceContext overloads that we do not call directly from the generated code, but which we 
            // need to account for in this assert
            Fx.Assert(clientBaseType.GetConstructors(ctorBindingFlags).Length == ClientCtorParamTypes.Length * 2, DebugCheckTable_errorString);

            // DuplexClientBase<> also has extra object/InstanceContext overloads (but we call these)
            Fx.Assert(duplexClientBaseType.GetConstructors(ctorBindingFlags).Length == ClientCtorParamTypes.Length * 2, DebugCheckTable_errorString);
        }

        static T[] DebugCheckTable_InsertAtStart<T>(T[] arr, T item)
        {
            T[] newArr = new T[arr.Length + 1];
            newArr[0] = item;
            Array.Copy(arr, 0, newArr, 1, arr.Length);
            return newArr;
        }

        static void DebugCheckTable_ValidateCtor(ConstructorInfo ctor, string[] paramNames)
        {
            Fx.Assert(ctor != null, DebugCheckTable_errorString);

            ParameterInfo[] parameters = ctor.GetParameters();
            Fx.Assert(parameters.Length == paramNames.Length, DebugCheckTable_errorString);
            for (int i = 0; i < paramNames.Length; i++)
            {
                Fx.Assert(parameters[i].Name == paramNames[i], DebugCheckTable_errorString);
            }
        }
#endif

        void IServiceContractGenerationExtension.GenerateContract(ServiceContractGenerationContext context)
        {
#if DEBUG
            // DebugCheckTable();
#endif
            CodeTypeDeclaration clientType = context.TypeFactory.CreateClassType();
            // Have to make sure that client name does not match any methods: member names can not be the same as their enclosing type (CSharp only)
            clientType.Name = NamingHelper.GetUniqueName(GetClientClassName(context.ContractType.Name), DoesMethodNameExist, context.Operations);
            CodeTypeReference contractTypeRef = context.ContractTypeReference;
            if (context.DuplexCallbackType == null)
                clientType.BaseTypes.Add(new CodeTypeReference(context.ServiceContractGenerator.GetCodeTypeReference(typeof(ClientBase<>)).BaseType, context.ContractTypeReference));
            else
                clientType.BaseTypes.Add(new CodeTypeReference(context.ServiceContractGenerator.GetCodeTypeReference(typeof(DuplexClientBase<>)).BaseType, context.ContractTypeReference));

            clientType.BaseTypes.Add(context.ContractTypeReference);

            if (!(ClientCtorParamNames.Length == ClientCtorParamTypes.Length))
            {
                Fx.Assert("Invalid client generation constructor table initialization");
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Invalid client generation constructor table initialization")));
            }

            for (int i = 0; i < ClientCtorParamNames.Length; i++)
            {
                if (!(ClientCtorParamNames[i].Length == ClientCtorParamTypes[i].Length))
                {
                    Fx.Assert("Invalid client generation constructor table initialization");
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Invalid client generation constructor table initialization")));
                }

                CodeConstructor ctor = new CodeConstructor();
                ctor.Attributes = MemberAttributes.Public;
                if (context.DuplexCallbackType != null)
                {
                    ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(InstanceContext), inputInstanceName));
                    ctor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(inputInstanceName));
                }
                for (int j = 0; j < ClientCtorParamNames[i].Length; j++)
                {
                    ctor.Parameters.Add(new CodeParameterDeclarationExpression(ClientCtorParamTypes[i][j], ClientCtorParamNames[i][j]));
                    ctor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(ClientCtorParamNames[i][j]));
                }
                clientType.Members.Add(ctor);
            }

            foreach (OperationContractGenerationContext operationContext in context.Operations)
            {
                // Note that we generate all the client-side methods, even inherited ones.
                if (operationContext.Operation.IsServerInitiated()) continue;
                CodeTypeReference declaringContractTypeRef = operationContext.DeclaringTypeReference;
                GenerateClientClassMethod(clientType, contractTypeRef, operationContext.SyncMethod, this.tryAddHelperMethod, declaringContractTypeRef);

                if (operationContext.IsAsync)
                {
                    CodeMemberMethod beginMethod = GenerateClientClassMethod(clientType, contractTypeRef, operationContext.BeginMethod, this.tryAddHelperMethod, declaringContractTypeRef);
                    CodeMemberMethod endMethod = GenerateClientClassMethod(clientType, contractTypeRef, operationContext.EndMethod, this.tryAddHelperMethod, declaringContractTypeRef);

                    if (this.generateEventAsyncMethods)
                    {
                        GenerateEventAsyncMethods(context, clientType, operationContext.SyncMethod.Name, beginMethod, endMethod);
                    }
                }

                if (operationContext.IsTask)
                {
                    GenerateClientClassMethod(clientType, contractTypeRef, operationContext.TaskMethod, !operationContext.Operation.HasOutputParameters && this.tryAddHelperMethod, declaringContractTypeRef);
                }
            }

            context.Namespace.Types.Add(clientType);
            context.ClientType = clientType;
            context.ClientTypeReference = ServiceContractGenerator.NamespaceHelper.GetCodeTypeReference(context.Namespace, clientType);
        }

        static CodeMemberMethod GenerateClientClassMethod(CodeTypeDeclaration clientType, CodeTypeReference contractTypeRef, CodeMemberMethod method, bool addHelperMethod, CodeTypeReference declaringContractTypeRef)
        {
            CodeMemberMethod methodImpl = GetImplementationOfMethod(contractTypeRef, method);
            AddMethodImpl(methodImpl);
            int methodPosition = clientType.Members.Add(methodImpl);
            CodeMemberMethod helperMethod = null;

            if (addHelperMethod)
            {
                helperMethod = GenerateHelperMethod(declaringContractTypeRef, methodImpl);
                if (helperMethod != null)
                {
                    clientType.Members[methodPosition].CustomAttributes.Add(CreateEditorBrowsableAttribute(EditorBrowsableState.Advanced));
                    clientType.Members.Add(helperMethod);
                }
            }

            return (helperMethod != null) ? helperMethod : methodImpl;
        }

        internal static CodeAttributeDeclaration CreateEditorBrowsableAttribute(EditorBrowsableState editorBrowsableState)
        {
            CodeAttributeDeclaration browsableAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(EditorBrowsableAttribute)));
            CodeTypeReferenceExpression browsableAttributeState = new CodeTypeReferenceExpression(typeof(EditorBrowsableState));
            CodeAttributeArgument browsableAttributeValue = new CodeAttributeArgument(new CodeFieldReferenceExpression(browsableAttributeState, editorBrowsableState.ToString()));
            browsableAttribute.Arguments.Add(browsableAttributeValue);

            return browsableAttribute;
        }

        private static CodeMemberMethod GenerateHelperMethod(CodeTypeReference ifaceType, CodeMemberMethod method)
        {
            CodeMemberMethod helperMethod = new CodeMemberMethod();
            helperMethod.Name = method.Name;
            helperMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            CodeMethodInvokeExpression invokeMethod = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeCastExpression(ifaceType, new CodeThisReferenceExpression()), method.Name));
            bool hasTypedMessage = false;
            foreach (CodeParameterDeclarationExpression param in method.Parameters)
            {
                CodeTypeDeclaration paramTypeDecl = ServiceContractGenerator.NamespaceHelper.GetCodeType(param.Type);
                if (paramTypeDecl != null)
                {
                    hasTypedMessage = true;
                    CodeVariableReferenceExpression inValue = new CodeVariableReferenceExpression("inValue");
                    helperMethod.Statements.Add(new CodeVariableDeclarationStatement(param.Type, inValue.VariableName, new CodeObjectCreateExpression(param.Type)));
                    invokeMethod.Parameters.Add(inValue);
                    GenerateParameters(helperMethod, paramTypeDecl, inValue, FieldDirection.In);
                }
                else
                {
                    helperMethod.Parameters.Add(new CodeParameterDeclarationExpression(param.Type, param.Name));
                    invokeMethod.Parameters.Add(new CodeArgumentReferenceExpression(param.Name));
                }
            }
            if (method.ReturnType.BaseType == voidTypeRef.BaseType)
                helperMethod.Statements.Add(invokeMethod);
            else
            {
                CodeTypeDeclaration returnTypeDecl = ServiceContractGenerator.NamespaceHelper.GetCodeType(method.ReturnType);
                if (returnTypeDecl != null)
                {
                    hasTypedMessage = true;
                    CodeVariableReferenceExpression outVar = new CodeVariableReferenceExpression("retVal");

                    helperMethod.Statements.Add(new CodeVariableDeclarationStatement(method.ReturnType, outVar.VariableName, invokeMethod));
                    CodeMethodReturnStatement returnStatement = GenerateParameters(helperMethod, returnTypeDecl, outVar, FieldDirection.Out);
                    if (returnStatement != null)
                        helperMethod.Statements.Add(returnStatement);
                }
                else
                {
                    helperMethod.Statements.Add(new CodeMethodReturnStatement(invokeMethod));
                    helperMethod.ReturnType = method.ReturnType;
                }
            }
            if (hasTypedMessage)
                method.PrivateImplementationType = ifaceType;
            return hasTypedMessage ? helperMethod : null;
        }

        private static CodeMethodReturnStatement GenerateParameters(CodeMemberMethod helperMethod, CodeTypeDeclaration codeTypeDeclaration, CodeExpression target, FieldDirection dir)
        {
            CodeMethodReturnStatement returnStatement = null;
            foreach (CodeTypeMember member in codeTypeDeclaration.Members)
            {
                CodeMemberField field = member as CodeMemberField;
                if (field == null)
                    continue;
                CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression(target, field.Name);
                CodeTypeDeclaration bodyTypeDecl = ServiceContractGenerator.NamespaceHelper.GetCodeType(field.Type);
                if (bodyTypeDecl != null)
                {
                    if (dir == FieldDirection.In)
                        helperMethod.Statements.Add(new CodeAssignStatement(fieldRef, new CodeObjectCreateExpression(field.Type)));
                    returnStatement = GenerateParameters(helperMethod, bodyTypeDecl, fieldRef, dir);
                    continue;
                }
                CodeParameterDeclarationExpression param = GetRefParameter(helperMethod.Parameters, dir, field);
                if (param == null && dir == FieldDirection.Out && helperMethod.ReturnType.BaseType == voidTypeRef.BaseType)
                {
                    helperMethod.ReturnType = field.Type;
                    returnStatement = new CodeMethodReturnStatement(fieldRef);
                }
                else
                {
                    if (param == null)
                    {
                        param = new CodeParameterDeclarationExpression(field.Type, NamingHelper.GetUniqueName(field.Name, DoesParameterNameExist, helperMethod));
                        param.Direction = dir;
                        helperMethod.Parameters.Add(param);
                    }
                    if (dir == FieldDirection.Out)
                        helperMethod.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression(param.Name), fieldRef));
                    else
                        helperMethod.Statements.Add(new CodeAssignStatement(fieldRef, new CodeArgumentReferenceExpression(param.Name)));
                }
            }
            return returnStatement;
        }

        private static CodeParameterDeclarationExpression GetRefParameter(CodeParameterDeclarationExpressionCollection parameters, FieldDirection dir, CodeMemberField field)
        {
            foreach (CodeParameterDeclarationExpression p in parameters)
            {
                if (p.Name == field.Name)
                {
                    if (p.Direction != dir && p.Type.BaseType == field.Type.BaseType)
                    {
                        p.Direction = FieldDirection.Ref;
                        return p;
                    }
                    return null;
                }
            }
            return null;
        }

        internal static bool DoesMemberNameExist(string name, object typeDeclarationObject)
        {
            CodeTypeDeclaration typeDeclaration = (CodeTypeDeclaration)typeDeclarationObject;

            if (string.Compare(typeDeclaration.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
            {
                return true;
            }

            foreach (CodeTypeMember member in typeDeclaration.Members)
            {
                if (string.Compare(member.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return true;
                }
            }

            return false;
        }

        internal static bool DoesTypeNameExists(string name, object codeTypeDeclarationCollectionObject)
        {
            CodeTypeDeclarationCollection codeTypeDeclarations = (CodeTypeDeclarationCollection)codeTypeDeclarationCollectionObject;
            foreach (CodeTypeDeclaration codeTypeDeclaration in codeTypeDeclarations)
            {
                if (string.Compare(codeTypeDeclaration.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return true;
                }
            }

            return false;
        }

        internal static bool DoesTypeAndMemberNameExist(string name, object nameCollection)
        {
            object[] nameCollections = (object[])nameCollection;

            if (DoesTypeNameExists(name, nameCollections[0]))
            {
                return true;
            }
            if (DoesMemberNameExist(name, nameCollections[1]))
            {
                return true;
            }

            return false;
        }

        internal static bool DoesMethodNameExist(string name, object operationsObject)
        {
            Collection<OperationContractGenerationContext> operations = (Collection<OperationContractGenerationContext>)operationsObject;
            foreach (OperationContractGenerationContext operationContext in operations)
            {
                if (String.Compare(operationContext.SyncMethod.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
                    return true;
                if (operationContext.IsAsync)
                {
                    if (String.Compare(operationContext.BeginMethod.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
                        return true;
                    if (String.Compare(operationContext.EndMethod.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
                        return true;
                }
                if (operationContext.IsTask)
                {
                    if (String.Compare(operationContext.TaskMethod.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
                        return true;
                }
            }
            return false;
        }

        internal static bool DoesParameterNameExist(string name, object methodObject)
        {
            CodeMemberMethod method = (CodeMemberMethod)methodObject;
            if (String.Compare(method.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
                return true;
            CodeParameterDeclarationExpressionCollection parameters = method.Parameters;
            foreach (CodeParameterDeclarationExpression p in parameters)
            {
                if (String.Compare(p.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
                    return true;
            }
            return false;
        }

        static void AddMethodImpl(CodeMemberMethod method)
        {
            CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(GetChannelReference(), method.Name);
            foreach (CodeParameterDeclarationExpression parameter in method.Parameters)
            {
                methodInvoke.Parameters.Add(new CodeDirectionExpression(parameter.Direction, new CodeVariableReferenceExpression(parameter.Name)));
            }
            if (IsVoid(method))
                method.Statements.Add(methodInvoke);
            else
                method.Statements.Add(new CodeMethodReturnStatement(methodInvoke));
        }

        static CodeMemberMethod GetImplementationOfMethod(CodeTypeReference ifaceType, CodeMemberMethod method)
        {
            CodeMemberMethod m = new CodeMemberMethod();
            m.Name = method.Name;
            m.ImplementationTypes.Add(ifaceType);
            m.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            foreach (CodeParameterDeclarationExpression parameter in method.Parameters)
            {
                CodeParameterDeclarationExpression newParam = new CodeParameterDeclarationExpression(parameter.Type, parameter.Name);
                newParam.Direction = parameter.Direction;
                m.Parameters.Add(newParam);
            }
            m.ReturnType = method.ReturnType;
            return m;
        }

        static void GenerateEventAsyncMethods(ServiceContractGenerationContext context, CodeTypeDeclaration clientType,
            string syncMethodName, CodeMemberMethod beginMethod, CodeMemberMethod endMethod)
        {
            CodeTypeDeclaration operationCompletedEventArgsType = CreateOperationCompletedEventArgsType(context, syncMethodName, endMethod);
            CodeMemberEvent operationCompletedEvent = CreateOperationCompletedEvent(context, clientType, syncMethodName, operationCompletedEventArgsType);

            CodeMemberField beginOperationDelegate = CreateBeginOperationDelegate(context, clientType, syncMethodName);
            CodeMemberMethod beginOperationMethod = CreateBeginOperationMethod(context, clientType, syncMethodName, beginMethod);

            CodeMemberField endOperationDelegate = CreateEndOperationDelegate(context, clientType, syncMethodName);
            CodeMemberMethod endOperationMethod = CreateEndOperationMethod(context, clientType, syncMethodName, endMethod);

            CodeMemberField operationCompletedDelegate = CreateOperationCompletedDelegate(context, clientType, syncMethodName);
            CodeMemberMethod operationCompletedMethod = CreateOperationCompletedMethod(context, clientType, syncMethodName, operationCompletedEventArgsType, operationCompletedEvent);

            CodeMemberMethod eventAsyncMethod = CreateEventAsyncMethod(context, clientType, syncMethodName, beginMethod, 
                beginOperationDelegate, beginOperationMethod, endOperationDelegate, endOperationMethod, operationCompletedDelegate, operationCompletedMethod);

            CreateEventAsyncMethodOverload(clientType, eventAsyncMethod);

            // hide the normal async methods from intellisense
            beginMethod.CustomAttributes.Add(CreateEditorBrowsableAttribute(EditorBrowsableState.Advanced));
            endMethod.CustomAttributes.Add(CreateEditorBrowsableAttribute(EditorBrowsableState.Advanced));            
        }

        static CodeTypeDeclaration CreateOperationCompletedEventArgsType(ServiceContractGenerationContext context, 
            string syncMethodName, CodeMemberMethod endMethod)
        {
            if ((endMethod.Parameters.Count == 1) && (endMethod.ReturnType.BaseType == voidTypeRef.BaseType))
            {
                // no need to create new event args type, use AsyncCompletedEventArgs
                return null;
            }

            CodeTypeDeclaration argsType = context.TypeFactory.CreateClassType();
            argsType.BaseTypes.Add(new CodeTypeReference(asyncCompletedEventArgsType));

            // define object[] results field.
            CodeMemberField resultsField = new CodeMemberField();
            resultsField.Type = new CodeTypeReference(objectArrayType);

            CodeFieldReferenceExpression resultsFieldReference = new CodeFieldReferenceExpression();
            resultsFieldReference.TargetObject = new CodeThisReferenceExpression();

            // create constructor, that assigns the results field.
            CodeConstructor ctor = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            for (int i = 0; i < EventArgsCtorParamTypes.Length; i++)
            {
                ctor.Parameters.Add(new CodeParameterDeclarationExpression(EventArgsCtorParamTypes[i], EventArgsCtorParamNames[i]));
                if (i > 0)
                {
                    ctor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(EventArgsCtorParamNames[i]));
                }
            }
            argsType.Members.Add(ctor);
            ctor.Statements.Add(new CodeAssignStatement(resultsFieldReference, new CodeVariableReferenceExpression(EventArgsCtorParamNames[0])));
             
            // create properties for the out parameters
            int asyncResultParamIndex = GetAsyncResultParamIndex(endMethod);
            int count = 0;
            for (int i = 0; i < endMethod.Parameters.Count; i++)
            {
                if (i != asyncResultParamIndex)
                {
                    CreateEventAsyncCompletedArgsTypeProperty(argsType,
                        endMethod.Parameters[i].Type,
                        endMethod.Parameters[i].Name,
                        new CodeArrayIndexerExpression(resultsFieldReference, new CodePrimitiveExpression(count++)));
                }
            }

            // create the property for the return type
            if (endMethod.ReturnType.BaseType != voidTypeRef.BaseType)
            {
                CreateEventAsyncCompletedArgsTypeProperty(
                    argsType,
                    endMethod.ReturnType,
                    NamingHelper.GetUniqueName("Result", DoesMemberNameExist, argsType),
                    new CodeArrayIndexerExpression(resultsFieldReference, 
                        new CodePrimitiveExpression(count)));
               
            }

            // Name the "results" field after generating the properties to make sure it does 
            // not conflict with the property names.
            resultsField.Name = NamingHelper.GetUniqueName("results", DoesMemberNameExist, argsType);
            resultsFieldReference.FieldName = resultsField.Name;
            argsType.Members.Add(resultsField);

            // Name the type making sure that it does not conflict with its members and types already present in
            // the namespace. 
            argsType.Name = NamingHelper.GetUniqueName(GetOperationCompletedEventArgsTypeName(syncMethodName),
                DoesTypeAndMemberNameExist, new object[] { context.Namespace.Types, argsType });
            context.Namespace.Types.Add(argsType);

            return argsType;
        }

        static int GetAsyncResultParamIndex(CodeMemberMethod endMethod)
        {
            int index = endMethod.Parameters.Count - 1;
            if (endMethod.Parameters[index].Type.BaseType != asyncResultTypeRef.BaseType)
            {
                // workaround for CSD Dev Framework:10826, the unwrapped end method has IAsyncResult as first param. 
                index = 0;
            }

            return index;
        }
        
        static CodeMemberProperty CreateEventAsyncCompletedArgsTypeProperty(CodeTypeDeclaration ownerTypeDecl, 
            CodeTypeReference propertyType, string propertyName, CodeExpression propertyValueExpr)
        {
            CodeMemberProperty property = new CodeMemberProperty();
            property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            property.Type = propertyType;
            property.Name = propertyName;
            property.HasSet = false;
            property.HasGet = true;

            CodeCastExpression castExpr = new CodeCastExpression(propertyType, propertyValueExpr);
            CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(castExpr);

            property.GetStatements.Add(new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), raiseExceptionIfNecessaryMethodName));
            property.GetStatements.Add(returnStmt);
            ownerTypeDecl.Members.Add(property);

            return property;
        }

        static CodeMemberEvent CreateOperationCompletedEvent(ServiceContractGenerationContext context, 
            CodeTypeDeclaration clientType, string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType)
        {
            CodeMemberEvent operationCompletedEvent = new CodeMemberEvent();
            operationCompletedEvent.Attributes = MemberAttributes.Public;
            operationCompletedEvent.Type = new CodeTypeReference(eventHandlerType);
            
            if (operationCompletedEventArgsType == null)
            {
                operationCompletedEvent.Type.TypeArguments.Add(asyncCompletedEventArgsType);
            }
            else
            {
                operationCompletedEvent.Type.TypeArguments.Add(operationCompletedEventArgsType.Name);
            }

            operationCompletedEvent.Name = NamingHelper.GetUniqueName(GetOperationCompletedEventName(syncMethodName),
                DoesMethodNameExist, context.Operations);
            
            clientType.Members.Add(operationCompletedEvent);
            return operationCompletedEvent;
        }

        static CodeMemberField CreateBeginOperationDelegate(ServiceContractGenerationContext context,
            CodeTypeDeclaration clientType, string syncMethodName)
        {
            CodeMemberField beginOperationDelegate = new CodeMemberField();
            beginOperationDelegate.Attributes = MemberAttributes.Private;
            beginOperationDelegate.Type = new CodeTypeReference(beginOperationDelegateTypeName);
            beginOperationDelegate.Name = NamingHelper.GetUniqueName(GetBeginOperationDelegateName(syncMethodName),
                DoesMethodNameExist, context.Operations);

            clientType.Members.Add(beginOperationDelegate);
            return beginOperationDelegate;
        }

        static CodeMemberMethod CreateBeginOperationMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, 
            string syncMethodName, CodeMemberMethod beginMethod)
        {
            CodeMemberMethod onBeginOperationMethod = new CodeMemberMethod();
            onBeginOperationMethod.Attributes = MemberAttributes.Private;
            onBeginOperationMethod.ReturnType = new CodeTypeReference(asyncResultType);
            onBeginOperationMethod.Name = NamingHelper.GetUniqueName(GetBeginOperationMethodName(syncMethodName), 
                DoesMethodNameExist, context.Operations);

            CodeParameterDeclarationExpression inValuesParam = new CodeParameterDeclarationExpression();
            inValuesParam.Type = new CodeTypeReference(objectArrayType);
            inValuesParam.Name = NamingHelper.GetUniqueName("inValues", DoesParameterNameExist, beginMethod);
            onBeginOperationMethod.Parameters.Add(inValuesParam);

            CodeMethodInvokeExpression invokeBegin = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), beginMethod.Name);
            CodeExpression inValuesRef = new CodeVariableReferenceExpression(inValuesParam.Name);

            for (int i = 0; i < beginMethod.Parameters.Count - 2; i++)
            {
                CodeVariableDeclarationStatement variableDecl = new CodeVariableDeclarationStatement();
                variableDecl.Type = beginMethod.Parameters[i].Type;
                variableDecl.Name = beginMethod.Parameters[i].Name;
                variableDecl.InitExpression = new CodeCastExpression(variableDecl.Type,
                    new CodeArrayIndexerExpression(inValuesRef, new CodePrimitiveExpression(i)));

                onBeginOperationMethod.Statements.Add(variableDecl);
                invokeBegin.Parameters.Add(new CodeDirectionExpression(beginMethod.Parameters[i].Direction,
                    new CodeVariableReferenceExpression(variableDecl.Name)));
            }

            for (int i = beginMethod.Parameters.Count - 2; i < beginMethod.Parameters.Count; i++)
            {
                onBeginOperationMethod.Parameters.Add(new CodeParameterDeclarationExpression(
                    beginMethod.Parameters[i].Type, beginMethod.Parameters[i].Name));
                invokeBegin.Parameters.Add(new CodeVariableReferenceExpression(beginMethod.Parameters[i].Name));
            }

            onBeginOperationMethod.Statements.Add(new CodeMethodReturnStatement(invokeBegin));
            clientType.Members.Add(onBeginOperationMethod);
            return onBeginOperationMethod;
        }
       
        static CodeMemberField CreateEndOperationDelegate(ServiceContractGenerationContext context,
            CodeTypeDeclaration clientType, string syncMethodName)
        {
            CodeMemberField endOperationDelegate = new CodeMemberField();
            endOperationDelegate.Attributes = MemberAttributes.Private;
            endOperationDelegate.Type = new CodeTypeReference(endOperationDelegateTypeName);
            endOperationDelegate.Name = NamingHelper.GetUniqueName(GetEndOperationDelegateName(syncMethodName),
                DoesMethodNameExist, context.Operations);

            clientType.Members.Add(endOperationDelegate);
            return endOperationDelegate;
        }

        static CodeMemberMethod CreateEndOperationMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeMemberMethod endMethod)
        {
            CodeMemberMethod onEndOperationMethod = new CodeMemberMethod();
            onEndOperationMethod.Attributes = MemberAttributes.Private;
            onEndOperationMethod.ReturnType = new CodeTypeReference(objectArrayType);
            onEndOperationMethod.Name = NamingHelper.GetUniqueName(GetEndOperationMethodName(syncMethodName), DoesMethodNameExist, context.Operations);

            int asyncResultParamIndex = GetAsyncResultParamIndex(endMethod);
            CodeMethodInvokeExpression invokeEnd = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), endMethod.Name);
            CodeArrayCreateExpression retArray = new CodeArrayCreateExpression();
            retArray.CreateType = new CodeTypeReference(objectArrayType);
            for (int i = 0; i < endMethod.Parameters.Count; i++)
            {
                if (i == asyncResultParamIndex)
                {
                    onEndOperationMethod.Parameters.Add(new CodeParameterDeclarationExpression(
                        endMethod.Parameters[i].Type, endMethod.Parameters[i].Name));
                    invokeEnd.Parameters.Add(new CodeVariableReferenceExpression(endMethod.Parameters[i].Name));
                }
                else
                {
                    CodeVariableDeclarationStatement variableDecl = new CodeVariableDeclarationStatement(
                        endMethod.Parameters[i].Type, endMethod.Parameters[i].Name);
                    CodeMethodReferenceExpression getDefaultValueMethodRef = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), getDefaultValueForInitializationMethodName, endMethod.Parameters[i].Type);
                    variableDecl.InitExpression = new CodeMethodInvokeExpression(getDefaultValueMethodRef); 
                    onEndOperationMethod.Statements.Add(variableDecl);

                    invokeEnd.Parameters.Add(new CodeDirectionExpression(endMethod.Parameters[i].Direction,
                            new CodeVariableReferenceExpression(variableDecl.Name)));

                    retArray.Initializers.Add(new CodeVariableReferenceExpression(variableDecl.Name));
                }
            }

            if (endMethod.ReturnType.BaseType != voidTypeRef.BaseType)
            {
                CodeVariableDeclarationStatement retValDecl = new CodeVariableDeclarationStatement();
                retValDecl.Type = endMethod.ReturnType;
                retValDecl.Name = NamingHelper.GetUniqueName("retVal", DoesParameterNameExist, endMethod);
                retValDecl.InitExpression = invokeEnd;
                retArray.Initializers.Add(new CodeVariableReferenceExpression(retValDecl.Name));

                onEndOperationMethod.Statements.Add(retValDecl);
            }
            else
            {
                onEndOperationMethod.Statements.Add(invokeEnd);
            }

            if (retArray.Initializers.Count > 0)
            {
                onEndOperationMethod.Statements.Add(new CodeMethodReturnStatement(retArray));
            }
            else
            {
                onEndOperationMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
            }

            clientType.Members.Add(onEndOperationMethod);
            return onEndOperationMethod;
        }

        static CodeMemberField CreateOperationCompletedDelegate(ServiceContractGenerationContext context, 
            CodeTypeDeclaration clientType, string syncMethodName)
        {
            CodeMemberField operationCompletedDelegate = new CodeMemberField();
            operationCompletedDelegate.Attributes = MemberAttributes.Private;
            operationCompletedDelegate.Type = new CodeTypeReference(sendOrPostCallbackType);
            operationCompletedDelegate.Name = NamingHelper.GetUniqueName(GetOperationCompletedDelegateName(syncMethodName),
                DoesMethodNameExist, context.Operations);

            clientType.Members.Add(operationCompletedDelegate);
            return operationCompletedDelegate;
        }

        static CodeMemberMethod CreateOperationCompletedMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, 
            string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType, CodeMemberEvent operationCompletedEvent)
        {
            CodeMemberMethod operationCompletedMethod = new CodeMemberMethod();
            operationCompletedMethod.Attributes = MemberAttributes.Private;
            operationCompletedMethod.Name = NamingHelper.GetUniqueName(GetOperationCompletedMethodName(syncMethodName), 
                DoesMethodNameExist, context.Operations);

            operationCompletedMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(objectType), "state"));
            operationCompletedMethod.ReturnType = new CodeTypeReference(voidType);

            CodeVariableDeclarationStatement eventArgsDecl =
                new CodeVariableDeclarationStatement(invokeAsyncCompletedEventArgsTypeName, "e");

            eventArgsDecl.InitExpression = new CodeCastExpression(invokeAsyncCompletedEventArgsTypeName,
                new CodeArgumentReferenceExpression(operationCompletedMethod.Parameters[0].Name));

            CodeObjectCreateExpression newEventArgsExpr;
            CodeVariableReferenceExpression eventArgsRef = new CodeVariableReferenceExpression(eventArgsDecl.Name);
            if (operationCompletedEventArgsType != null)
            {
                newEventArgsExpr = new CodeObjectCreateExpression(operationCompletedEventArgsType.Name,
                    new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[0]),
                    new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[1]),
                    new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[2]),
                    new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[3]));
            }
            else
            {
                newEventArgsExpr = new CodeObjectCreateExpression(asyncCompletedEventArgsType,
                    new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[1]),
                    new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[2]),
                    new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[3]));
            }

            CodeEventReferenceExpression completedEvent = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), operationCompletedEvent.Name);

            CodeDelegateInvokeExpression raiseEventExpr = new CodeDelegateInvokeExpression(
                completedEvent,
                new CodeThisReferenceExpression(),
                newEventArgsExpr);

            CodeConditionStatement ifEventHandlerNotNullBlock = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    completedEvent,
                    CodeBinaryOperatorType.IdentityInequality,
                    new CodePrimitiveExpression(null)),
                eventArgsDecl,
                new CodeExpressionStatement(raiseEventExpr));

            operationCompletedMethod.Statements.Add(ifEventHandlerNotNullBlock);

            clientType.Members.Add(operationCompletedMethod);
            return operationCompletedMethod;
        }
        
        static CodeMemberMethod CreateEventAsyncMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, 
            string syncMethodName, CodeMemberMethod beginMethod,
            CodeMemberField beginOperationDelegate, CodeMemberMethod beginOperationMethod, 
            CodeMemberField endOperationDelegate, CodeMemberMethod endOperationMethod, 
            CodeMemberField operationCompletedDelegate, CodeMemberMethod operationCompletedMethod)
        {
            CodeMemberMethod eventAsyncMethod = new CodeMemberMethod();
            eventAsyncMethod.Name = NamingHelper.GetUniqueName(GetEventAsyncMethodName(syncMethodName), 
                DoesMethodNameExist, context.Operations);
            eventAsyncMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            eventAsyncMethod.ReturnType = new CodeTypeReference(voidType);

            CodeArrayCreateExpression invokeAsyncInValues = new CodeArrayCreateExpression(new CodeTypeReference(objectArrayType));
            for (int i = 0; i < beginMethod.Parameters.Count - 2; i++)
            {
                CodeParameterDeclarationExpression beginMethodParameter = beginMethod.Parameters[i];
                CodeParameterDeclarationExpression eventAsyncMethodParameter = new CodeParameterDeclarationExpression(
                    beginMethodParameter.Type, beginMethodParameter.Name);

                eventAsyncMethodParameter.Direction = FieldDirection.In;
                eventAsyncMethod.Parameters.Add(eventAsyncMethodParameter);
                invokeAsyncInValues.Initializers.Add(new CodeVariableReferenceExpression(eventAsyncMethodParameter.Name));
            }

            string userStateParamName = NamingHelper.GetUniqueName("userState", DoesParameterNameExist, eventAsyncMethod);
            eventAsyncMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(objectType), userStateParamName));
            
            eventAsyncMethod.Statements.Add(CreateDelegateIfNotNull(beginOperationDelegate, beginOperationMethod));
            eventAsyncMethod.Statements.Add(CreateDelegateIfNotNull(endOperationDelegate, endOperationMethod));
            eventAsyncMethod.Statements.Add(CreateDelegateIfNotNull(operationCompletedDelegate, operationCompletedMethod));

            CodeMethodInvokeExpression invokeAsync = new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), invokeAsyncMethodName);
            invokeAsync.Parameters.Add(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), beginOperationDelegate.Name));
            if (invokeAsyncInValues.Initializers.Count > 0)
            {
                invokeAsync.Parameters.Add(invokeAsyncInValues);
            }
            else
            {
                invokeAsync.Parameters.Add(new CodePrimitiveExpression(null));
            }
            invokeAsync.Parameters.Add(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), endOperationDelegate.Name));
            invokeAsync.Parameters.Add(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), operationCompletedDelegate.Name));
            invokeAsync.Parameters.Add(new CodeVariableReferenceExpression(userStateParamName));
        
            eventAsyncMethod.Statements.Add(new CodeExpressionStatement(invokeAsync));

            clientType.Members.Add(eventAsyncMethod);
            return eventAsyncMethod;
        }

        static CodeMemberMethod CreateEventAsyncMethodOverload(CodeTypeDeclaration clientType, CodeMemberMethod eventAsyncMethod)
        {
            CodeMemberMethod eventAsyncMethodOverload = new CodeMemberMethod();
            eventAsyncMethodOverload.Attributes = eventAsyncMethod.Attributes;
            eventAsyncMethodOverload.Name = eventAsyncMethod.Name;
            eventAsyncMethodOverload.ReturnType = eventAsyncMethod.ReturnType;

            CodeMethodInvokeExpression invokeEventAsyncMethod = new CodeMethodInvokeExpression(
                new CodeThisReferenceExpression(), eventAsyncMethod.Name);

            for (int i = 0; i < eventAsyncMethod.Parameters.Count - 1; i++)
            {
                eventAsyncMethodOverload.Parameters.Add(new CodeParameterDeclarationExpression(
                    eventAsyncMethod.Parameters[i].Type,
                    eventAsyncMethod.Parameters[i].Name));

                invokeEventAsyncMethod.Parameters.Add(new CodeVariableReferenceExpression(
                    eventAsyncMethod.Parameters[i].Name));
            }
            invokeEventAsyncMethod.Parameters.Add(new CodePrimitiveExpression(null));

            eventAsyncMethodOverload.Statements.Add(invokeEventAsyncMethod);

            int eventAsyncMethodPosition = clientType.Members.IndexOf(eventAsyncMethod);
            Fx.Assert(eventAsyncMethodPosition != -1,
                "The eventAsyncMethod must be added to the clientType before calling CreateEventAsyncMethodOverload");

            clientType.Members.Insert(eventAsyncMethodPosition, eventAsyncMethodOverload);
            return eventAsyncMethodOverload;
        }

        static CodeStatement CreateDelegateIfNotNull(CodeMemberField delegateField, CodeMemberMethod delegateMethod)
        {
            return new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), delegateField.Name),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePrimitiveExpression(null)),
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), delegateField.Name),
                    new CodeDelegateCreateExpression(delegateField.Type, 
                        new CodeThisReferenceExpression(), delegateMethod.Name)));
        }

        static string GetClassName(string interfaceName)
        {
            // maybe strip a leading 'I'
            if (interfaceName.Length >= 2 &&
                String.Compare(interfaceName, 0, Strings.InterfaceTypePrefix, 0, Strings.InterfaceTypePrefix.Length, StringComparison.Ordinal) == 0 &&
                Char.IsUpper(interfaceName, 1))
                return interfaceName.Substring(1);
            else
                return interfaceName;
        }

        static string GetEventAsyncMethodName(string syncMethodName)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}Async", syncMethodName);
        }

        static string GetBeginOperationDelegateName(string syncMethodName)
        {
            return string.Format(CultureInfo.InvariantCulture, "onBegin{0}Delegate", syncMethodName);
        }

        static string GetBeginOperationMethodName(string syncMethodName)
        {
            return string.Format(CultureInfo.InvariantCulture, "OnBegin{0}", syncMethodName);
        }

        static string GetEndOperationDelegateName(string syncMethodName)
        {
            return string.Format(CultureInfo.InvariantCulture, "onEnd{0}Delegate", syncMethodName);
        }

        static string GetEndOperationMethodName(string syncMethodName)
        {
            return string.Format(CultureInfo.InvariantCulture, "OnEnd{0}", syncMethodName);
        }

        static string GetOperationCompletedDelegateName(string syncMethodName)
        {
            return string.Format(CultureInfo.InvariantCulture, "on{0}CompletedDelegate", syncMethodName);
        }

        static string GetOperationCompletedMethodName(string syncMethodName)
        {
            return string.Format(CultureInfo.InvariantCulture, "On{0}Completed", syncMethodName);
        }

        static string GetOperationCompletedEventName(string syncMethodName)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}Completed", syncMethodName);
        }

        static string GetOperationCompletedEventArgsTypeName(string syncMethodName)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}CompletedEventArgs", syncMethodName);
        }

        static internal string GetClientClassName(string interfaceName)
        {
            return GetClassName(interfaceName) + Strings.ClientTypeSuffix;
        }

        static bool IsVoid(CodeMemberMethod method)
        {
            return method.ReturnType == null || String.Compare(method.ReturnType.BaseType, typeof(void).FullName, StringComparison.Ordinal) == 0;
        }

        static CodeExpression GetChannelReference()
        {
            return new CodePropertyReferenceExpression(new CodeBaseReferenceExpression(), Strings.ClientBaseChannelProperty);
        }

        static class Strings
        {
            public const string ClientBaseChannelProperty = "Channel";
            public const string ClientTypeSuffix = "Client";
            public const string InterfaceTypePrefix = "I";
        }
    }
}