File: HttpProtocolImporter.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 (395 lines) | stat: -rw-r--r-- 21,824 bytes parent folder | download | duplicates (7)
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
//------------------------------------------------------------------------------
// <copyright file="HttpProtocolImporter.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </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.Schema;
    using System.Collections;
    using System;
    using System.Reflection;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using System.Web.Services.Configuration;
    using System.Diagnostics;
    using System.ComponentModel;
    using System.Threading;
    using System.EnterpriseServices;

    // 
    internal class HttpMethodInfo {
        internal MimeParameterCollection UrlParameters;
        internal MimeParameterCollection MimeParameters;
        internal MimeReturn MimeReturn;
        internal string Name;
        internal string Href;
    }

    internal abstract class HttpProtocolImporter : ProtocolImporter {
        MimeImporter[] importers;
        ArrayList[] importedParameters;
        ArrayList[] importedReturns;
        bool hasInputPayload;
        ArrayList codeClasses = new ArrayList();

        protected HttpProtocolImporter(bool hasInputPayload) {
            Type[] importerTypes = WebServicesSection.Current.MimeImporterTypes;
            importers = new MimeImporter[importerTypes.Length];
            importedParameters = new ArrayList[importerTypes.Length];
            importedReturns = new ArrayList[importerTypes.Length];
            for (int i = 0; i < importers.Length; i++) {
                MimeImporter importer = (MimeImporter)Activator.CreateInstance(importerTypes[i]);
                importer.ImportContext = this;
                importedParameters[i] = new ArrayList();
                importedReturns[i] = new ArrayList();
                importers[i] = importer;
            }
            this.hasInputPayload = hasInputPayload;
        }

        // 
        MimeParameterCollection ImportMimeParameters() {
            for (int i = 0; i < importers.Length; i++) {
                MimeParameterCollection importedParameters = importers[i].ImportParameters();
                if (importedParameters != null) {
                    this.importedParameters[i].Add(importedParameters);
                    return importedParameters;
                }
            }
            return null;
        }

        MimeReturn ImportMimeReturn() {
            MimeReturn importedReturn;
            if (OperationBinding.Output.Extensions.Count == 0) {
                importedReturn = new MimeReturn();
                importedReturn.TypeName = typeof(void).FullName;
                return importedReturn;
            }
            for (int i = 0; i < importers.Length; i++) {
                importedReturn = importers[i].ImportReturn();
                if (importedReturn != null) {
                    this.importedReturns[i].Add(importedReturn);
                    return importedReturn;
                }
            }
            return null;
        }

        MimeParameterCollection ImportUrlParameters() {
            // 
            HttpUrlEncodedBinding httpUrlEncodedBinding = (HttpUrlEncodedBinding)OperationBinding.Input.Extensions.Find(typeof(HttpUrlEncodedBinding));
            if (httpUrlEncodedBinding == null) return new MimeParameterCollection();
            return ImportStringParametersMessage();
        }

        internal MimeParameterCollection ImportStringParametersMessage() {
            MimeParameterCollection parameters = new MimeParameterCollection();
            foreach (MessagePart part in InputMessage.Parts) {
                MimeParameter parameter = ImportUrlParameter(part);
                if (parameter == null) return null;
                parameters.Add(parameter);
            }
            return parameters;
        }

        MimeParameter ImportUrlParameter(MessagePart part) {
            // 
            MimeParameter parameter = new MimeParameter();
            parameter.Name = CodeIdentifier.MakeValid(XmlConvert.DecodeName(part.Name));
            parameter.TypeName = IsRepeatingParameter(part) ? typeof(string[]).FullName : typeof(string).FullName;
            return parameter;
        }

        bool IsRepeatingParameter(MessagePart part) {
            XmlSchemaComplexType type = (XmlSchemaComplexType)Schemas.Find(part.Type, typeof(XmlSchemaComplexType));
            if (type == null) return false;
            if (type.ContentModel == null) return false;
            if (type.ContentModel.Content == null) throw new ArgumentException(Res.GetString(Res.Missing2, type.Name, type.ContentModel.GetType().Name), "part");
            if (type.ContentModel.Content is XmlSchemaComplexContentExtension) {
                return ((XmlSchemaComplexContentExtension)type.ContentModel.Content).BaseTypeName == new XmlQualifiedName(Soap.ArrayType, Soap.Encoding);
            }
            else if (type.ContentModel.Content is XmlSchemaComplexContentRestriction) {
                return ((XmlSchemaComplexContentRestriction)type.ContentModel.Content).BaseTypeName == new XmlQualifiedName(Soap.ArrayType, Soap.Encoding);
            }
            return false;
        }

        static void AppendMetadata(CodeAttributeDeclarationCollection from, CodeAttributeDeclarationCollection to) {
            foreach (CodeAttributeDeclaration attr in from) to.Add(attr);
        }

        CodeMemberMethod GenerateMethod(HttpMethodInfo method) {
            MimeParameterCollection parameters = method.MimeParameters != null ? method.MimeParameters : method.UrlParameters;

            string[] parameterTypeNames = new string[parameters.Count];
            string[] parameterNames = new string[parameters.Count];

            for (int i = 0; i < parameters.Count; i++) {
                MimeParameter param = parameters[i];
                parameterNames[i] = param.Name;
                parameterTypeNames[i] = param.TypeName;
            }

            CodeAttributeDeclarationCollection metadata = new CodeAttributeDeclarationCollection();
            
            CodeExpression[] formatterTypes = new CodeExpression[2];

            if (method.MimeReturn.ReaderType == null) {
                formatterTypes[0] = new CodeTypeOfExpression(typeof(NopReturnReader).FullName);
            }
            else {
                formatterTypes[0] = new CodeTypeOfExpression(method.MimeReturn.ReaderType.FullName);
            }

            if (method.MimeParameters != null)
                formatterTypes[1] = new CodeTypeOfExpression(method.MimeParameters.WriterType.FullName);
            else
                formatterTypes[1] = new CodeTypeOfExpression(typeof(UrlParameterWriter).FullName);

            WebCodeGenerator.AddCustomAttribute(metadata, typeof(HttpMethodAttribute), formatterTypes, new string[0], new CodeExpression[0]);


            CodeMemberMethod mainCodeMethod = WebCodeGenerator.AddMethod(this.CodeTypeDeclaration, method.Name, new CodeFlags[parameterTypeNames.Length], parameterTypeNames, parameterNames, 
                                        method.MimeReturn.TypeName, metadata, 
                                        CodeFlags.IsPublic | (Style == ServiceDescriptionImportStyle.Client ? 0 : CodeFlags.IsAbstract));

            AppendMetadata(method.MimeReturn.Attributes, mainCodeMethod.ReturnTypeCustomAttributes);

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

            for (int i = 0; i < parameters.Count; i++) {
                AppendMetadata(parameters[i].Attributes, mainCodeMethod.Parameters[i].CustomAttributes);
            }

            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[3];
                CreateInvokeParams(invokeParams, method, parameterNames);
                CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Invoke", invokeParams);
                if (method.MimeReturn.ReaderType != null) {
                    mainCodeMethod.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(method.MimeReturn.TypeName, invoke)));
                }
                else {
                    mainCodeMethod.Statements.Add(new CodeExpressionStatement(invoke));
                }

                metadata = new CodeAttributeDeclarationCollection();

                string[] asyncParameterTypeNames = new string[parameterTypeNames.Length + 2];
                parameterTypeNames.CopyTo(asyncParameterTypeNames, 0);
                asyncParameterTypeNames[parameterTypeNames.Length] = typeof(AsyncCallback).FullName;
                asyncParameterTypeNames[parameterTypeNames.Length + 1] = typeof(object).FullName;

                string[] asyncParameterNames = new string[parameterNames.Length + 2];
                parameterNames.CopyTo(asyncParameterNames, 0);
                asyncParameterNames[parameterNames.Length] = "callback";
                asyncParameterNames[parameterNames.Length + 1] = "asyncState";

                if (oldAsync) {
                    CodeMemberMethod beginCodeMethod = WebCodeGenerator.AddMethod(this.CodeTypeDeclaration, "Begin" + method.Name, new CodeFlags[asyncParameterTypeNames.Length], 
                        asyncParameterTypeNames, asyncParameterNames, 
                        typeof(IAsyncResult).FullName, metadata, CodeFlags.IsPublic);
                    beginCodeMethod.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true));
                    
                    invokeParams = new CodeExpression[5];
                    CreateInvokeParams(invokeParams, method, parameterNames);

                    invokeParams[3] = new CodeArgumentReferenceExpression( "callback");
                    invokeParams[4] = new CodeArgumentReferenceExpression( "asyncState");

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

                    CodeMemberMethod endCodeMethod = WebCodeGenerator.AddMethod(this.CodeTypeDeclaration, "End" + method.Name, new CodeFlags[1], 
                        new string[] { typeof(IAsyncResult).FullName },
                        new string[] { "asyncResult" },
                        method.MimeReturn.TypeName, metadata, CodeFlags.IsPublic);
                    endCodeMethod.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true));

                    CodeExpression expr = new CodeArgumentReferenceExpression( "asyncResult");
                    invoke = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "EndInvoke", new CodeExpression[] { expr });
                    if (method.MimeReturn.ReaderType != null) {
                        endCodeMethod.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(method.MimeReturn.TypeName, invoke)));
                    }
                    else {
                        endCodeMethod.Statements.Add(new CodeExpressionStatement(invoke));
                    }
                }
                if (newAsync) {
                    metadata = new CodeAttributeDeclarationCollection();
                    string uniqueMethodName = method.Name;
                    string methodKey = MethodSignature(uniqueMethodName, method.MimeReturn.TypeName, new CodeFlags[parameterTypeNames.Length], parameterTypeNames);
                    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 userState = UniqueName("userState", parameterNames);
                    CodeMemberMethod asyncCodeMethod = WebCodeGenerator.AddAsyncMethod(this.CodeTypeDeclaration, asyncName, 
                        parameterTypeNames, parameterNames, callbackMember, callbackName, userState);

                    // Generate InvokeAsync call
                    invokeParams = new CodeExpression[5];
                    CreateInvokeParams(invokeParams, method, parameterNames);
                    invokeParams[3] = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), callbackMember);
                    invokeParams[4] = new CodeArgumentReferenceExpression(userState);
                        
                    invoke = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InvokeAsync", invokeParams);
                    asyncCodeMethod.Statements.Add(invoke);

                    //  private void On_xxx_OperationCompleted(object arg) {..}
                    bool methodHasReturn = method.MimeReturn.ReaderType != null;
                    WebCodeGenerator.AddCallbackImplementation(this.CodeTypeDeclaration, callbackName, handlerName, delegateInfo.handlerArgs, methodHasReturn);
                    if (ExportContext[methodKey] == null) {
                        // public delegate void xxxCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs args);
                        WebCodeGenerator.AddDelegate(ExtraCodeClasses, delegateInfo.handlerType, methodHasReturn ? delegateInfo.handlerArgs : typeof(AsyncCompletedEventArgs).FullName);
                        
                        if (methodHasReturn) {
                            ExtraCodeClasses.Add(WebCodeGenerator.CreateArgsClass(delegateInfo.handlerArgs, new string[] { method.MimeReturn.TypeName }, new string[] { "Result" },
                                ServiceImporter.CodeGenerator.Supports(GeneratorSupport.PartialTypes)));
                        }
                        ExportContext[methodKey] = delegateInfo;
                    }
                }
            }
            return mainCodeMethod;
        }

        void CreateInvokeParams(CodeExpression[] invokeParams, HttpMethodInfo method, string[] parameterNames) {
            invokeParams[0] = new CodePrimitiveExpression(method.Name);

            CodeExpression left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Url");
            CodeExpression right = new CodePrimitiveExpression(method.Href);
            invokeParams[1] = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.Add, right);

            CodeExpression[] values = new CodeExpression[parameterNames.Length];
            for (int i = 0; i < parameterNames.Length; i++) {
                values[i] = new CodeArgumentReferenceExpression( parameterNames[i]);
            }
            invokeParams[2] = new CodeArrayCreateExpression(typeof(object).FullName, values);
        }

        protected override bool IsOperationFlowSupported(OperationFlow flow) {
            return flow == OperationFlow.RequestResponse;
        }

        // 

        protected override CodeMemberMethod GenerateMethod() {
            HttpOperationBinding httpOperationBinding = (HttpOperationBinding)OperationBinding.Extensions.Find(typeof(HttpOperationBinding));
            if (httpOperationBinding == null) throw OperationBindingSyntaxException(Res.GetString(Res.MissingHttpOperationElement0));

            HttpMethodInfo method = new HttpMethodInfo();

            if (hasInputPayload) {
                method.MimeParameters = ImportMimeParameters();
                if (method.MimeParameters == null) {
                    UnsupportedOperationWarning(Res.GetString(Res.NoInputMIMEFormatsWereRecognized0));
                    return null;
                }
            }
            else {
                method.UrlParameters = ImportUrlParameters();
                if (method.UrlParameters == null) {
                    UnsupportedOperationWarning(Res.GetString(Res.NoInputHTTPFormatsWereRecognized0));
                    return null;
                }
            }
            method.MimeReturn = ImportMimeReturn();
            if (method.MimeReturn == null) {
                UnsupportedOperationWarning(Res.GetString(Res.NoOutputMIMEFormatsWereRecognized0));
                return null;
            }
            method.Name = MethodNames.AddUnique(MethodName, method);
            method.Href = httpOperationBinding.Location;
            return GenerateMethod(method);
        }

        protected override CodeTypeDeclaration BeginClass() {
            MethodNames.Clear();
            ExtraCodeClasses.Clear();
            CodeAttributeDeclarationCollection metadata = new CodeAttributeDeclarationCollection();
            if (Style == ServiceDescriptionImportStyle.Client) {
                WebCodeGenerator.AddCustomAttribute(metadata, typeof(DebuggerStepThroughAttribute), new CodeExpression[0]);
                WebCodeGenerator.AddCustomAttribute(metadata, typeof(DesignerCategoryAttribute), new CodeExpression[] { new CodePrimitiveExpression("code") });
            }

            Type[] requiredTypes = new Type[] { 
                typeof(SoapDocumentMethodAttribute), 
                typeof(XmlAttributeAttribute), 
                typeof(WebService), 
                typeof(Object), 
                typeof(DebuggerStepThroughAttribute), 
                typeof(DesignerCategoryAttribute),
                typeof(TransactionOption),
            };
            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, BaseClass.FullName, 
                new string[0], metadata, CodeFlags.IsPublic | flags, 
                ServiceImporter.CodeGenerator.Supports(GeneratorSupport.PartialTypes));

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

            CodeConstructor ctor = WebCodeGenerator.AddConstructor(codeClass, new string[0], new string[0], null, CodeFlags.IsPublic);
            ctor.Comments.Add(new CodeCommentStatement(Res.GetString(Res.CodeRemarks), true));

            HttpAddressBinding httpAddressBinding = Port == null ? null : (HttpAddressBinding)Port.Extensions.Find(typeof(HttpAddressBinding));
            string url = (httpAddressBinding != null) ? httpAddressBinding.Location : null;
            ServiceDescription serviceDescription = Binding.ServiceDescription;
            ProtocolImporterUtil.GenerateConstructorStatements(ctor, url, serviceDescription.AppSettingUrlKey, serviceDescription.AppSettingBaseUrl, false);

            codeClasses.Add(codeClass);
            return codeClass;
        }

        protected override void EndNamespace() { 
            for (int i = 0; i < importers.Length; i++) {
                importers[i].GenerateCode((MimeReturn[])importedReturns[i].ToArray(typeof(MimeReturn)), 
                                          (MimeParameterCollection[])importedParameters[i].ToArray(typeof(MimeParameterCollection))); 
            }

            foreach (CodeTypeDeclaration codeClass in codeClasses) {
                if (codeClass.CustomAttributes == null)
                    codeClass.CustomAttributes = new CodeAttributeDeclarationCollection();

                for (int i = 0; i < importers.Length; i++) {
                    importers[i].AddClassMetadata(codeClass);
                }
            }
            foreach (CodeTypeDeclaration declaration in ExtraCodeClasses) {
                this.CodeNamespace.Types.Add(declaration);
            }
            CodeGenerator.ValidateIdentifiers(CodeNamespace);
        }

        internal abstract Type BaseClass { get; }
    }
}