File: ProtocolImporter.cs

package info (click to toggle)
mono 2.6.7-5.1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 327,344 kB
  • ctags: 413,649
  • sloc: cs: 2,471,883; xml: 1,768,594; ansic: 350,665; sh: 13,644; makefile: 8,640; perl: 1,784; asm: 717; cpp: 209; python: 146; sql: 81; sed: 16
file content (862 lines) | stat: -rw-r--r-- 28,965 bytes parent folder | download | duplicates (5)
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
// 
// System.Web.Services.Description.ProtocolImporter.cs
//
// Author:
//   Tim Coleman (tim@timcoleman.com)
//   Lluis Sanchez Gual (lluis@ximian.com)
//
// Copyright (C) Tim Coleman, 2002
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Collections;
using System.Configuration;

namespace System.Web.Services.Description {
	public abstract class ProtocolImporter {

		#region Fields

		Binding binding;
		string className;
		CodeIdentifiers classNames;
		CodeNamespace codeNamespace;
		CodeTypeDeclaration codeTypeDeclaration;
		Message inputMessage;
		string methodName;
		Operation operation;
		OperationBinding operationBinding;
		Message outputMessage;		
		Port port;
		PortType portType;
		Service service;
		ServiceDescriptionImportWarnings warnings = (ServiceDescriptionImportWarnings)0;	
		ServiceDescriptionImporter descriptionImporter;
		ImportInfo iinfo;
		XmlSchemas xmlSchemas;
		XmlSchemas soapSchemas;
		
#if NET_2_0
		ArrayList asyncTypes = new ArrayList ();
#endif

		#endregion // Fields

		#region Constructors
	
		protected ProtocolImporter ()
		{
		}
		
		#endregion // Constructors

		#region Properties

		[MonoTODO]
		public XmlSchemas AbstractSchemas {
			get { return descriptionImporter.Schemas; }
		}

		public Binding Binding {
			get { return binding; }
		}

		public string ClassName {
			get { return className; }
		}

		public CodeIdentifiers ClassNames {
			get { return classNames; }
		}

		public CodeNamespace CodeNamespace {
			get { return codeNamespace; }
		}

		public CodeTypeDeclaration CodeTypeDeclaration {
			get { return codeTypeDeclaration; }
		}

		[MonoTODO]
		public XmlSchemas ConcreteSchemas {
			get { return descriptionImporter.Schemas; }
		}

		public Message InputMessage {
			get { return inputMessage; }
		}

		public string MethodName {
			get { return methodName; }
		}

		public Operation Operation {
			get { return operation; }
		}

		public OperationBinding OperationBinding {
			get { return operationBinding; }
		}

		public Message OutputMessage {
			get { return outputMessage; }
		}

		public Port Port {
			get { return port; }
		}

		public PortType PortType {
			get { return portType; }
		}

		public abstract string ProtocolName {
			get; 
		}

		public XmlSchemas Schemas {
			get { return descriptionImporter.Schemas; }
		}

		public Service Service {
			get { return service; } 
		}

		public ServiceDescriptionCollection ServiceDescriptions {
			get { return descriptionImporter.ServiceDescriptions; }
		}

		public ServiceDescriptionImportStyle Style {
			get { return descriptionImporter.Style; }
		}

		public ServiceDescriptionImportWarnings Warnings {
			get { return warnings; }
			set { warnings = value; }
		}
		
		internal ImportInfo ImportInfo
		{
			get { return iinfo; }
		}
		
		internal XmlSchemas LiteralSchemas
		{
			get { return xmlSchemas; }
		}
		
		internal XmlSchemas EncodedSchemas
		{
			get { return soapSchemas; }
		}
		
#if NET_2_0
		internal CodeGenerationOptions CodeGenerationOptions {
			get { return descriptionImporter.CodeGenerationOptions; }
		}
		
		internal CodeDomProvider CodeGenerator {
			get { return descriptionImporter.CodeGenerator; }
		}

		internal ImportContext ImportContext {
			get { return descriptionImporter.Context; }
		}
#endif

		#endregion // Properties

		#region Methods
		
		internal bool Import (ServiceDescriptionImporter descriptionImporter, CodeNamespace codeNamespace, ArrayList importInfo)
		{
			this.descriptionImporter = descriptionImporter;
			this.classNames = new CodeIdentifiers();;
			this.codeNamespace = codeNamespace;

			warnings = (ServiceDescriptionImportWarnings) 0;
			
			bool found = false;
			
			ClasifySchemas (importInfo);

			BeginNamespace ();
			
			foreach (ImportInfo info in importInfo)
			{
				foreach (Service service in info.ServiceDescription.Services)
				{
					this.service = service;
					int bindingCount = 0;
					foreach (Port port in service.Ports)
					{
						binding = ServiceDescriptions.GetBinding (port.Binding);
						if (IsBindingSupported ()) bindingCount ++;
					}
					
					foreach (Port port in service.Ports)
					{
						this.iinfo = info;
						this.port = port;
						binding = ServiceDescriptions.GetBinding (port.Binding);
						if (!IsBindingSupported ()) continue;
						
						found = true;
						ImportPortBinding (bindingCount > 1);
					}
				}
			}
			
			if (!found)
			{
				// Looks like MS.NET generates classes for all bindings if
				// no services are present
				
				foreach (ImportInfo info in importInfo)
				{
					this.iinfo = info;
					foreach (Binding b in info.ServiceDescription.Bindings)
					{
						this.binding = b;
						this.service = null;
						this.port = null;
						if (!IsBindingSupported ()) continue;
						found = true;
						ImportPortBinding (true);
					}
				}
			}

			EndNamespace ();
			
			if (!found) warnings = ServiceDescriptionImportWarnings.NoCodeGenerated;
			return found;
		}

		void ImportPortBinding (bool multipleBindings)
		{
			if (port != null) {
				if (multipleBindings) className = binding.Name;
				else className = service.Name;
			}
			else
				className = binding.Name;
			
			className = classNames.AddUnique (CodeIdentifier.MakeValid (className), port);
			className = className.Replace ("_x0020_", "");	// MS.NET seems to do this
			
			try
			{
				portType = ServiceDescriptions.GetPortType (binding.Type);
				if (portType == null) throw new Exception ("Port type not found: " + binding.Type);

				CodeTypeDeclaration codeClass = BeginClass ();
				codeTypeDeclaration = codeClass;
				AddCodeType (codeClass, port != null ? port.Documentation : null);
				codeClass.Attributes = MemberAttributes.Public;
			
				if (service != null && service.Documentation != null && service.Documentation != "")
					AddComments (codeClass, service.Documentation);

				if (Style == ServiceDescriptionImportStyle.Client) {
					CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Diagnostics.DebuggerStepThroughAttribute");
					AddCustomAttribute (codeClass, att, true);
	
					att = new CodeAttributeDeclaration ("System.ComponentModel.DesignerCategoryAttribute");
					att.Arguments.Add (GetArg ("code"));
					AddCustomAttribute (codeClass, att, true);
				}
				else
					codeClass.TypeAttributes = System.Reflection.TypeAttributes.Abstract | System.Reflection.TypeAttributes.Public;

				if (binding.Operations.Count == 0) {
					warnings |= ServiceDescriptionImportWarnings.NoMethodsGenerated;
					return;
				}
				
				foreach (OperationBinding oper in binding.Operations) 
				{
					operationBinding = oper;
					operation = FindPortOperation ();
					if (operation == null)
						throw new Exception ("Operation " + operationBinding.Name + " not found in portType " + PortType.Name);

					inputMessage = null;
					outputMessage = null;

					foreach (OperationMessage omsg in operation.Messages)
					{
						Message msg = ServiceDescriptions.GetMessage (omsg.Message);
						if (msg == null) throw new Exception ("Message not found: " + omsg.Message);
						
						if (omsg is OperationInput)
							inputMessage = msg;
						else
							outputMessage = msg;
					}
					
					CodeMemberMethod method = GenerateMethod ();
					
					if (method != null)
					{
						methodName = method.Name;
						if (operation.Documentation != null && operation.Documentation != "")
							AddComments (method, operation.Documentation);
#if NET_2_0
						if (Style == ServiceDescriptionImportStyle.Client)
							AddAsyncMembers (method.Name, method);
#endif
					}
				}
				
#if NET_2_0
			if (Style == ServiceDescriptionImportStyle.Client)
				AddAsyncTypes ();
#endif
				
				EndClass ();
			}
			catch (InvalidOperationException ex)
			{
				warnings |= ServiceDescriptionImportWarnings.NoCodeGenerated;
				UnsupportedBindingWarning (ex.Message);
			}
		}

		Operation FindPortOperation ()
		{
			string inMessage = null;
			string outMessage = null;
			int numMsg = 1;
			
			if (operationBinding.Input == null) throw new InvalidOperationException ("Input operation binding not found");
			inMessage = (operationBinding.Input.Name != null) ? operationBinding.Input.Name : operationBinding.Name;
				
			if (operationBinding.Output != null) {
				outMessage = (operationBinding.Output.Name != null) ? operationBinding.Output.Name : operationBinding.Name;
				numMsg++;
			}
			
			string operName = operationBinding.Name;
			
			Operation foundOper = null;
			foreach (Operation oper in PortType.Operations)
			{
				if (oper.Name == operName)
				{
					int hits = 0;
					foreach (OperationMessage omsg in oper.Messages)
					{
						if (omsg is OperationInput && GetOperMessageName (omsg, operName) == inMessage) hits++;
						if (omsg is OperationOutput && GetOperMessageName (omsg, operName) == outMessage) hits++;
					}
					if (hits == numMsg) return oper;
					foundOper = oper;
				}
			}
			return foundOper;
		}
		
		string GetOperMessageName (OperationMessage msg, string operName)
		{
			if (msg.Name == null) return operName;
			else return msg.Name;
		}
		
		internal void GenerateServiceUrl (string location, CodeStatementCollection stms)
		{
			if (ImportInfo.AppSettingUrlKey == null || ImportInfo.AppSettingUrlKey == string.Empty) {
				if (location != null) {
					CodeExpression ce = new CodeFieldReferenceExpression (new CodeThisReferenceExpression(), "Url");
					CodeAssignStatement cas = new CodeAssignStatement (ce, new CodePrimitiveExpression (location));
					stms.Add (cas);
				}
			}
			else
			{
				CodeExpression prop = new CodePropertyReferenceExpression (new CodeTypeReferenceExpression ("System.Configuration.ConfigurationSettings"), "AppSettings");
				prop = new CodeIndexerExpression (prop, new CodePrimitiveExpression (ImportInfo.AppSettingUrlKey));
				stms.Add (new CodeVariableDeclarationStatement (typeof(string), "urlSetting", prop));
				
				CodeExpression urlSetting = new CodeVariableReferenceExpression ("urlSetting");
				CodeExpression thisUrl = new CodeFieldReferenceExpression (new CodeThisReferenceExpression(), "Url");
				
				CodeStatement[] trueStms = new CodeStatement [1];
				CodeExpression ce = urlSetting;
				CodeExpression cond = new CodeBinaryOperatorExpression (urlSetting, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression (null));
				
				if (ImportInfo.AppSettingBaseUrl != null)
					ce = new CodeMethodInvokeExpression (new CodeTypeReferenceExpression (typeof(string)), "Concat", ce, new CodePrimitiveExpression (ImportInfo.AppSettingBaseUrl));
				trueStms [0] = new CodeAssignStatement (thisUrl, ce);
				
				if (location != null) {
					CodeStatement[] falseStms = new CodeStatement [1];
					falseStms [0] = new CodeAssignStatement (thisUrl, new CodePrimitiveExpression (location));
					stms.Add (new CodeConditionStatement (cond, trueStms, falseStms));
				}
				else
					stms.Add (new CodeConditionStatement (cond, trueStms));
			}
		}
		
		void ClasifySchemas (ArrayList importInfo)
		{
			// I don't like this, but I could not find any other way of clasifying
			// schemas between encoded and literal.
			
			xmlSchemas = new XmlSchemas ();
			soapSchemas = new XmlSchemas ();
			
			foreach (ImportInfo info in importInfo)
			{
				foreach (Service service in info.ServiceDescription.Services)
				{
					foreach (Port port in service.Ports)
					{
						this.iinfo = info;
						this.port = port;
						binding = ServiceDescriptions.GetBinding (port.Binding);
						if (binding == null) continue;
						portType = ServiceDescriptions.GetPortType (binding.Type);
						if (portType == null) continue;
						
						foreach (OperationBinding oper in binding.Operations) 
						{
							operationBinding = oper;
							operation = FindPortOperation ();
							if (operation == null) continue;
		
							foreach (OperationMessage omsg in operation.Messages)
							{
								Message msg = ServiceDescriptions.GetMessage (omsg.Message);
								if (msg == null) continue;
								
								if (omsg is OperationInput)
									inputMessage = msg;
								else
									outputMessage = msg;
							}
							
							if (GetMessageEncoding (oper.Input) == SoapBindingUse.Encoded)
								AddMessageSchema (soapSchemas, oper.Input, inputMessage);
							else
								AddMessageSchema (xmlSchemas, oper.Input, inputMessage);
							
							if (oper.Output != null) {
								if (GetMessageEncoding (oper.Output) == SoapBindingUse.Encoded)
									AddMessageSchema (soapSchemas, oper.Output, outputMessage);
								else
									AddMessageSchema (xmlSchemas, oper.Output, outputMessage);
							}
						}
					}
				}
			}
			
			XmlSchemas defaultList = xmlSchemas;
				
			if (xmlSchemas.Count == 0 && soapSchemas.Count > 0)
				defaultList = soapSchemas;
				
			// Schemas not referenced by any message
			foreach (XmlSchema sc in Schemas)
			{
				if (!soapSchemas.Contains (sc) && !xmlSchemas.Contains (sc)) {
					if (ImportsEncodedNamespace (sc))
						soapSchemas.Add (sc);
					else
						defaultList.Add (sc);
				}
			}
		}
			
		void AddMessageSchema (XmlSchemas schemas, MessageBinding mb, Message msg)
		{
			foreach (MessagePart part in msg.Parts)
			{
				if (part.Element != XmlQualifiedName.Empty)
					AddIncludingSchema (schemas, part.Element.Namespace);
				else if (part.Type != XmlQualifiedName.Empty)
					AddIncludingSchema (schemas, part.Type.Namespace);
			}
			SoapBodyBinding sbb = mb.Extensions.Find (typeof(SoapBodyBinding)) as SoapBodyBinding;
			if (sbb != null) AddIncludingSchema (schemas, sbb.Namespace);
		}
		
		void AddIncludingSchema (XmlSchemas list, string ns)
		{
			foreach (XmlSchema sc in Schemas) {
				if (sc.TargetNamespace == ns && !list.Contains (sc)) {
					list.Add (sc);
					foreach (XmlSchemaObject ob in sc.Includes) {
						XmlSchemaImport import = ob as XmlSchemaImport;
						if (import != null) AddIncludingSchema (list, import.Namespace);
					}
				}
			}
		}
		
		SoapBindingUse GetMessageEncoding (MessageBinding mb)
		{
			SoapBodyBinding sbb = mb.Extensions.Find (typeof(SoapBodyBinding)) as SoapBodyBinding;
			if (sbb == null)
			{
				if (mb is InputBinding) return SoapBindingUse.Encoded;
				else return SoapBindingUse.Literal;
			}
			else 
				if (sbb.Use == SoapBindingUse.Encoded) return SoapBindingUse.Encoded;
			else
				return SoapBindingUse.Literal;
		}
		
		bool ImportsEncodedNamespace (XmlSchema sc)
		{
			foreach (XmlSchemaObject ob in sc.Includes)
			{
				XmlSchemaImport import = ob as XmlSchemaImport;
				if (import == null)
					continue;
#if NET_2_0
				if (import.Namespace == Soap11BindingExtensionReflector.EncodingNamespace
				    || import.Namespace == Soap12BindingExtensionReflector.EncodingNamespace)
#else
				if (import.Namespace == Soap11BindingExtensionReflector.EncodingNamespace)
#endif
					return true;
			}
			return false;
		}
		
#if NET_2_0

		void AddAsyncTypes ()
		{
			foreach (CodeTypeDeclaration type in asyncTypes)
				codeNamespace.Types.Add (type);
			asyncTypes.Clear ();
		}

		void AddAsyncMembers (string messageName, CodeMemberMethod method)
		{
			CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
			CodePrimitiveExpression enull = new CodePrimitiveExpression (null);
			
			CodeMemberField codeField = new CodeMemberField (typeof(System.Threading.SendOrPostCallback), messageName + "OperationCompleted");
			codeField.Attributes = MemberAttributes.Private;
			CodeTypeDeclaration.Members.Add (codeField);
			
			// Event arguments class
			
			string argsClassName = classNames.AddUnique (messageName + "CompletedEventArgs", null);
			CodeTypeDeclaration argsClass = new CodeTypeDeclaration (argsClassName);
			argsClass.Attributes |= MemberAttributes.Public;
#if NET_2_0
			argsClass.IsPartial = true;
#endif
			argsClass.BaseTypes.Add (new CodeTypeReference ("System.ComponentModel.AsyncCompletedEventArgs"));

			CodeMemberField resultsField = new CodeMemberField (typeof(object[]), "results");
			resultsField.Attributes = MemberAttributes.Private;
			argsClass.Members.Add (resultsField);
			
			CodeConstructor cc = new CodeConstructor ();
			cc.Attributes = MemberAttributes.Assembly;
			cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object[]), "results"));
			cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof(System.Exception), "exception"));
			cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof(bool), "cancelled"));
			cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object), "userState"));
			cc.BaseConstructorArgs.Add (new CodeVariableReferenceExpression ("exception"));
			cc.BaseConstructorArgs.Add (new CodeVariableReferenceExpression ("cancelled"));
			cc.BaseConstructorArgs.Add (new CodeVariableReferenceExpression ("userState"));
			CodeExpression thisResults = new CodeFieldReferenceExpression (ethis, "results");
			cc.Statements.Add (new CodeAssignStatement (thisResults, new CodeVariableReferenceExpression ("results")));
			argsClass.Members.Add (cc);
			
			int ind = 0;
			
			if (method.ReturnType.BaseType != "System.Void")
				argsClass.Members.Add (CreateArgsProperty (method.ReturnType, "Result", ind++));
			
			foreach (CodeParameterDeclarationExpression par in method.Parameters) 
			{
				if (par.Direction == FieldDirection.Out || par.Direction == FieldDirection.Ref)
					argsClass.Members.Add (CreateArgsProperty (par.Type, par.Name, ind++));
			}
			
			bool needsArgsClass = (ind > 0);
			if (needsArgsClass)
				asyncTypes.Add (argsClass);
			else
				argsClassName = "System.ComponentModel.AsyncCompletedEventArgs";
			
			// Event delegate type
			
			CodeTypeDelegate delegateType = new CodeTypeDelegate (messageName + "CompletedEventHandler");
			delegateType.Attributes |= MemberAttributes.Public;
			delegateType.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object), "sender"));
			delegateType.Parameters.Add (new CodeParameterDeclarationExpression (argsClassName, "args"));
			
			// Event member
			
			CodeMemberEvent codeEvent = new CodeMemberEvent ();
			codeEvent.Attributes = codeEvent.Attributes & ~MemberAttributes.AccessMask | MemberAttributes.Public;
			codeEvent.Name = messageName + "Completed";
			codeEvent.Type = new CodeTypeReference (delegateType.Name);
			CodeTypeDeclaration.Members.Add (codeEvent);
			
			// Async method (without user state param)
			
			CodeMemberMethod am = new CodeMemberMethod ();
			am.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			am.Name = method.Name + "Async";
			am.ReturnType = new CodeTypeReference (typeof(void));
			CodeMethodInvokeExpression inv;
			inv = new CodeMethodInvokeExpression (ethis, am.Name);
			am.Statements.Add (inv);
			
			// On...Completed method
			
			CodeMemberMethod onCompleted = new CodeMemberMethod ();
			onCompleted.Name = "On" + messageName + "Completed";
			onCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final;
			onCompleted.ReturnType = new CodeTypeReference (typeof(void));
			onCompleted.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object), "arg"));
			
			CodeConditionStatement anIf = new CodeConditionStatement ();
			
			CodeExpression eventField = new CodeEventReferenceExpression (ethis, codeEvent.Name);
			anIf.Condition = new CodeBinaryOperatorExpression (eventField, CodeBinaryOperatorType.IdentityInequality, enull);
			CodeExpression castedArg = new CodeCastExpression (typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), new CodeVariableReferenceExpression ("arg"));
			CodeStatement invokeArgs = new CodeVariableDeclarationStatement (typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), "invokeArgs", castedArg);
			anIf.TrueStatements.Add (invokeArgs);
			
			CodeDelegateInvokeExpression delegateInvoke = new CodeDelegateInvokeExpression ();
			delegateInvoke.TargetObject = eventField;
			delegateInvoke.Parameters.Add (ethis);
			CodeObjectCreateExpression argsInstance = new CodeObjectCreateExpression (argsClassName);
			CodeExpression invokeArgsVar = new CodeVariableReferenceExpression ("invokeArgs");
			if (needsArgsClass) argsInstance.Parameters.Add (new CodeFieldReferenceExpression (invokeArgsVar, "Results"));
			argsInstance.Parameters.Add (new CodeFieldReferenceExpression (invokeArgsVar, "Error"));
			argsInstance.Parameters.Add (new CodeFieldReferenceExpression (invokeArgsVar, "Cancelled"));
			argsInstance.Parameters.Add (new CodeFieldReferenceExpression (invokeArgsVar, "UserState"));
			delegateInvoke.Parameters.Add (argsInstance);
			anIf.TrueStatements.Add (delegateInvoke);
			
			onCompleted.Statements.Add (anIf);
			
			// Async method
			
			CodeMemberMethod asyncMethod = new CodeMemberMethod ();
			asyncMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			asyncMethod.Name = method.Name + "Async";
			asyncMethod.ReturnType = new CodeTypeReference (typeof(void));
			
			CodeExpression delegateField = new CodeFieldReferenceExpression (ethis, codeField.Name);
			anIf = new CodeConditionStatement ();
			anIf.Condition = new CodeBinaryOperatorExpression (delegateField, CodeBinaryOperatorType.IdentityEquality, enull);;
			CodeExpression delegateRef = new CodeMethodReferenceExpression (ethis, onCompleted.Name);
			CodeExpression newDelegate = new CodeObjectCreateExpression (typeof(System.Threading.SendOrPostCallback), delegateRef);
			CodeAssignStatement cas = new CodeAssignStatement (delegateField, newDelegate);
			anIf.TrueStatements.Add (cas);
			asyncMethod.Statements.Add (anIf);
			
			CodeArrayCreateExpression paramsArray = new CodeArrayCreateExpression (typeof(object));
			
			// Assign parameters
			
			CodeIdentifiers paramsIds = new CodeIdentifiers ();
			
			foreach (CodeParameterDeclarationExpression par in method.Parameters) 
			{
				paramsIds.Add (par.Name, null);
				if (par.Direction == FieldDirection.In || par.Direction == FieldDirection.Ref) {
					CodeParameterDeclarationExpression inpar = new CodeParameterDeclarationExpression (par.Type, par.Name);
					am.Parameters.Add (inpar);
					asyncMethod.Parameters.Add (inpar);
					inv.Parameters.Add (new CodeVariableReferenceExpression (par.Name));
					paramsArray.Initializers.Add (new CodeVariableReferenceExpression (par.Name));
				}
			}


			inv.Parameters.Add (enull);
			
			string userStateName = paramsIds.AddUnique ("userState", null);
			asyncMethod.Parameters.Add (new CodeParameterDeclarationExpression (typeof(object), userStateName));
			
			CodeExpression userStateVar = new CodeVariableReferenceExpression (userStateName);
			asyncMethod.Statements.Add (BuildInvokeAsync (messageName, paramsArray, delegateField, userStateVar));
			
			CodeTypeDeclaration.Members.Add (am);
			CodeTypeDeclaration.Members.Add (asyncMethod);
			CodeTypeDeclaration.Members.Add (onCompleted);
			
			asyncTypes.Add (delegateType);
		}
		
		CodeMemberProperty CreateArgsProperty (CodeTypeReference type, string name, int ind)
		{
			CodeMemberProperty prop = new CodeMemberProperty ();
			prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			prop.HasGet = true;
			prop.HasSet = false;
			prop.Name = name;
			prop.Type = type;
			CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
			CodeExpression thisResults = new CodeFieldReferenceExpression (ethis, "results");
			prop.GetStatements.Add (new CodeMethodInvokeExpression (ethis, "RaiseExceptionIfNecessary"));
			CodeArrayIndexerExpression arrValue = new CodeArrayIndexerExpression (thisResults, new CodePrimitiveExpression (ind));
			CodeExpression retval = new CodeCastExpression (type, arrValue);
			prop.GetStatements.Add (new CodeMethodReturnStatement (retval));
			return prop;
		}
		
		internal virtual CodeExpression BuildInvokeAsync (string messageName, CodeArrayCreateExpression paramsArray, CodeExpression delegateField, CodeExpression userStateVar)
		{
			CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
			CodeMethodInvokeExpression inv2 = new CodeMethodInvokeExpression (ethis, "InvokeAsync");
			inv2.Parameters.Add (new CodePrimitiveExpression (messageName));
			inv2.Parameters.Add (paramsArray);
			inv2.Parameters.Add (delegateField);
			inv2.Parameters.Add (userStateVar);
			return inv2;
		}
#endif
		
		[MonoTODO]
		public void AddExtensionWarningComments (CodeCommentStatementCollection comments, ServiceDescriptionFormatExtensionCollection extensions) 
		{
			throw new NotImplementedException ();
		}

		protected abstract CodeTypeDeclaration BeginClass ();

		protected virtual void BeginNamespace ()
		{
		}

		protected virtual void EndClass ()
		{
		}

		protected virtual void EndNamespace ()
		{
		}

		protected abstract CodeMemberMethod GenerateMethod ();
		protected abstract bool IsBindingSupported ();
		protected abstract bool IsOperationFlowSupported (OperationFlow flow);
		
		[MonoTODO]
		public Exception OperationBindingSyntaxException (string text)
		{
			throw new NotImplementedException ();
		}

		[MonoTODO]
		public Exception OperationSyntaxException (string text)
		{
			throw new NotImplementedException ();
		}

		public void UnsupportedBindingWarning (string text)
		{
			warnings |= ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored;
			AddGlobalComments ("WARNING: Could not generate proxy for binding " + binding.Name + ". " + text);
		}

		public void UnsupportedOperationBindingWarning (string text)
		{
			warnings |= ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored;
			AddGlobalComments ("WARNING: Could not generate operation binding " + OperationBinding.Name + ". " + text);
		}

		public void UnsupportedOperationWarning (string text)
		{
			warnings |= ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored;
			AddGlobalComments ("WARNING: Could not generate operation " + Operation.Name + ". " + text);
		}

		void AddGlobalComments (string comments)
		{
			codeNamespace.Comments.Add (new CodeCommentStatement (comments, false));
		}

		void AddComments (CodeTypeMember member, string comments)
		{
			if (comments == null || comments == "") member.Comments.Add (new CodeCommentStatement ("<remarks/>", true));
			else member.Comments.Add (new CodeCommentStatement ("<remarks>\n" + comments + "\n</remarks>", true));
		}

		void AddCodeType (CodeTypeDeclaration type, string comments)
		{
			AddComments (type, comments);
			codeNamespace.Types.Add (type);
		}

		internal void AddCustomAttribute (CodeTypeMember ctm, CodeAttributeDeclaration att, bool addIfNoParams)
		{
			if (att.Arguments.Count == 0 && !addIfNoParams) return;
			
			if (ctm.CustomAttributes == null) ctm.CustomAttributes = new CodeAttributeDeclarationCollection ();
			ctm.CustomAttributes.Add (att);
		}

		internal void AddCustomAttribute (CodeTypeMember ctm, string name, params CodeAttributeArgument[] args)
		{
			if (ctm.CustomAttributes == null) ctm.CustomAttributes = new CodeAttributeDeclarationCollection ();
			ctm.CustomAttributes.Add (new CodeAttributeDeclaration (name, args));
		}

		internal CodeAttributeArgument GetArg (string name, object value)
		{
			return new CodeAttributeArgument (name, new CodePrimitiveExpression(value));
		}

		internal CodeAttributeArgument GetEnumArg (string name, string enumType, string enumValue)
		{
			return new CodeAttributeArgument (name, new CodeFieldReferenceExpression (new CodeTypeReferenceExpression(enumType), enumValue));
		}

		internal CodeAttributeArgument GetArg (object value)
		{
			return new CodeAttributeArgument (new CodePrimitiveExpression(value));
		}

		internal CodeAttributeArgument GetTypeArg (string name, string typeName)
		{
			return new CodeAttributeArgument (name, new CodeTypeOfExpression(typeName));
		}
		
		#endregion
	}
}