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