File: SoapProtocolImporter.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1180 lines) | stat: -rw-r--r-- 65,166 bytes parent folder | download | duplicates (6)
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
//------------------------------------------------------------------------------
//  <copyright from='1997' to='2001' company='Microsoft Corporation'>           
//     Copyright (c) Microsoft Corporation. All Rights Reserved.                
//     Information Contained Herein is Proprietary and Confidential.            
//  </copyright>                                                                
//------------------------------------------------------------------------------
namespace System.Web.Services.Description {

    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Xml.Serialization.Advanced;
    using System.Xml.Schema;
    using System.Collections;
    using System;
    using System.Data;
    using System.Data.Design;
    using System.Reflection;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using System.Web.Services.Configuration;
    using System.Diagnostics;
    using System.ComponentModel;
    using System.Security.Permissions;
    using System.Globalization;
    using System.Threading;
    
    internal class SoapParameters {
        XmlMemberMapping ret;
        ArrayList parameters = new ArrayList();
        ArrayList inParameters = new ArrayList();
        ArrayList outParameters = new ArrayList();
        int checkSpecifiedCount;
        int inCheckSpecifiedCount;
        int outCheckSpecifiedCount;

        internal SoapParameters(XmlMembersMapping request, XmlMembersMapping response, string[] parameterOrder, CodeIdentifiers identifiers) {
            ArrayList requestList = new ArrayList();
            ArrayList responseList = new ArrayList();

            AddMappings(requestList, request);
            if (response != null) AddMappings(responseList, response);

            if (parameterOrder != null) {
                for (int i = 0; i < parameterOrder.Length; i++) {
                    string elementName = parameterOrder[i];
                    XmlMemberMapping requestMapping = FindMapping(requestList, elementName);
                    SoapParameter parameter = new SoapParameter();
                    if (requestMapping != null) {
                        if (RemoveByRefMapping(responseList, requestMapping))
                            parameter.codeFlags = CodeFlags.IsByRef;
                        parameter.mapping = requestMapping;
                        requestList.Remove(requestMapping);
                        AddParameter(parameter);
                    }
                    else {
                        XmlMemberMapping responseMapping = FindMapping(responseList, elementName);
                        if (responseMapping != null) {
                            parameter.codeFlags = CodeFlags.IsOut;
                            parameter.mapping = responseMapping;
                            responseList.Remove(responseMapping);
                            AddParameter(parameter);
                        }
                    }
                }
            }

            foreach (XmlMemberMapping requestMapping in requestList) {
                SoapParameter parameter = new SoapParameter();
                if (RemoveByRefMapping(responseList, requestMapping))
                    parameter.codeFlags = CodeFlags.IsByRef;
                parameter.mapping = requestMapping;
                AddParameter(parameter);
            }

            if (responseList.Count > 0) {
                if (!((XmlMemberMapping) responseList[0]).CheckSpecified) {
                    ret = (XmlMemberMapping)responseList[0];
                    responseList.RemoveAt(0);
                }
                foreach (XmlMemberMapping responseMapping in responseList) {
                    SoapParameter parameter = new SoapParameter();
                    parameter.mapping = responseMapping;
                    parameter.codeFlags = CodeFlags.IsOut;
                    AddParameter(parameter);
                }
            }

            foreach (SoapParameter parameter in parameters) {
                parameter.name = identifiers.MakeUnique(CodeIdentifier.MakeValid(parameter.mapping.MemberName));
            }
        }

        void AddParameter(SoapParameter parameter) {
            parameters.Add(parameter);
            if (parameter.mapping.CheckSpecified) {
                checkSpecifiedCount++;
            }
            if (parameter.IsByRef) {
                inParameters.Add(parameter);
                outParameters.Add(parameter);
                if (parameter.mapping.CheckSpecified) {
                    inCheckSpecifiedCount++;
                    outCheckSpecifiedCount++;
                }
            } else if (parameter.IsOut) {
                outParameters.Add(parameter);
                if (parameter.mapping.CheckSpecified)
                    outCheckSpecifiedCount++;
            }
            else {
                inParameters.Add(parameter);
                if (parameter.mapping.CheckSpecified)
                    inCheckSpecifiedCount++;
            }
        }

        static bool RemoveByRefMapping(ArrayList responseList, XmlMemberMapping requestMapping) {
            XmlMemberMapping responseMapping = FindMapping(responseList, requestMapping.ElementName);
            if (responseMapping == null) return false;
            if (requestMapping.TypeFullName != responseMapping.TypeFullName) return false;
            if (requestMapping.Namespace != responseMapping.Namespace) return false;
            if (requestMapping.MemberName != responseMapping.MemberName) return false;
            responseList.Remove(responseMapping);
            return true;
        }

        static void AddMappings(ArrayList mappingsList, XmlMembersMapping mappings) {
            for (int i = 0; i < mappings.Count; i++) {
                mappingsList.Add(mappings[i]);
            }
        }

        static XmlMemberMapping FindMapping(ArrayList mappingsList, string elementName) {
            foreach (XmlMemberMapping mapping in mappingsList)
                if (mapping.ElementName == elementName)
                    return mapping;
            return null;
        }

        internal XmlMemberMapping Return {
            get { return ret; }
        }

        internal IList Parameters {
            get { return parameters; }
        }

        internal IList InParameters {
            get { return inParameters; }
        }

        internal IList OutParameters {
            get { return outParameters; }
        }
        
        internal int CheckSpecifiedCount {
            get { return checkSpecifiedCount; }
        }
        
        internal int InCheckSpecifiedCount {
            get { return inCheckSpecifiedCount; }
        }
        
        internal int OutCheckSpecifiedCount {
            get { return outCheckSpecifiedCount; }
        }
    }

    internal class SoapParameter {
        internal CodeFlags codeFlags;
        internal string name;
        internal XmlMemberMapping mapping;
        internal string specifiedName;

        internal bool IsOut {
            get { return (codeFlags & CodeFlags.IsOut) != 0; }
        }

        internal bool IsByRef {
            get { return (codeFlags & CodeFlags.IsByRef) != 0; }
        }

        internal static string[] GetTypeFullNames(IList parameters, int specifiedCount, CodeDomProvider codeProvider) {
            string[] typeFullNames = new string[parameters.Count + specifiedCount];
            GetTypeFullNames(parameters, typeFullNames, 0, specifiedCount, codeProvider);
            return typeFullNames;
        }

        internal static void GetTypeFullNames(IList parameters, string[] typeFullNames, int start, int specifiedCount, CodeDomProvider codeProvider) {
            int specified = 0;
            for (int i = 0; i < parameters.Count; i++) {
                typeFullNames[i + start + specified] = WebCodeGenerator.FullTypeName(((SoapParameter)parameters[i]).mapping, codeProvider);
                if (((SoapParameter) parameters[i]).mapping.CheckSpecified) {
                    specified++;
                    typeFullNames[i + start + specified] = typeof(bool).FullName;
                }
            }
        }

        internal static string[] GetNames(IList parameters, int specifiedCount) {
            string[] names = new string[parameters.Count + specifiedCount];
            GetNames(parameters, names, 0, specifiedCount);
            return names;
        }

        internal static void GetNames(IList parameters, string[] names, int start, int specifiedCount) {
            int specified = 0;
            for (int i = 0; i < parameters.Count; i++) {
                names[i + start + specified] = ((SoapParameter)parameters[i]).name;
                if (((SoapParameter) parameters[i]).mapping.CheckSpecified) {
                    specified++;
                    names[i + start + specified] = ((SoapParameter) parameters[i]).specifiedName;
                }
            }
        }

        internal static CodeFlags[] GetCodeFlags(IList parameters, int specifiedCount) {
            CodeFlags[] codeFlags = new CodeFlags[parameters.Count + specifiedCount];
            GetCodeFlags(parameters, codeFlags, 0, specifiedCount);
            return codeFlags;
        }

        internal static void GetCodeFlags(IList parameters, CodeFlags[] codeFlags, int start, int specifiedCount) {
            int specified = 0;
            for (int i = 0; i < parameters.Count; i++) {
                codeFlags[i + start + specified] = ((SoapParameter)parameters[i]).codeFlags;
                if (((SoapParameter) parameters[i]).mapping.CheckSpecified) {
                    specified++;
                    codeFlags[i + start + specified] = ((SoapParameter) parameters[i]).codeFlags;
                }
            }
        }
    }

    internal class GlobalSoapHeader {
        internal string fieldName;        
        internal XmlTypeMapping mapping;  
        internal bool isEncoded;      
    }
    
    internal class LocalSoapHeader {
        internal SoapHeaderDirection direction;        
        internal string fieldName;        
    }
            
    /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter"]/*' />
    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
    [PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")]
    public class SoapProtocolImporter : ProtocolImporter {
        XmlSchemaImporter xmlImporter;
        XmlCodeExporter xmlExporter;
        SoapSchemaImporter soapImporter;
        SoapCodeExporter soapExporter;
        ArrayList xmlMembers = new ArrayList();        
        ArrayList soapMembers = new ArrayList();
        Hashtable headers = new Hashtable();
        Hashtable classHeaders = new Hashtable();
        ArrayList propertyNames = new ArrayList();
        ArrayList propertyValues = new ArrayList();
        SoapExtensionImporter[] extensions;
        SoapTransportImporter transport;
        SoapBinding soapBinding;
        ArrayList codeClasses = new ArrayList();
        static TypedDataSetSchemaImporterExtension typedDataSetSchemaImporterExtension;

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.ProtocolName"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public override string ProtocolName {
            get { return "Soap"; }
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.SoapBinding"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public SoapBinding SoapBinding {
            get { return soapBinding; }
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.SoapImporter"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public SoapSchemaImporter SoapImporter {
            get { return soapImporter; }
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.XmlImporter"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlSchemaImporter XmlImporter {
            get { return xmlImporter; }
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.XmlExporter"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public XmlCodeExporter XmlExporter {
            get { return xmlExporter; }
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.SoapExporter"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public SoapCodeExporter SoapExporter {
            get { return soapExporter; }
        }

        static TypedDataSetSchemaImporterExtension TypedDataSetSchemaImporterExtension {
            get {
                if (typedDataSetSchemaImporterExtension == null) {
                    typedDataSetSchemaImporterExtension = new TypedDataSetSchemaImporterExtension();
                }
                return typedDataSetSchemaImporterExtension;
            }
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.BeginNamespace"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override void BeginNamespace() {
            try {
                MethodNames.Clear();
                ExtraCodeClasses.Clear();
                soapImporter = new SoapSchemaImporter(AbstractSchemas, ServiceImporter.CodeGenerationOptions, ImportContext);
                xmlImporter = new XmlSchemaImporter(ConcreteSchemas, ServiceImporter.CodeGenerationOptions, ServiceImporter.CodeGenerator, ImportContext);
                foreach (Type extensionType in ServiceImporter.Extensions) {
                    xmlImporter.Extensions.Add(extensionType.FullName, extensionType);
                }
                // use cached version of typed DataSetSchemaImporterExtension for /sharetypes feature
                // 
                xmlImporter.Extensions.Add(TypedDataSetSchemaImporterExtension);
                xmlImporter.Extensions.Add(new DataSetSchemaImporterExtension());
                xmlExporter = new XmlCodeExporter(this.CodeNamespace, ServiceImporter.CodeCompileUnit, ServiceImporter.CodeGenerator, ServiceImporter.CodeGenerationOptions, ExportContext);
                soapExporter = new SoapCodeExporter(this.CodeNamespace, null, ServiceImporter.CodeGenerator, ServiceImporter.CodeGenerationOptions, ExportContext);
            }
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
                    throw;
                }
                throw new InvalidOperationException(Res.GetString(Res.InitFailed), e);
            }
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.EndNamespace"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override void EndNamespace() {
            // need to preprocess all exported schemas to make sure that IXmlSerializable schemas are Merged and the resulting set is valid
            ConcreteSchemas.Compile(null, false);

            foreach (GlobalSoapHeader soapHeader in headers.Values) {
                if (soapHeader.isEncoded)
                    soapExporter.ExportTypeMapping(soapHeader.mapping);
                else
                    xmlExporter.ExportTypeMapping(soapHeader.mapping);
            }

            foreach (XmlMembersMapping member in xmlMembers)
                xmlExporter.ExportMembersMapping(member);

            foreach (XmlMembersMapping member in soapMembers)
                soapExporter.ExportMembersMapping(member);

            // NOTE, Microsoft, we are sharing the SoapInclude and XmlInclude attributes of the 
            // class among ALL classes generated, This is probably OK, since doing to per 
            // class would probably result in the same set of includes if the user
            // has object as a return value (meaning 'all' types are OK).
            foreach (CodeTypeDeclaration codeClass in codeClasses) {
                foreach (CodeAttributeDeclaration attribute in xmlExporter.IncludeMetadata) {
                    codeClass.CustomAttributes.Add(attribute);
                }
                foreach (CodeAttributeDeclaration attribute in soapExporter.IncludeMetadata) {
                    codeClass.CustomAttributes.Add(attribute);
                }
            }
            foreach (CodeTypeDeclaration declaration in ExtraCodeClasses) {
                this.CodeNamespace.Types.Add(declaration);
            }
            CodeGenerator.ValidateIdentifiers(CodeNamespace);
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.IsBindingSupported"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override bool IsBindingSupported() {
            SoapBinding soapBinding = (SoapBinding)Binding.Extensions.Find(typeof(SoapBinding));
            if (soapBinding == null || soapBinding.GetType() != typeof(SoapBinding)) return false;

            if (GetTransport(soapBinding.Transport) == null) {
                UnsupportedBindingWarning(Res.GetString(Res.ThereIsNoSoapTransportImporterThatUnderstands1, soapBinding.Transport));
                return false;
            }

            return true;
        }

        internal SoapTransportImporter GetTransport(string transport) {
            foreach (Type type in WebServicesSection.Current.SoapTransportImporters)
            {
                SoapTransportImporter transportImporter = (SoapTransportImporter)Activator.CreateInstance(type);
                transportImporter.ImportContext = this;
                if (transportImporter.IsSupportedTransport(transport)) return transportImporter;
            }
            return null;
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.BeginClass"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override CodeTypeDeclaration BeginClass() {
            MethodNames.Clear();

            soapBinding = (SoapBinding)Binding.Extensions.Find(typeof(SoapBinding));
            transport = GetTransport(soapBinding.Transport);

            Type[] requiredTypes = new Type[] { typeof(SoapDocumentMethodAttribute), typeof(XmlAttributeAttribute), typeof(WebService), typeof(Object), typeof(DebuggerStepThroughAttribute), typeof(DesignerCategoryAttribute) };
            WebCodeGenerator.AddImports(this.CodeNamespace, WebCodeGenerator.GetNamespacesForTypes(requiredTypes));
            CodeFlags flags = 0;
            if (Style == ServiceDescriptionImportStyle.Server)
                flags = CodeFlags.IsAbstract;
            else if (Style == ServiceDescriptionImportStyle.ServerInterface)
                flags = CodeFlags.IsInterface;
            CodeTypeDeclaration codeClass = WebCodeGenerator.CreateClass(this.ClassName, null, 
                new string[0], null, CodeFlags.IsPublic | flags,
                ServiceImporter.CodeGenerator.Supports(GeneratorSupport.PartialTypes));

            codeClass.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true));
            if (Style == ServiceDescriptionImportStyle.Client) {
                codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DebuggerStepThroughAttribute).FullName));
                codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DesignerCategoryAttribute).FullName, new CodeAttributeArgument[] { new CodeAttributeArgument(new CodePrimitiveExpression("code")) }));
            }
            else if (Style == ServiceDescriptionImportStyle.Server) {
                CodeAttributeDeclaration webService = new CodeAttributeDeclaration(typeof(WebServiceAttribute).FullName);
                string targetNs = Service != null ? Service.ServiceDescription.TargetNamespace : Binding.ServiceDescription.TargetNamespace;
                webService.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(targetNs)));
                codeClass.CustomAttributes.Add(webService);
            }

            CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(WebServiceBindingAttribute).FullName);
            attribute.Arguments.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(XmlConvert.DecodeName(Binding.Name))));
            attribute.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(Binding.ServiceDescription.TargetNamespace)));

            codeClass.CustomAttributes.Add(attribute);

            codeClasses.Add(codeClass);
            classHeaders.Clear();
            return codeClass;
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.EndClass"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override void EndClass() { 
            if (transport != null)
                transport.ImportClass();
            soapBinding = null;
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.IsOperationFlowSupported"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override bool IsOperationFlowSupported(OperationFlow flow) {
            return flow == OperationFlow.OneWay || flow == OperationFlow.RequestResponse;
        }

        void BeginMetadata() {
            propertyNames.Clear();
            propertyValues.Clear();
        }

        bool MetadataPropertiesAdded {
            get { return propertyNames.Count > 0; }
        }

        void AddMetadataProperty(string name, object value) {
            AddMetadataProperty(name, new CodePrimitiveExpression(value));
        }

        void AddMetadataProperty(string name, CodeExpression expr) {
            propertyNames.Add(name);
            propertyValues.Add(expr);
        }

        void EndMetadata(CodeAttributeDeclarationCollection metadata, Type attributeType, string parameter) {
            CodeExpression[] parameters;
            if (parameter == null) {
                parameters = new CodeExpression[0];
            }
            else {
                parameters = new CodeExpression[1] { new CodePrimitiveExpression(parameter) };
            }
            WebCodeGenerator.AddCustomAttribute(metadata, attributeType, parameters, 
                                  (string[])propertyNames.ToArray(typeof(string)), 
                                  (CodeExpression[])propertyValues.ToArray(typeof(CodeExpression)));
        }

        void GenerateExtensionMetadata(CodeAttributeDeclarationCollection metadata) {
            if (extensions == null) {
                TypeElementCollection extensionTypes = WebServicesSection.Current.SoapExtensionImporterTypes;
                extensions = new SoapExtensionImporter[extensionTypes.Count];
                for (int i = 0; i < extensions.Length; i++) {
                    SoapExtensionImporter extension = (SoapExtensionImporter)Activator.CreateInstance(extensionTypes[i].Type);
                    extension.ImportContext = this;
                    extensions[i] = extension;
                }
            }
            foreach (SoapExtensionImporter extension in extensions) {
                extension.ImportMethod(metadata);
            }
        }

        void PrepareHeaders(MessageBinding messageBinding) {
            // By default, map all headers to properties on the generated class
            // ExtensionImporters can modify this behavior by clearing the flag
            SoapHeaderBinding[] headers = (SoapHeaderBinding[])messageBinding.Extensions.FindAll(typeof(SoapHeaderBinding));
            foreach (SoapHeaderBinding header in headers) {
                header.MapToProperty = true;
            }
        }

        void GenerateHeaders(CodeAttributeDeclarationCollection metadata, SoapBindingUse use, bool rpc, MessageBinding requestMessage, MessageBinding responseMessage) { 
            Hashtable localHeaders = new Hashtable();

            for (int i = 0; i < 2; ++i) {
                MessageBinding messageBinding;
                SoapHeaderDirection direction;
                if (i == 0) {
                    messageBinding = requestMessage;
                    direction = SoapHeaderDirection.In;
                }
                else if (responseMessage != null) {
                    messageBinding = responseMessage;
                    direction = SoapHeaderDirection.Out;
                }
                else
                    continue;

                SoapHeaderBinding[] headerBindings = (SoapHeaderBinding[])messageBinding.Extensions.FindAll(typeof(SoapHeaderBinding));
                foreach (SoapHeaderBinding header in headerBindings) {
                    // Skip headers which should not be mapped to properties (extension importers can control this)
                    if (!header.MapToProperty) continue;

                    if (use != header.Use) throw new InvalidOperationException(Res.GetString(Res.WebDescriptionHeaderAndBodyUseMismatch));
                    if (use == SoapBindingUse.Encoded && !IsSoapEncodingPresent(header.Encoding) )
                        throw new InvalidOperationException(Res.GetString(Res.WebUnknownEncodingStyle, header.Encoding));

                    Message message = ServiceDescriptions.GetMessage(header.Message);
                    if (message == null) throw new InvalidOperationException(Res.GetString(Res.MissingMessage2, header.Message.Name, header.Message.Namespace));

                    MessagePart part = message.FindPartByName(header.Part);
                    if (part == null) throw new InvalidOperationException(Res.GetString(Res.MissingMessagePartForMessageFromNamespace3, part.Name, header.Message.Name, header.Message.Namespace));

                    XmlTypeMapping mapping;
                    string key;
                    if (use == SoapBindingUse.Encoded) {
                        if (part.Type.IsEmpty) throw new InvalidOperationException(Res.GetString(Res.WebDescriptionPartTypeRequired, part.Name, header.Message.Name, header.Message.Namespace));
                        if (!part.Element.IsEmpty) UnsupportedOperationBindingWarning(Res.GetString(Res.WebDescriptionPartElementWarning, part.Name, header.Message.Name, header.Message.Namespace));
                        mapping = soapImporter.ImportDerivedTypeMapping(part.Type, typeof(SoapHeader), true);
                        key = "type=" + part.Type.ToString();
                    }
                    else {
                        if (part.Element.IsEmpty) throw new InvalidOperationException(Res.GetString(Res.WebDescriptionPartElementRequired, part.Name, header.Message.Name, header.Message.Namespace));
                        if (!part.Type.IsEmpty) UnsupportedOperationBindingWarning(Res.GetString(Res.WebDescriptionPartTypeWarning, part.Name, header.Message.Name, header.Message.Namespace));
                        mapping = xmlImporter.ImportDerivedTypeMapping(part.Element, typeof(SoapHeader), true);
                        key = "element=" + part.Element.ToString();
                    }
                    LocalSoapHeader localHeader = (LocalSoapHeader)localHeaders[key];
                    if (localHeader == null) {
                        GlobalSoapHeader globalHeader = (GlobalSoapHeader)classHeaders[key];
                        if (globalHeader == null) {
                            globalHeader = new GlobalSoapHeader();
                            globalHeader.isEncoded = use == SoapBindingUse.Encoded;
                            string fieldName = CodeIdentifier.MakeValid(mapping.ElementName);
                            if (fieldName == mapping.TypeName) fieldName += "Value";
                            fieldName = MethodNames.AddUnique(fieldName, mapping);
                            globalHeader.fieldName = fieldName;
                            WebCodeGenerator.AddMember(CodeTypeDeclaration, mapping.TypeFullName, globalHeader.fieldName, null, null, CodeFlags.IsPublic, ServiceImporter.CodeGenerationOptions);
                            globalHeader.mapping = mapping;
                            classHeaders.Add(key, globalHeader);
                            if (headers[key] == null)
                                headers.Add(key, globalHeader);
                        }

                        localHeader = new LocalSoapHeader();
                        localHeader.fieldName = globalHeader.fieldName;
                        localHeader.direction = direction;
                        localHeaders.Add(key, localHeader);
                    }
                    else {
                        if (localHeader.direction != direction)
                            localHeader.direction = SoapHeaderDirection.InOut;
                    }
                }
            }

            foreach (LocalSoapHeader soapHeader in localHeaders.Values) {
                BeginMetadata();
                if (soapHeader.direction == SoapHeaderDirection.Out) {
                    AddMetadataProperty("Direction", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SoapHeaderDirection).FullName), SoapHeaderDirection.Out.ToString()));
                }
                else if (soapHeader.direction == SoapHeaderDirection.InOut) { 
                    AddMetadataProperty("Direction", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SoapHeaderDirection).FullName), SoapHeaderDirection.InOut.ToString()));
                }

                EndMetadata(metadata, typeof(SoapHeaderAttribute), soapHeader.fieldName);
            }
        }

        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.GenerateMethod"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override CodeMemberMethod GenerateMethod() {
            Message requestMessage;
            Message responseMessage;
            string[] parameterOrder;
            SoapBodyBinding soapRequestBinding;
            SoapBodyBinding soapResponseBinding;
            MessageBinding requestBinding;
            MessageBinding responseBinding;

            SoapOperationBinding soapOperationBinding = (SoapOperationBinding)this.OperationBinding.Extensions.Find(typeof(SoapOperationBinding));
            if (soapOperationBinding == null) throw OperationBindingSyntaxException(Res.GetString(Res.MissingSoapOperationBinding0));

            SoapBindingStyle soapBindingStyle = soapOperationBinding.Style;
            if (soapBindingStyle == SoapBindingStyle.Default)
                soapBindingStyle = SoapBinding.Style;
            if (soapBindingStyle == SoapBindingStyle.Default)
                soapBindingStyle = SoapBindingStyle.Document;

            parameterOrder = this.Operation.ParameterOrder;

            requestMessage = this.InputMessage;
            requestBinding = this.OperationBinding.Input;
            soapRequestBinding = (SoapBodyBinding)this.OperationBinding.Input.Extensions.Find(typeof(SoapBodyBinding));
            if (soapRequestBinding == null) {
                UnsupportedOperationBindingWarning(Res.GetString(Res.MissingSoapBodyInputBinding0));
                return null;
            }

            if (this.Operation.Messages.Output != null) {
                responseMessage = this.OutputMessage;
                responseBinding = this.OperationBinding.Output;
                soapResponseBinding = (SoapBodyBinding)this.OperationBinding.Output.Extensions.Find(typeof(SoapBodyBinding));
                if (soapResponseBinding == null) {
                    UnsupportedOperationBindingWarning(Res.GetString(Res.MissingSoapBodyOutputBinding0));
                    return null;
                }
            }
            else {
                responseMessage = null;
                responseBinding = null;
                soapResponseBinding = null;
            }

            CodeAttributeDeclarationCollection metadata = new CodeAttributeDeclarationCollection();

            PrepareHeaders(requestBinding);
            if (responseBinding != null) PrepareHeaders(responseBinding);

            string requestMessageName;
            string responseMessageName = null;

            requestMessageName = !String.IsNullOrEmpty(requestBinding.Name) && soapBindingStyle != SoapBindingStyle.Rpc ? requestBinding.Name : this.Operation.Name; // per WSDL 1.1 sec 3.5
            requestMessageName = XmlConvert.DecodeName(requestMessageName);

            if (responseBinding != null) {
                responseMessageName = !String.IsNullOrEmpty(responseBinding.Name) && soapBindingStyle != SoapBindingStyle.Rpc ? responseBinding.Name : this.Operation.Name + "Response"; // per WSDL 1.1 sec 3.5
                responseMessageName = XmlConvert.DecodeName(responseMessageName);
            }

            GenerateExtensionMetadata(metadata);
            GenerateHeaders(metadata, soapRequestBinding.Use, soapBindingStyle == SoapBindingStyle.Rpc, requestBinding, responseBinding);

            MessagePart[] requestParts = GetMessageParts(requestMessage, soapRequestBinding);
            bool hasWrapper;
            if (!CheckMessageStyles(MethodName, requestParts, soapRequestBinding, soapBindingStyle, out hasWrapper))
                return null;

            MessagePart[] responseParts = null;
            if (responseMessage != null) {
                responseParts = GetMessageParts(responseMessage, soapResponseBinding);
                bool responseHasWrapper;
                if (!CheckMessageStyles(MethodName, responseParts, soapResponseBinding, soapBindingStyle, out responseHasWrapper)) 
                    return null;

                // since we're using a potentially inaccurate heuristic to determine whether there's a wrapper,
                // if we disagree about the request and response we should assume there isn't a wrapper.
                if (hasWrapper != responseHasWrapper)
                    hasWrapper = false;
            }

            bool wrapperNamesMatter = (soapBindingStyle != SoapBindingStyle.Rpc && hasWrapper) || (soapRequestBinding.Use == SoapBindingUse.Literal && soapBindingStyle == SoapBindingStyle.Rpc);

            XmlMembersMapping request = ImportMessage(requestMessageName, requestParts, soapRequestBinding, soapBindingStyle, hasWrapper);
            if (request == null) return null;

            XmlMembersMapping response = null;

            if (responseMessage != null) {
                response = ImportMessage(responseMessageName, responseParts, soapResponseBinding, soapBindingStyle, hasWrapper);
                if (response == null) return null;
            }

            string methodName = CodeIdentifier.MakeValid(XmlConvert.DecodeName(this.Operation.Name));
            if (ClassName == methodName) {
                methodName = "Call" + methodName;
            }
            string uniqueMethodName = MethodNames.AddUnique(CodeIdentifier.MakeValid(XmlConvert.DecodeName(methodName)), this.Operation);
            bool differentNames = methodName != uniqueMethodName;

            CodeIdentifiers localIdentifiers = new CodeIdentifiers(false);
            localIdentifiers.AddReserved(uniqueMethodName);

            SoapParameters parameters = new SoapParameters(request, response, parameterOrder, MethodNames);

            foreach (SoapParameter param in parameters.Parameters) {
                if ((param.IsOut || param.IsByRef) && !ServiceImporter.CodeGenerator.Supports(GeneratorSupport.ReferenceParameters)) {
                    UnsupportedOperationWarning(Res.GetString(Res.CodeGenSupportReferenceParameters, ServiceImporter.CodeGenerator.GetType().Name));
                    return null;
                }
                param.name = localIdentifiers.AddUnique(param.name, null);
                if (param.mapping.CheckSpecified)
                    param.specifiedName = localIdentifiers.AddUnique(param.name + "Specified", null);
            }

            if (!(Style == ServiceDescriptionImportStyle.Client) || differentNames) {
                BeginMetadata();
                if (differentNames) AddMetadataProperty("MessageName", uniqueMethodName);
                EndMetadata(metadata, typeof(WebMethodAttribute), null);
            }

            BeginMetadata();
            if (wrapperNamesMatter && request.ElementName.Length > 0 && request.ElementName != uniqueMethodName)
                AddMetadataProperty("RequestElementName", request.ElementName);
            if (request.Namespace != null)
                AddMetadataProperty("RequestNamespace", request.Namespace);
            if (response == null) {
                AddMetadataProperty("OneWay", true);                    
            }
            else {
                if (wrapperNamesMatter && response.ElementName.Length > 0 && response.ElementName != (uniqueMethodName + "Response"))
                    AddMetadataProperty("ResponseElementName", response.ElementName);
                if (response.Namespace != null)
                    AddMetadataProperty("ResponseNamespace", response.Namespace);                                     
            }

            if (soapBindingStyle == SoapBindingStyle.Rpc) {
                if (soapRequestBinding.Use != SoapBindingUse.Encoded) {
                    AddMetadataProperty("Use", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SoapBindingUse).FullName), Enum.Format(typeof(SoapBindingUse), soapRequestBinding.Use, "G")));
                }
                EndMetadata(metadata, typeof(SoapRpcMethodAttribute), soapOperationBinding.SoapAction);
            }
            else {
                AddMetadataProperty("Use", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SoapBindingUse).FullName), Enum.Format(typeof(SoapBindingUse), soapRequestBinding.Use, "G")));
                AddMetadataProperty("ParameterStyle", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SoapParameterStyle).FullName), Enum.Format(typeof(SoapParameterStyle), hasWrapper ? SoapParameterStyle.Wrapped : SoapParameterStyle.Bare, "G")));
                EndMetadata(metadata, typeof(SoapDocumentMethodAttribute), soapOperationBinding.SoapAction);
            }
            IsEncodedBinding = IsEncodedBinding || (soapRequestBinding.Use == SoapBindingUse.Encoded);

            CodeAttributeDeclarationCollection[] paramsMetadata = new CodeAttributeDeclarationCollection[parameters.Parameters.Count + parameters.CheckSpecifiedCount];
            int j = 0;
            CodeAttributeDeclaration ignoreAttribute = new CodeAttributeDeclaration(typeof(XmlIgnoreAttribute).FullName);
            foreach (SoapParameter parameter in parameters.Parameters) {
                paramsMetadata[j] = new CodeAttributeDeclarationCollection();
                if (soapRequestBinding.Use == SoapBindingUse.Encoded)
                    soapExporter.AddMappingMetadata(paramsMetadata[j], parameter.mapping, parameter.name != parameter.mapping.MemberName);
                else {
                    string ns = soapBindingStyle == SoapBindingStyle.Rpc ? parameter.mapping.Namespace : parameter.IsOut ? response.Namespace : request.Namespace;
                    bool forceUseMemberName = parameter.name != parameter.mapping.MemberName;
                    xmlExporter.AddMappingMetadata(paramsMetadata[j], parameter.mapping,  ns, forceUseMemberName);
                    if (parameter.mapping.CheckSpecified) {
                        j++;
                        paramsMetadata[j] = new CodeAttributeDeclarationCollection();
                        xmlExporter.AddMappingMetadata(paramsMetadata[j], parameter.mapping, ns, parameter.specifiedName != parameter.mapping.MemberName + "Specified");
                        paramsMetadata[j].Add(ignoreAttribute);
                    }
                }
                if (paramsMetadata[j].Count > 0  && !ServiceImporter.CodeGenerator.Supports(GeneratorSupport.ParameterAttributes)) {
                    UnsupportedOperationWarning(Res.GetString(Res.CodeGenSupportParameterAttributes, ServiceImporter.CodeGenerator.GetType().Name));
                    return null;
                }
                j++;
            }

            CodeFlags[] parameterFlags = SoapParameter.GetCodeFlags(parameters.Parameters, parameters.CheckSpecifiedCount);
            string[] parameterTypes = SoapParameter.GetTypeFullNames(parameters.Parameters, parameters.CheckSpecifiedCount, ServiceImporter.CodeGenerator);
            string returnType = parameters.Return == null ? typeof(void).FullName : WebCodeGenerator.FullTypeName(parameters.Return, ServiceImporter.CodeGenerator);

            CodeMemberMethod mainCodeMethod = WebCodeGenerator.AddMethod(this.CodeTypeDeclaration, methodName, 
                                        parameterFlags, 
                                        parameterTypes,
                                        SoapParameter.GetNames(parameters.Parameters, parameters.CheckSpecifiedCount),
                                        paramsMetadata,
                                        returnType,
                                        metadata, 
                                        CodeFlags.IsPublic | (Style == ServiceDescriptionImportStyle.Client ? 0 : CodeFlags.IsAbstract));

            mainCodeMethod.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true));

            if (parameters.Return != null) {
                if (soapRequestBinding.Use == SoapBindingUse.Encoded)
                    soapExporter.AddMappingMetadata(mainCodeMethod.ReturnTypeCustomAttributes, parameters.Return, parameters.Return.ElementName != uniqueMethodName + "Result");
                else
                    xmlExporter.AddMappingMetadata(mainCodeMethod.ReturnTypeCustomAttributes, parameters.Return, response.Namespace, parameters.Return.ElementName != uniqueMethodName + "Result");

                if (mainCodeMethod.ReturnTypeCustomAttributes.Count != 0 && !ServiceImporter.CodeGenerator.Supports(GeneratorSupport.ReturnTypeAttributes)) {
                    UnsupportedOperationWarning(Res.GetString(Res.CodeGenSupportReturnTypeAttributes, ServiceImporter.CodeGenerator.GetType().Name));
                    return null;
                }
            }

            string resultsName = localIdentifiers.MakeUnique("results");

            if (Style == ServiceDescriptionImportStyle.Client) {
                bool oldAsync = (ServiceImporter.CodeGenerationOptions & CodeGenerationOptions.GenerateOldAsync) != 0;
                bool newAsync = (ServiceImporter.CodeGenerationOptions & CodeGenerationOptions.GenerateNewAsync) != 0 && 
                    ServiceImporter.CodeGenerator.Supports(GeneratorSupport.DeclareEvents) && 
                    ServiceImporter.CodeGenerator.Supports(GeneratorSupport.DeclareDelegates);
                CodeExpression[] invokeParams = new CodeExpression[2];
                CreateInvokeParams(invokeParams, uniqueMethodName, parameters.InParameters, parameters.InCheckSpecifiedCount);
                CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Invoke", invokeParams);
                WriteReturnMappings(mainCodeMethod, invoke, parameters, resultsName);

                if (oldAsync) {
                    int inCount = parameters.InParameters.Count + parameters.InCheckSpecifiedCount;

                    string[] asyncParameterTypes = new string[inCount + 2];
                    SoapParameter.GetTypeFullNames(parameters.InParameters, asyncParameterTypes, 0, parameters.InCheckSpecifiedCount, ServiceImporter.CodeGenerator);
                    asyncParameterTypes[inCount] = typeof(AsyncCallback).FullName;
                    asyncParameterTypes[inCount + 1] = typeof(object).FullName;

                    string[] asyncParameterNames = new string[inCount + 2];
                    SoapParameter.GetNames(parameters.InParameters, asyncParameterNames, 0, parameters.InCheckSpecifiedCount);
                    asyncParameterNames[inCount] = "callback";
                    asyncParameterNames[inCount + 1] = "asyncState";

                    CodeFlags[] asyncParameterFlags = new CodeFlags[inCount + 2];

                    CodeMemberMethod beginCodeMethod = WebCodeGenerator.AddMethod(this.CodeTypeDeclaration, "Begin" + uniqueMethodName, 
                        asyncParameterFlags,
                        asyncParameterTypes, 
                        asyncParameterNames, 
                        typeof(IAsyncResult).FullName, 
                        null, 
                        CodeFlags.IsPublic);

                    beginCodeMethod.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true));

                    invokeParams = new CodeExpression[4];
                    CreateInvokeParams(invokeParams, uniqueMethodName, parameters.InParameters, parameters.InCheckSpecifiedCount);
                    invokeParams[2] = new CodeArgumentReferenceExpression("callback");
                    invokeParams[3] = new CodeArgumentReferenceExpression("asyncState");

                    invoke = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "BeginInvoke", invokeParams);
                    beginCodeMethod.Statements.Add(new CodeMethodReturnStatement(invoke));

                    int outCount = parameters.OutParameters.Count + parameters.OutCheckSpecifiedCount;
                    string[] asyncReturnTypes = new string[outCount + 1];
                    SoapParameter.GetTypeFullNames(parameters.OutParameters, asyncReturnTypes, 1, parameters.OutCheckSpecifiedCount, ServiceImporter.CodeGenerator);
                    asyncReturnTypes[0] = typeof(IAsyncResult).FullName;

                    string[] asyncReturnNames = new string[outCount + 1];
                    SoapParameter.GetNames(parameters.OutParameters, asyncReturnNames, 1, parameters.OutCheckSpecifiedCount);
                    asyncReturnNames[0] = "asyncResult";

                    CodeFlags[] asyncReturnFlags = new CodeFlags[outCount + 1];
                    for (int i = 0; i < outCount; i++)
                        asyncReturnFlags[i + 1] = CodeFlags.IsOut;

                    CodeMemberMethod codeMethod = WebCodeGenerator.AddMethod(this.CodeTypeDeclaration, "End" + uniqueMethodName, 
                        asyncReturnFlags, 
                        asyncReturnTypes, 
                        asyncReturnNames, 
                        parameters.Return == null ? typeof(void).FullName : WebCodeGenerator.FullTypeName(parameters.Return, ServiceImporter.CodeGenerator), 
                        null, 
                        CodeFlags.IsPublic);

                    codeMethod.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true));

                    CodeExpression invokeParam = new CodeArgumentReferenceExpression("asyncResult");
                    invoke = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "EndInvoke", new CodeExpression[] { invokeParam });

                    WriteReturnMappings(codeMethod, invoke, parameters, resultsName);
                }

                // new RAD Async pattern
                if (newAsync) {
                    string methodKey = MethodSignature(uniqueMethodName, returnType, parameterFlags, parameterTypes);
                    DelegateInfo delegateInfo = (DelegateInfo)ExportContext[methodKey];
                    if (delegateInfo == null) {
                        string handlerType = ClassNames.AddUnique(uniqueMethodName + "CompletedEventHandler", uniqueMethodName);
                        string handlerArgs = ClassNames.AddUnique(uniqueMethodName + "CompletedEventArgs", uniqueMethodName);
                        delegateInfo = new DelegateInfo(handlerType, handlerArgs);
                    }
                    string handlerName = MethodNames.AddUnique(uniqueMethodName + "Completed", uniqueMethodName);
                    string asyncName = MethodNames.AddUnique(uniqueMethodName + "Async", uniqueMethodName);
                    string callbackMember = MethodNames.AddUnique(uniqueMethodName + "OperationCompleted", uniqueMethodName);
                    string callbackName = MethodNames.AddUnique("On" + uniqueMethodName + "OperationCompleted", uniqueMethodName);

                    // public event xxxCompletedEventHandler xxxCompleted;
                    WebCodeGenerator.AddEvent(this.CodeTypeDeclaration.Members, delegateInfo.handlerType, handlerName);

                    // private SendOrPostCallback xxxOperationCompleted;
                    WebCodeGenerator.AddCallbackDeclaration(this.CodeTypeDeclaration.Members, callbackMember);

                    // create the pair of xxxAsync methods
                    string[] inParamNames = SoapParameter.GetNames(parameters.InParameters, parameters.InCheckSpecifiedCount);
                    string userState = UniqueName("userState", inParamNames);
                    CodeMemberMethod asyncCodeMethod = WebCodeGenerator.AddAsyncMethod(this.CodeTypeDeclaration, asyncName, 
                        SoapParameter.GetTypeFullNames(parameters.InParameters, parameters.InCheckSpecifiedCount, ServiceImporter.CodeGenerator), inParamNames, callbackMember, callbackName, userState);

                    // Generate InvokeAsync call
                    invokeParams = new CodeExpression[4];
                    CreateInvokeParams(invokeParams, uniqueMethodName, parameters.InParameters, parameters.InCheckSpecifiedCount);
                    invokeParams[2] = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), callbackMember);
                    invokeParams[3] = new CodeArgumentReferenceExpression(userState);
                        
                    invoke = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InvokeAsync", invokeParams);
                    asyncCodeMethod.Statements.Add(invoke);

                    //  private void On_xxx_OperationCompleted(object arg) {..}
                    bool methodHasOutParameters = parameters.Return != null || parameters.OutParameters.Count > 0;
                    WebCodeGenerator.AddCallbackImplementation(this.CodeTypeDeclaration, callbackName, handlerName, delegateInfo.handlerArgs, methodHasOutParameters);

                    if (ExportContext[methodKey] == null) {
                        // public delegate void xxxCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs args);
                        WebCodeGenerator.AddDelegate(ExtraCodeClasses, delegateInfo.handlerType, methodHasOutParameters ? delegateInfo.handlerArgs : typeof(AsyncCompletedEventArgs).FullName);
                        
                        // Create strongly-typed Args class
                        if (methodHasOutParameters) {
                            int outCount = parameters.OutParameters.Count + parameters.OutCheckSpecifiedCount;
                            string[] asyncReturnTypes = new string[outCount + 1];
                            SoapParameter.GetTypeFullNames(parameters.OutParameters, asyncReturnTypes, 1, parameters.OutCheckSpecifiedCount, ServiceImporter.CodeGenerator);
                            asyncReturnTypes[0] = parameters.Return == null ? null : WebCodeGenerator.FullTypeName(parameters.Return, ServiceImporter.CodeGenerator);

                            string[] asyncReturnNames = new string[outCount + 1];
                            SoapParameter.GetNames(parameters.OutParameters, asyncReturnNames, 1, parameters.OutCheckSpecifiedCount);
                            asyncReturnNames[0] = parameters.Return == null ? null : "Result";
                            ExtraCodeClasses.Add(WebCodeGenerator.CreateArgsClass(delegateInfo.handlerArgs, asyncReturnTypes, asyncReturnNames, ServiceImporter.CodeGenerator.Supports(GeneratorSupport.PartialTypes)));
                        }
                        ExportContext[methodKey] = delegateInfo;
                    }
                }
            }
            return mainCodeMethod;
        }

        void WriteReturnMappings(CodeMemberMethod codeMethod, CodeExpression invoke, SoapParameters parameters, string resultsName) {
            if (parameters.Return == null && parameters.OutParameters.Count == 0) {
                codeMethod.Statements.Add(new CodeExpressionStatement(invoke));
            }
            else {
                codeMethod.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), resultsName, invoke));

                int count = parameters.Return == null ? 0 : 1;
                for (int i = 0; i < parameters.OutParameters.Count; i++) {
                    SoapParameter parameter = (SoapParameter)parameters.OutParameters[i];
                    CodeExpression target = new CodeArgumentReferenceExpression(parameter.name);
                    CodeExpression value = new CodeArrayIndexerExpression();
                    ((CodeArrayIndexerExpression)value).TargetObject = new CodeVariableReferenceExpression(resultsName);
                    ((CodeArrayIndexerExpression)value).Indices.Add(new CodePrimitiveExpression(count++));
                    value = new CodeCastExpression(WebCodeGenerator.FullTypeName(parameter.mapping, ServiceImporter.CodeGenerator), value);
                    codeMethod.Statements.Add(new CodeAssignStatement(target, value));
                    if (parameter.mapping.CheckSpecified) {
                        target = new CodeArgumentReferenceExpression(parameter.name + "Specified");
                        value = new CodeArrayIndexerExpression();
                        ((CodeArrayIndexerExpression) value).TargetObject = new CodeVariableReferenceExpression(resultsName);
                        ((CodeArrayIndexerExpression)value).Indices.Add(new CodePrimitiveExpression(count++));
                        value = new CodeCastExpression(typeof(bool).FullName, value);
                        codeMethod.Statements.Add(new CodeAssignStatement(target, value));
                    }
                }

                if (parameters.Return != null) {
                    CodeExpression value = new CodeArrayIndexerExpression();
                    ((CodeArrayIndexerExpression)value).TargetObject = new CodeVariableReferenceExpression(resultsName);
                    ((CodeArrayIndexerExpression)value).Indices.Add(new CodePrimitiveExpression(0));
                    value = new CodeCastExpression(WebCodeGenerator.FullTypeName(parameters.Return, ServiceImporter.CodeGenerator), value);
                    codeMethod.Statements.Add(new CodeMethodReturnStatement(value));
                }
            }
        }

        void CreateInvokeParams(CodeExpression[] invokeParams, string methodName, IList parameters, int checkSpecifiedCount) {
            invokeParams[0] = new CodePrimitiveExpression(methodName);

            CodeExpression[] values = new CodeExpression[parameters.Count + checkSpecifiedCount];
            int value = 0;
            for (int i = 0; i < parameters.Count; i++) {
                SoapParameter parameter = (SoapParameter)parameters[i];
                values[value++] = new CodeArgumentReferenceExpression(parameter.name);
                if (parameter.mapping.CheckSpecified)
                    values[value++] = new CodeArgumentReferenceExpression(parameter.specifiedName);
            }
            invokeParams[1] = new CodeArrayCreateExpression(typeof(object).FullName, values);
        }

        // returns false if we didn't like the message -- otherwise caller is safe to use body binding and binding style
        bool CheckMessageStyles(string messageName, MessagePart[] parts, SoapBodyBinding soapBodyBinding, SoapBindingStyle soapBindingStyle, out bool hasWrapper) {
            hasWrapper = false;
            if (soapBodyBinding.Use == SoapBindingUse.Default) {
                soapBodyBinding.Use = SoapBindingUse.Literal;
            }
            if (soapBodyBinding.Use == SoapBindingUse.Literal) {
                if (soapBindingStyle == SoapBindingStyle.Rpc) {
                    foreach (MessagePart part in parts) {
                        if (!part.Element.IsEmpty) {
                            UnsupportedOperationBindingWarning(Res.GetString(Res.EachMessagePartInRpcUseLiteralMessageMustSpecify0));
                            return false;
                        }
                    }
                    return true;
                }
                if (parts.Length == 1 && !parts[0].Type.IsEmpty) {
                    // special top-level any case
                    if (!parts[0].Element.IsEmpty) {
                        UnsupportedOperationBindingWarning(Res.GetString(Res.SpecifyingATypeForUseLiteralMessagesIs0));
                        return false;
                    }
                    XmlMembersMapping membersMapping = xmlImporter.ImportAnyType(parts[0].Type, parts[0].Name);
                    if (membersMapping == null) {
                        UnsupportedOperationBindingWarning(Res.GetString(Res.SpecifyingATypeForUseLiteralMessagesIsAny, parts[0].Type.Name, parts[0].Type.Namespace));
                        return false;
                    }
                    return true;
                }
                else {
                    foreach (MessagePart part in parts) {
                        if (!part.Type.IsEmpty) {
                            UnsupportedOperationBindingWarning(Res.GetString(Res.SpecifyingATypeForUseLiteralMessagesIs0));
                            return false;
                        }
                        if (part.Element.IsEmpty) {
                            UnsupportedOperationBindingWarning(Res.GetString(Res.EachMessagePartInAUseLiteralMessageMustSpecify0));
                            return false;
                        }
                    }
                }
            }
            else if (soapBodyBinding.Use == SoapBindingUse.Encoded) {
                if (!IsSoapEncodingPresent(soapBodyBinding.Encoding)) {
                    UnsupportedOperationBindingWarning(Res.GetString(Res.TheEncodingIsNotSupported1, soapBodyBinding.Encoding));
                    return false;
                }
                foreach (MessagePart part in parts) {
                    if (!part.Element.IsEmpty) {
                        UnsupportedOperationBindingWarning(Res.GetString(Res.SpecifyingAnElementForUseEncodedMessageParts0));
                        return false;
                    }
                    if (part.Type.IsEmpty) {
                        UnsupportedOperationBindingWarning(Res.GetString(Res.EachMessagePartInAnUseEncodedMessageMustSpecify0));
                        return false;
                    }
                }
            }

            if (soapBindingStyle == SoapBindingStyle.Rpc) {
                return true;
            }
            else if (soapBindingStyle == SoapBindingStyle.Document) {
                // NOTE, Microsoft.  WSDL doesn't really let us figure out whether a document is
                // in fact a struct containing parameters, so we apply a little heuristic here
                // in order to produce the appropriate programming model.
                hasWrapper = (parts.Length == 1 && string.Compare(parts[0].Name, "parameters", StringComparison.Ordinal) == 0);
                return true;
            }
            return false;
        }
        
        /// <include file='doc\SoapProtocolImporter.uex' path='docs/doc[@for="SoapProtocolImporter.IsSoapEncodingPresent"]/*' />
        /// <internalonly/>
        protected virtual bool IsSoapEncodingPresent(string uriList) {
            int iStart = 0;
            do {
                iStart = uriList.IndexOf(Soap.Encoding, iStart, StringComparison.Ordinal);
                if (iStart < 0)
                    return false;
                int iEnd = iStart + Soap.Encoding.Length;
                if (iStart == 0 || uriList[iStart - 1] == ' ')
                    if (iEnd == uriList.Length || uriList[iEnd] == ' ')
                        return true;
                iStart = iEnd;
            } while (iStart < uriList.Length);
            return false;
        }

        MessagePart[] GetMessageParts(Message message, SoapBodyBinding soapBodyBinding) {
            MessagePart[] parts;
            if (soapBodyBinding.Parts == null) {
                parts = new MessagePart[message.Parts.Count];
                message.Parts.CopyTo(parts, 0);
            }
            else {
                parts = message.FindPartsByName(soapBodyBinding.Parts);
            }
            return parts;
        }

        XmlMembersMapping ImportMessage(string messageName, MessagePart[] parts, SoapBodyBinding soapBodyBinding, SoapBindingStyle soapBindingStyle, bool wrapped) {
            if (soapBodyBinding.Use == SoapBindingUse.Encoded)
                return ImportEncodedMessage(messageName, parts, soapBodyBinding, wrapped);
            else
                return ImportLiteralMessage(messageName, parts, soapBodyBinding, soapBindingStyle, wrapped);
        }

        XmlMembersMapping ImportEncodedMessage(string messageName, MessagePart[] parts, SoapBodyBinding soapBodyBinding, bool wrapped) {
            XmlMembersMapping membersMapping;
            if (wrapped) {
                SoapSchemaMember schemaMember = new SoapSchemaMember();
                schemaMember.MemberName = parts[0].Name;
                schemaMember.MemberType = parts[0].Type;
                membersMapping = soapImporter.ImportMembersMapping(messageName, soapBodyBinding.Namespace, schemaMember);
            }
            else {
                SoapSchemaMember[] schemaMembers = new SoapSchemaMember[parts.Length];
                for (int i = 0; i < schemaMembers.Length; i++) {
                    MessagePart part = parts[i];
                    SoapSchemaMember schemaMember = new SoapSchemaMember();
                    schemaMember.MemberName = part.Name;
                    schemaMember.MemberType = part.Type;
                    schemaMembers[i] = schemaMember;
                }
                membersMapping = soapImporter.ImportMembersMapping(messageName, soapBodyBinding.Namespace, schemaMembers);
            } 
            soapMembers.Add(membersMapping);
            return membersMapping;
        }

        XmlMembersMapping ImportLiteralMessage(string messageName, MessagePart[] parts, SoapBodyBinding soapBodyBinding, SoapBindingStyle soapBindingStyle, bool wrapped) {
            XmlMembersMapping membersMapping;
            if (soapBindingStyle == SoapBindingStyle.Rpc) {
                SoapSchemaMember[] schemaMembers = new SoapSchemaMember[parts.Length];
                for (int i = 0; i < schemaMembers.Length; i++) {
                    MessagePart part = parts[i];
                    SoapSchemaMember schemaMember = new SoapSchemaMember();
                    schemaMember.MemberName = part.Name;
                    schemaMember.MemberType = part.Type;
                    schemaMembers[i] = schemaMember;
                }
                membersMapping = xmlImporter.ImportMembersMapping(messageName, soapBodyBinding.Namespace, schemaMembers);
            }
            else if (wrapped) {
                membersMapping = xmlImporter.ImportMembersMapping(parts[0].Element);
            }
            else {
                if (parts.Length == 1 && !parts[0].Type.IsEmpty) {
                    // special case for <any> at root
                    // we know this will work because we tried it earlier in CheckMessageStyles.
                    membersMapping = xmlImporter.ImportAnyType(parts[0].Type, parts[0].Name);
                    xmlMembers.Add(membersMapping);
                    return membersMapping;
                }
                XmlQualifiedName[] names = new XmlQualifiedName[parts.Length];
                for (int i = 0; i < parts.Length; i++)
                    names[i] = parts[i].Element;
                membersMapping = xmlImporter.ImportMembersMapping(names);
            }
            xmlMembers.Add(membersMapping);
            return membersMapping;
        }
    }
}