merge from trunk revisions 58933, 58935, 58936
[mono.git] / mcs / tools / wsdl / MonoWSDL2.cs
1 ///\r
2 /// MonoWSDL.cs -- a WSDL to proxy code generator.\r
3 ///\r
4 /// Author: Erik LeBel (eriklebel@yahoo.ca)\r
5 ///             Lluis Sanchez (lluis@novell.com)\r
6 ///\r
7 /// Copyright (C) 2003, Erik LeBel,\r
8 ///\r
9 \r
10 #if NET_2_0\r
11 \r
12 using System;\r
13 using System.Xml;\r
14 using System.Xml.Serialization;\r
15 using System.Xml.Schema;\r
16 using System.Collections;\r
17 using System.Collections.Specialized;\r
18 using System.CodeDom;\r
19 using System.CodeDom.Compiler;\r
20 using System.IO;\r
21 using System.Net;\r
22 using System.Web.Services.Description;\r
23 using System.Web.Services.Discovery;\r
24 using System.Web.Services;\r
25 \r
26 using Microsoft.CSharp;\r
27 \r
28 namespace Mono.WebServices\r
29 {\r
30         public class Driver\r
31         {\r
32                 string ProductId = "Web Services Description Language Utility\nMono Framework v" + Environment.Version;\r
33                 const string UsageMessage = \r
34                         "wsdl [options] {path | URL} {path | URL} ...\n\n"\r
35                         + "   -d, -domain:domain           Domain of username for server authentication.\n"\r
36                         + "   -l, -language:language       Language of generated code. Allowed CS (default)\n"\r
37                         + "                                and VB. You can also specify the fully qualified\n"\r
38                         + "                                name of a class that implements the\n"\r
39                         + "                                System.CodeDom.Compiler.CodeDomProvider Class.\n"\r
40                         + "   -n, -namespace:ns            The namespace of the generated code, default\n"\r
41                         + "                                namespace if none.\n"\r
42                         + "   -nologo                      Surpress the startup logo.\n"\r
43                         + "   -o, -out:filename            The target file for generated code.\n"\r
44                         + "   -p, -password:pwd            Password used to contact the server.\n"\r
45                         + "   -protocol:protocol           Protocol to implement. Allowed: Soap (default),\n"\r
46                         + "                                HttpGet or HttpPost.\n"\r
47                         + "   -fields                      Generate fields instead of properties in data\n"\r
48                         + "                                classes.\n"\r
49                         + "   -server                      Generate server instead of client proxy code.\n"\r
50                         + "   -u, -username:username       Username used to contact the server.\n"\r
51                         + "   -proxy:url                   Address of the proxy.\n"\r
52                         + "   -pu, -proxyusername:username Username used to contact the proxy.\n"\r
53                         + "   -pp, -proxypassword:pwd      Password used to contact the proxy.\n"\r
54                         + "   -pd, -proxydomain:domain     Domain of username for proxy authentication.\n"\r
55                         + "   -urlkey, -appsettingurlkey:key Configuration key that contains the default\n"\r
56                         + "                                url for the generated WS proxy.\n"\r
57                         + "   -baseurl, -appsettingbaseurl:url Base url to use when constructing the\n"\r
58                         + "                                service url.\n"\r
59                         + "   -sample:[binding/]operation  Display a sample SOAP request and response.\n"\r
60                         + "   -?                           Display this message\n"\r
61                         + "\n"\r
62                         + "Options can be of the forms  -option, --option or /option\n";\r
63                 \r
64                 ArrayList descriptions = new ArrayList ();\r
65                 ArrayList schemas = new ArrayList ();\r
66                 \r
67                 bool noLogo;\r
68                 bool help;\r
69                 string sampleSoap;\r
70                 \r
71                 string proxyAddress;\r
72                 string proxyDomain;\r
73                 string proxyPassword;\r
74                 string proxyUsername;\r
75                 string username;\r
76                 string password;\r
77                 string domain;\r
78                 \r
79                 string applicationSignature;\r
80                 string appSettingURLKey;\r
81                 string appSettingBaseURL;\r
82                 string language = "CS";\r
83                 string ns;\r
84                 string outFilename;\r
85                 string protocol = "Soap";\r
86                 ServiceDescriptionImportStyle style;\r
87                 CodeGenerationOptions options = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;\r
88                 bool verbose;\r
89                 \r
90                 StringCollection urls = new StringCollection ();\r
91 \r
92                 ///\r
93                 /// <summary>\r
94                 ///     Application entry point.\r
95                 /// </summary>\r
96                 ///\r
97                 public static int Main(string[] args)\r
98                 {\r
99                         Driver d = new Driver();\r
100                         return d.Run(args);\r
101                 }\r
102                 \r
103                 Driver()\r
104                 {\r
105                         applicationSignature = ProductId;\r
106                 }\r
107                 \r
108                 int Run (string[] args)\r
109                 {\r
110                         try\r
111                         {\r
112                                 // parse command line arguments\r
113                                 foreach (string argument in args)\r
114                                         ImportArgument(argument);\r
115                                 \r
116                                 if (noLogo == false)\r
117                                         Console.WriteLine(ProductId);\r
118                                 \r
119                                 if (help || urls.Count == 0)\r
120                                 {\r
121                                         Console.WriteLine(UsageMessage);\r
122                                         return 0;\r
123                                 }\r
124                                 \r
125                                 CodeCompileUnit codeUnit = new CodeCompileUnit();\r
126                                 CodeNamespace proxyCode = GetCodeNamespace();\r
127                                 codeUnit.Namespaces.Add (proxyCode);\r
128                                 \r
129                                 WebReferenceCollection references = new WebReferenceCollection ();\r
130                                 foreach (string murl in urls) \r
131                                 {\r
132                                         DiscoveryClientProtocol dcc = CreateClient ();\r
133 \r
134                                         string url = murl;\r
135                                         if (!url.StartsWith ("http://") && !url.StartsWith ("https://") && !url.StartsWith ("file://"))\r
136                                                 url = new Uri (Path.GetFullPath (url)).ToString ();\r
137 \r
138                                         dcc.DiscoverAny (url);\r
139                                         dcc.ResolveAll ();\r
140                                         \r
141                                         WebReference reference = new WebReference (dcc.Documents, proxyCode, protocol, appSettingURLKey, appSettingBaseURL);\r
142                                         references.Add (reference);\r
143                                         \r
144                                         if (sampleSoap != null)\r
145                                                 ConsoleSampleGenerator.Generate (descriptions, schemas, sampleSoap, protocol);\r
146                                 }\r
147                                 \r
148                                 if (sampleSoap != null)\r
149                                         return 0;\r
150                                         \r
151                                 // generate the code\r
152                                 if (GenerateCode (references, codeUnit))\r
153                                         return 1;\r
154                                 else\r
155                                         return 0;\r
156                         }\r
157                         catch (Exception exception)\r
158                         {\r
159                                 Console.WriteLine("Error: {0}", exception.Message);\r
160                                 \r
161                                 // Supress this except for when debug is enabled\r
162                                 Console.WriteLine("Stack:\n {0}", exception.StackTrace);\r
163                                 return 2;\r
164                         }\r
165                 }\r
166                 \r
167                 ///\r
168                 /// <summary>\r
169                 ///     Generate code for the specified ServiceDescription.\r
170                 /// </summary>\r
171                 ///\r
172                 public bool GenerateCode (WebReferenceCollection references, CodeCompileUnit codeUnit)\r
173                 {\r
174                         bool hasWarnings = false;\r
175                         \r
176                         CodeDomProvider provider = GetProvider();\r
177                         ICodeGenerator generator = provider.CreateGenerator();\r
178                                 \r
179                         StringCollection validationWarnings;\r
180                         validationWarnings = ServiceDescriptionImporter.GenerateWebReferences (references, options, style, generator, codeUnit, verbose);\r
181                         \r
182                         for (int n=0; n<references.Count; n++)\r
183                         {\r
184                                 WebReference wr  = references [n];\r
185                                 \r
186                                 BasicProfileViolationCollection violations = new BasicProfileViolationCollection ();\r
187                                 if (!WebServicesInteroperability.CheckConformance (WsiClaims.BP10, wr, violations)) {\r
188                                         wr.Warnings |= ServiceDescriptionImportWarnings.WsiConformance;\r
189                                 }\r
190                                 \r
191                                 if (wr.Warnings != 0)\r
192                                 {\r
193                                         if (!hasWarnings) {\r
194                                                 WriteText ("", 0, 0);\r
195                                                 WriteText ("There where some warnings while generating the code:", 0, 0);\r
196                                         }\r
197                                         \r
198                                         WriteText ("", 0, 0);\r
199                                         WriteText (urls[n], 2, 2);\r
200                                         \r
201                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.WsiConformance) > 0) {\r
202                                                 WriteText ("- This web reference does not conform to WS-I Basic Profile v1.0", 4, 6); \r
203                                                 foreach (BasicProfileViolation vio in violations) {\r
204                                                         WriteText (vio.NormativeStatement + ": " + vio.Details, 8, 8);\r
205                                                         foreach (string ele in vio.Elements)\r
206                                                                 WriteText ("* " + ele, 10, 12);\r
207                                                 }\r
208                                         }\r
209                                         \r
210                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) > 0)\r
211                                                 WriteText ("- WARNING: No proxy class was generated", 4, 6); \r
212                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) > 0)\r
213                                                 WriteText ("- WARNING: The proxy class generated includes no methods", 4, 6);\r
214                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) > 0)\r
215                                                 WriteText ("- WARNING: At least one optional extension has been ignored", 4, 6);\r
216                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) > 0)\r
217                                                 WriteText ("- WARNING: At least one necessary extension has been ignored", 4, 6);\r
218                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) > 0)\r
219                                                 WriteText ("- WARNING: At least one binding is of an unsupported type and has been ignored", 4, 6);\r
220                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) > 0)\r
221                                                 WriteText ("- WARNING: At least one operation is of an unsupported type and has been ignored", 4, 6);\r
222                                                 \r
223                                         hasWarnings = true;\r
224                                 }\r
225                         }\r
226                         \r
227                         if (hasWarnings) WriteText ("",0,0);\r
228                                 \r
229                         string filename = outFilename;\r
230                         bool hasBindings = false;\r
231                         \r
232                         foreach (object doc in references[0].Documents.Values)\r
233                         {\r
234                                 ServiceDescription desc = doc as ServiceDescription;\r
235                                 if (desc == null) continue;\r
236                                 \r
237                                 if (desc.Services.Count > 0 && filename == null)\r
238                                         filename = desc.Services[0].Name + "." + provider.FileExtension;\r
239                                         \r
240                                 if (desc.Bindings.Count > 0 || desc.Services.Count > 0)\r
241                                         hasBindings = true;\r
242                         }\r
243                         \r
244                         if (filename == null)\r
245                                 filename = "output." + provider.FileExtension;\r
246                         \r
247                         if (hasBindings) {\r
248                                 WriteText ("Writing file '" + filename + "'", 0, 0);\r
249                                 StreamWriter writer = new StreamWriter(filename);\r
250                                 \r
251                                 CodeGeneratorOptions compilerOptions = new CodeGeneratorOptions();\r
252                                 generator.GenerateCodeFromCompileUnit (codeUnit, writer, compilerOptions);\r
253                                 writer.Close();\r
254                         }\r
255                         \r
256                         return hasWarnings;\r
257                 }\r
258                 \r
259                 ///\r
260                 /// <summary>\r
261                 ///     Create the CodeNamespace with the generator's signature commented in.\r
262                 /// </summary>\r
263                 ///\r
264                 CodeNamespace GetCodeNamespace()\r
265                 {\r
266                         CodeNamespace codeNamespace = new CodeNamespace(ns);\r
267                         \r
268                         if (applicationSignature != null)\r
269                         {\r
270                                 codeNamespace.Comments.Add(new CodeCommentStatement("\n This source code was auto-generated by " + applicationSignature + "\n"));\r
271                         }\r
272                         \r
273                         return codeNamespace;\r
274                 }\r
275                 \r
276                 ///\r
277                 /// <summary/>\r
278                 ///\r
279                 void WriteCodeUnit(CodeCompileUnit codeUnit, string serviceName)\r
280                 {\r
281                         CodeDomProvider provider = GetProvider();\r
282                         ICodeGenerator generator = provider.CreateGenerator();\r
283                         CodeGeneratorOptions options = new CodeGeneratorOptions();\r
284                         \r
285                         string filename;\r
286                         if (outFilename != null)\r
287                                 filename = outFilename;\r
288                         else\r
289                                 filename = serviceName  + "." + provider.FileExtension;\r
290                         \r
291                         Console.WriteLine ("Writing file '{0}'", filename);\r
292                         StreamWriter writer = new StreamWriter(filename);\r
293                         generator.GenerateCodeFromCompileUnit(codeUnit, writer, options);\r
294                         writer.Close();\r
295                 }\r
296                 \r
297                 ///\r
298                 /// <summary>\r
299                 ///     Fetch the Code Provider for the language specified by the 'language' members.\r
300                 /// </summary>\r
301                 ///\r
302                 private CodeDomProvider GetProvider()\r
303                 {\r
304                         CodeDomProvider provider;\r
305                                     \r
306                         switch (language.ToUpper ()) {\r
307                         case "CS":\r
308                                 provider = new CSharpCodeProvider ();\r
309                                 break;\r
310                         case "VB":\r
311                                 provider = new Microsoft.VisualBasic.VBCodeProvider ();\r
312                                 break;\r
313                         default:\r
314                                 Type type = Type.GetType(language);\r
315                                 if (type != null) {\r
316                                         return (CodeDomProvider) Activator.CreateInstance (type);\r
317                                 }       \r
318                                 throw new Exception ("Unknown language");\r
319                         }\r
320                         return provider;\r
321                 }\r
322                 \r
323 \r
324 \r
325                 ///\r
326                 /// <summary>\r
327                 ///     Interperet the command-line arguments and configure the relavent components.\r
328                 /// </summary>\r
329                 ///             \r
330                 void ImportArgument(string argument)\r
331                 {\r
332                         string optionValuePair;\r
333                         \r
334                         if (argument.StartsWith("--"))\r
335                         {\r
336                                 optionValuePair = argument.Substring(2);\r
337                         }\r
338                         else if (argument.StartsWith("/") || argument.StartsWith("-"))\r
339                         {\r
340                                 optionValuePair = argument.Substring(1);\r
341                         }\r
342                         else\r
343                         {\r
344                                 urls.Add (argument);\r
345                                 return;\r
346                         }\r
347                         \r
348                         string option;\r
349                         string value;\r
350                         \r
351                         int indexOfEquals = optionValuePair.IndexOf(':');\r
352                         if (indexOfEquals > 0)\r
353                         {\r
354                                 option = optionValuePair.Substring(0, indexOfEquals);\r
355                                 value = optionValuePair.Substring(indexOfEquals + 1);\r
356                         }\r
357                         else\r
358                         {\r
359                                 option = optionValuePair;\r
360                                 value = null;\r
361                         }\r
362                         \r
363                         switch (option)\r
364                         {\r
365                                 case "appsettingurlkey":\r
366                                 case "urlkey":\r
367                                     appSettingURLKey = value;\r
368                                     break;\r
369 \r
370                                 case "appsettingbaseurl":\r
371                                 case "baseurl":\r
372                                     appSettingBaseURL = value;\r
373                                     break;\r
374 \r
375                                 case "d":\r
376                                 case "domain":\r
377                                     domain = value;\r
378                                     break;\r
379 \r
380                                 case "l":\r
381                                 case "language":\r
382                                     language = value;\r
383                                     break;\r
384 \r
385                                 case "n":\r
386                                 case "namespace":\r
387                                     ns = value;\r
388                                     break;\r
389 \r
390                                 case "nologo":\r
391                                     noLogo = true;\r
392                                     break;\r
393 \r
394                                 case "o":\r
395                                 case "out":\r
396                                     outFilename = value;\r
397                                     break;\r
398 \r
399                                 case "p":\r
400                                 case "password":\r
401                                     password = value;\r
402                                     break;\r
403 \r
404                                 case "protocol":\r
405                                     protocol = value;\r
406                                     break;\r
407 \r
408                                 case "proxy":\r
409                                     proxyAddress = value;\r
410                                     break;\r
411 \r
412                                 case "proxydomain":\r
413                                 case "pd":\r
414                                     proxyDomain = value;\r
415                                     break;\r
416 \r
417                                 case "proxypassword":\r
418                                 case "pp":\r
419                                     proxyPassword = value;\r
420                                     break;\r
421 \r
422                                 case "proxyusername":\r
423                                 case "pu":\r
424                                     proxyUsername = value;\r
425                                     break;\r
426 \r
427                                 case "server":\r
428                                     style = ServiceDescriptionImportStyle.Server;\r
429                                     break;\r
430 \r
431                                 case "u":\r
432                                 case "username":\r
433                                     username = value;\r
434                                     break;\r
435                                         \r
436                                 case "verbose":\r
437                                         verbose = true;\r
438                                         break;\r
439                                         \r
440                                 case "fields":\r
441                                         options &= ~CodeGenerationOptions.GenerateProperties;\r
442                                         break;\r
443                                         \r
444                                 case "sample":\r
445                                         sampleSoap = value;\r
446                                         break;\r
447 \r
448                                 case "?":\r
449                                     help = true;\r
450                                     break;\r
451 \r
452                                 default:\r
453                                         if (argument.StartsWith ("/") && argument.IndexOfAny (Path.InvalidPathChars) == -1) {\r
454                                                 urls.Add (argument);\r
455                                                 break;\r
456                                         }\r
457                                         else\r
458                                             throw new Exception("Unknown option " + option);\r
459                         }\r
460                 }\r
461                 \r
462                 DiscoveryClientProtocol CreateClient ()\r
463                 {\r
464                         DiscoveryClientProtocol dcc = new DiscoveryClientProtocol ();\r
465                         \r
466                         if (username != null || password != null || domain != null)\r
467                         {\r
468                                 NetworkCredential credentials = new NetworkCredential();\r
469                                 \r
470                                 if (username != null)\r
471                                         credentials.UserName = username;\r
472                                 \r
473                                 if (password != null)\r
474                                         credentials.Password = password;\r
475                                 \r
476                                 if (domain != null)\r
477                                         credentials.Domain = domain;\r
478                                 \r
479                                 dcc.Credentials = credentials;\r
480                         }\r
481                         \r
482                         if (proxyAddress != null)\r
483                         {\r
484                                 WebProxy proxy = new WebProxy (proxyAddress);\r
485                                 if (proxyUsername != null || proxyPassword != null || proxyDomain != null)\r
486                                 {\r
487                                         NetworkCredential credentials = new NetworkCredential();\r
488                                         \r
489                                         if (proxyUsername != null)\r
490                                                 credentials.UserName = proxyUsername;\r
491                                         \r
492                                         if (proxyPassword != null)\r
493                                                 credentials.Password = proxyPassword;\r
494                                         \r
495                                         if (proxyDomain != null)\r
496                                                 credentials.Domain = proxyDomain;\r
497                                         \r
498                                         proxy.Credentials = credentials;\r
499                                 }\r
500                         }                       \r
501                         \r
502                         return dcc;\r
503                 }\r
504                 \r
505                 static void WriteText (string text, int initialLeftMargin, int leftMargin)\r
506                 {\r
507                         int n = 0;\r
508                         int margin = initialLeftMargin;\r
509                         int maxCols = 80;\r
510                         \r
511                         if (text == "") {\r
512                                 Console.WriteLine ();\r
513                                 return;\r
514                         }\r
515                         \r
516                         while (n < text.Length)\r
517                         {\r
518                                 int col = margin;\r
519                                 int lastWhite = -1;\r
520                                 int sn = n;\r
521                                 while (col < maxCols && n < text.Length) {\r
522                                         if (char.IsWhiteSpace (text[n]))\r
523                                                 lastWhite = n;\r
524                                         col++;\r
525                                         n++;\r
526                                 }\r
527                                 \r
528                                 if (lastWhite == -1 || col < maxCols)\r
529                                         lastWhite = n;\r
530                                 else if (col >= maxCols)\r
531                                         n = lastWhite + 1;\r
532                                 \r
533                                 Console.WriteLine (new String (' ', margin) + text.Substring (sn, lastWhite - sn));\r
534                                 margin = leftMargin;\r
535                         }\r
536                 }\r
537         }\r
538 }\r
539 \r
540 #endif\r