svn path=/trunk/mcs/; revision=64924
[mono.git] / mcs / class / System.Web.Services / System.Web.Services.Description / HttpSimpleProtocolImporter.cs
1 // 
2 // System.Web.Services.Description.HttpSimpleProtocolImporter.cs
3 //
4 // Author:
5 //   Lluis Sanchez Gual (lluis@ximian.com)
6 //
7 // Copyright (C) 2003 Ximian, Inc.
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System.CodeDom;
32 using System.Web.Services;
33 using System.Web.Services.Protocols;
34 using System.Web.Services.Configuration;
35 using System.Xml;
36 using System.Xml.Serialization;
37 using System.Configuration;
38 using System.Collections;
39
40 namespace System.Web.Services.Description 
41 {
42         internal abstract class HttpSimpleProtocolImporter : ProtocolImporter 
43         {
44
45                 #region Fields
46
47                 HttpBinding httpBinding;
48                 
49                 SoapCodeExporter soapExporter;
50                 SoapSchemaImporter soapImporter;
51                 XmlCodeExporter xmlExporter;
52                 XmlSchemaImporter xmlImporter;
53                 CodeIdentifiers memberIds;
54                 XmlReflectionImporter xmlReflectionImporter;
55                 
56                 #endregion // Fields
57
58                 #region Constructors
59
60                 public HttpSimpleProtocolImporter ()
61                 {
62                 }
63                 
64                 #endregion // Constructors
65
66                 #region Methods
67
68                 protected override CodeTypeDeclaration BeginClass ()
69                 {
70                         httpBinding = (HttpBinding) Binding.Extensions.Find (typeof(HttpBinding));
71
72                         CodeTypeDeclaration codeClass = new CodeTypeDeclaration (ClassName);
73
74                         string location = null;
75                         if (Port != null) {
76                                 HttpAddressBinding sab = (HttpAddressBinding) Port.Extensions.Find (typeof(HttpAddressBinding));
77                                 if (sab != null) location = sab.Location;
78                         }
79                         
80                         CodeConstructor cc = new CodeConstructor ();
81                         cc.Attributes = MemberAttributes.Public;
82                         GenerateServiceUrl (location, cc.Statements);
83                         codeClass.Members.Add (cc);
84                         
85                         memberIds = new CodeIdentifiers ();
86                         return codeClass;
87                 }
88
89                 protected override void BeginNamespace ()
90                 {
91                         xmlImporter = new XmlSchemaImporter (LiteralSchemas, ClassNames);
92                         soapImporter = new SoapSchemaImporter (EncodedSchemas, ClassNames);
93                         xmlExporter = new XmlCodeExporter (CodeNamespace, null);
94                         xmlReflectionImporter = new XmlReflectionImporter ();
95                 }
96
97                 protected override void EndClass ()
98                 {
99                         if (xmlExporter.IncludeMetadata.Count > 0)
100                         {
101                                 if (CodeTypeDeclaration.CustomAttributes == null)
102                                         CodeTypeDeclaration.CustomAttributes = new CodeAttributeDeclarationCollection ();
103                                 CodeTypeDeclaration.CustomAttributes.AddRange (xmlExporter.IncludeMetadata);
104                         }
105                 }
106
107                 protected override void EndNamespace ()
108                 {
109                 }
110
111                 protected override bool IsBindingSupported ()
112                 {
113                         throw new NotImplementedException ();
114                 }
115
116                 [MonoTODO]
117                 protected override bool IsOperationFlowSupported (OperationFlow flow)
118                 {
119                         throw new NotImplementedException ();
120                 }
121
122                 protected override CodeMemberMethod GenerateMethod ()
123                 {
124                         try
125                         {
126                                 HttpOperationBinding httpOper = OperationBinding.Extensions.Find (typeof (HttpOperationBinding)) as HttpOperationBinding;
127                                 if (httpOper == null) throw new Exception ("Http operation binding not found");
128                                 
129                                 XmlMembersMapping inputMembers = ImportInMembersMapping (InputMessage);
130                                 XmlTypeMapping outputMember = ImportOutMembersMapping (OutputMessage);
131                                 
132                                 CodeMemberMethod met = GenerateMethod (memberIds, httpOper, inputMembers, outputMember);
133                                 
134                                 xmlExporter.ExportMembersMapping (inputMembers);
135                                 if (outputMember != null)
136                                         xmlExporter.ExportTypeMapping (outputMember);
137
138                                 return met;
139                         }
140                         catch (Exception ex)
141                         {
142                                 UnsupportedOperationBindingWarning (ex.Message);
143                                 return null;
144                         }
145                 }
146
147                 XmlMembersMapping ImportInMembersMapping (Message msg)
148                 {
149                         SoapSchemaMember[] mems = new SoapSchemaMember [msg.Parts.Count];
150                         for (int n=0; n<mems.Length; n++)
151                         {
152                                 SoapSchemaMember mem = new SoapSchemaMember();
153                                 mem.MemberName = msg.Parts[n].Name;
154                                 mem.MemberType = msg.Parts[n].Type;
155                                 mems[n] = mem;
156                         }
157                         return soapImporter.ImportMembersMapping (Operation.Name, "", mems);
158                 }
159                 
160                 XmlTypeMapping ImportOutMembersMapping (Message msg)
161                 {
162                         if (msg.Parts.Count == 0) return null;
163                         
164                         if (msg.Parts[0].Name == "Body" && msg.Parts[0].Element == XmlQualifiedName.Empty)
165                                 return xmlReflectionImporter.ImportTypeMapping (typeof(XmlNode));
166                         else {
167                                 // This is a bit hacky. The issue is that types such as string[] are to be imported
168                                 // as such, not as ArrayOfString class. ImportTypeMapping will return a
169                                 // class if the type has not been imported as an array before, hence the
170                                 // call to ImportMembersMapping.
171                                 xmlImporter.ImportMembersMapping (new XmlQualifiedName[] {msg.Parts[0].Element});
172                                 return xmlImporter.ImportTypeMapping (msg.Parts[0].Element);
173                         }
174                 }
175                 
176                 CodeMemberMethod GenerateMethod (CodeIdentifiers memberIds, HttpOperationBinding httpOper, XmlMembersMapping inputMembers, XmlTypeMapping outputMember)
177                 {
178                         CodeIdentifiers pids = new CodeIdentifiers ();
179                         CodeMemberMethod method = new CodeMemberMethod ();
180                         CodeMemberMethod methodBegin = new CodeMemberMethod ();
181                         CodeMemberMethod methodEnd = new CodeMemberMethod ();
182                         method.Attributes = MemberAttributes.Public;
183                         methodBegin.Attributes = MemberAttributes.Public;
184                         methodEnd.Attributes = MemberAttributes.Public;
185                         
186                         // Find unique names for temporary variables
187                         
188                         for (int n=0; n<inputMembers.Count; n++)
189                                 pids.AddUnique (inputMembers[n].MemberName, inputMembers[n]);
190
191                         string varAsyncResult = pids.AddUnique ("asyncResult","asyncResult");
192                         string varCallback = pids.AddUnique ("callback","callback");
193                         string varAsyncState = pids.AddUnique ("asyncState","asyncState");
194
195                         string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name),method);
196
197                         method.Name = Operation.Name;
198                         methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + Operation.Name),method);
199                         methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + Operation.Name),method);
200
201                         method.ReturnType = new CodeTypeReference (typeof(void));
202                         methodEnd.ReturnType = new CodeTypeReference (typeof(void));
203                         methodEnd.Parameters.Add (new CodeParameterDeclarationExpression (typeof (IAsyncResult),varAsyncResult));
204
205                         CodeExpression[] paramArray = new CodeExpression [inputMembers.Count];
206
207                         for (int n=0; n<inputMembers.Count; n++)
208                         {
209                                 string ptype = GetSimpleType (inputMembers[n]);
210                                 CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (ptype, inputMembers[n].MemberName);
211                                 
212                                 param.Direction = FieldDirection.In;
213                                 method.Parameters.Add (param);
214                                 methodBegin.Parameters.Add (param);
215                                 paramArray [n] = new CodeVariableReferenceExpression (param.Name);
216                         }
217
218                         bool isVoid = true;
219                         if (outputMember != null)
220                         {
221                                 method.ReturnType = new CodeTypeReference (outputMember.TypeFullName);
222                                 methodEnd.ReturnType = new CodeTypeReference (outputMember.TypeFullName);
223                                 xmlExporter.AddMappingMetadata (method.ReturnTypeCustomAttributes, outputMember, "");
224                                 isVoid = false;
225                         }
226
227                         methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (AsyncCallback),varCallback));
228                         methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object),varAsyncState));
229                         methodBegin.ReturnType = new CodeTypeReference (typeof(IAsyncResult));
230
231                         // Array of input parameters
232                         
233                         CodeArrayCreateExpression methodParams;
234                         if (paramArray.Length > 0)
235                                 methodParams = new CodeArrayCreateExpression (typeof(object), paramArray);
236                         else
237                                 methodParams = new CodeArrayCreateExpression (typeof(object), 0);
238
239                         // Generate method url
240                         
241                         CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
242                         
243                         CodeExpression thisURlExp = new CodeFieldReferenceExpression (ethis, "Url");
244                         CodePrimitiveExpression metUrl = new CodePrimitiveExpression (httpOper.Location);
245                         CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression (thisURlExp, CodeBinaryOperatorType.Add, metUrl);
246                         
247                         // Invoke call
248                         
249                         CodePrimitiveExpression varMsgName = new CodePrimitiveExpression (messageName);
250                         CodeMethodInvokeExpression inv;
251
252                         inv = new CodeMethodInvokeExpression (ethis, "Invoke", varMsgName, expMethodLocation, methodParams);
253                         if (!isVoid)
254                                 method.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (method.ReturnType, inv)));
255                         else
256                                 method.Statements.Add (inv);
257                         
258                         // Begin Invoke Call
259                         
260                         CodeExpression expCallb = new CodeVariableReferenceExpression (varCallback);
261                         CodeExpression expAsyncs = new CodeVariableReferenceExpression (varAsyncState);
262                         inv = new CodeMethodInvokeExpression (ethis, "BeginInvoke", varMsgName, expMethodLocation, methodParams, expCallb, expAsyncs);
263                         methodBegin.Statements.Add (new CodeMethodReturnStatement (inv));
264                         
265                         // End Invoke call
266                         
267                         CodeExpression varAsyncr = new CodeVariableReferenceExpression (varAsyncResult);
268                         inv = new CodeMethodInvokeExpression (ethis, "EndInvoke", varAsyncr);
269                         if (!isVoid)
270                                 methodEnd.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (methodEnd.ReturnType, inv)));
271                         else
272                                 methodEnd.Statements.Add (inv);
273                         
274                         // Attributes
275
276                         CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.HttpMethodAttribute");
277                         att.Arguments.Add (new CodeAttributeArgument (new CodeTypeOfExpression(GetOutMimeFormatter ())));
278                         att.Arguments.Add (new CodeAttributeArgument (new CodeTypeOfExpression(GetInMimeFormatter ())));
279                         AddCustomAttribute (method, att, true);
280                 
281                         CodeTypeDeclaration.Members.Add (method);
282                         CodeTypeDeclaration.Members.Add (methodBegin);
283                         CodeTypeDeclaration.Members.Add (methodEnd);
284                         
285                         return method;
286                 }               
287
288 #if NET_2_0
289                 internal override CodeExpression BuildInvokeAsync (string messageName, CodeArrayCreateExpression paramsArray, CodeExpression delegateField, CodeExpression userStateVar)
290                 {
291                         HttpOperationBinding httpOper = OperationBinding.Extensions.Find (typeof (HttpOperationBinding)) as HttpOperationBinding;
292                         
293                         CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
294                         
295                         CodeExpression thisURlExp = new CodeFieldReferenceExpression (ethis, "Url");
296                         CodePrimitiveExpression metUrl = new CodePrimitiveExpression (httpOper.Location);
297                         CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression (thisURlExp, CodeBinaryOperatorType.Add, metUrl);
298                         
299                         CodeMethodInvokeExpression inv2 = new CodeMethodInvokeExpression (ethis, "InvokeAsync");
300                         inv2.Parameters.Add (new CodePrimitiveExpression (messageName));
301                         inv2.Parameters.Add (expMethodLocation);
302                         inv2.Parameters.Add (paramsArray);
303                         inv2.Parameters.Add (delegateField);
304                         inv2.Parameters.Add (userStateVar);
305                         return inv2;
306                 }
307 #endif
308                 
309                 protected virtual Type GetInMimeFormatter ()
310                 {
311                         return null;
312                 }
313
314                 protected virtual Type GetOutMimeFormatter ()
315                 {
316                         if (OperationBinding.Output.Extensions.Find (typeof(MimeXmlBinding)) != null)
317                                 return typeof (XmlReturnReader);
318                                 
319                         MimeContentBinding bin = (MimeContentBinding) OperationBinding.Output.Extensions.Find (typeof(MimeContentBinding));
320                         if (bin != null && bin.Type == "text/xml")
321                                 return typeof (XmlReturnReader);
322                                 
323                         return typeof(NopReturnReader);
324                 }
325                 
326                 string GetSimpleType (XmlMemberMapping member)
327                 {
328                         // MS seems to always use System.String for input parameters, except for byte[]
329                         
330                         switch (member.TypeName)
331                         {
332                                 case "hexBinary":
333                                 case "base64Binary":
334                                         return "System.String";
335                                 
336                                 default:
337                                         string ptype = member.TypeFullName;
338                                         int i = ptype.IndexOf ('[');
339                                         if (i == -1)
340                                                 return "System.String";
341                                         else 
342                                                 return "System.String" + ptype.Substring (i);
343                         }
344                 }
345
346                 #endregion
347         }
348 }