tune on make all, not on install
[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                                 GenerateCode (references, codeUnit);\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                                 \r
176                         StringCollection validationWarnings;\r
177                         WebReferenceOptions opts = new WebReferenceOptions ();\r
178                         opts.CodeGenerationOptions = options;\r
179                         opts.Style = style;\r
180                         opts.Verbose = verbose;\r
181                         validationWarnings = ServiceDescriptionImporter.GenerateWebReferences (references, provider, codeUnit, opts);\r
182                         \r
183                         for (int n=0; n<references.Count; n++)\r
184                         {\r
185                                 WebReference wr  = references [n];\r
186                                 \r
187                                 BasicProfileViolationCollection violations = new BasicProfileViolationCollection ();\r
188                                 if (String.Compare (protocol, "SOAP", StringComparison.OrdinalIgnoreCase) == 0 && !WebServicesInteroperability.CheckConformance (WsiProfiles.BasicProfile1_1, wr, violations)) {\r
189                                         wr.Warnings |= ServiceDescriptionImportWarnings.WsiConformance;\r
190                                 }\r
191                                 \r
192                                 if (wr.Warnings != 0)\r
193                                 {\r
194                                         if (!hasWarnings) {\r
195                                                 WriteText ("", 0, 0);\r
196                                                 WriteText ("There where some warnings while generating the code:", 0, 0);\r
197                                         }\r
198                                         \r
199                                         WriteText ("", 0, 0);\r
200                                         WriteText (urls[n], 2, 2);\r
201                                         \r
202                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.WsiConformance) > 0) {\r
203                                                 WriteText ("- This web reference does not conform to WS-I Basic Profile v1.1", 4, 6); \r
204                                                 foreach (BasicProfileViolation vio in violations) {\r
205                                                         WriteText (vio.NormativeStatement + ": " + vio.Details, 8, 8);\r
206                                                         foreach (string ele in vio.Elements)\r
207                                                                 WriteText ("* " + ele, 10, 12);\r
208                                                 }\r
209                                         }\r
210                                         \r
211                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) > 0)\r
212                                                 WriteText ("- WARNING: No proxy class was generated", 4, 6); \r
213                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) > 0)\r
214                                                 WriteText ("- WARNING: The proxy class generated includes no methods", 4, 6);\r
215                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) > 0)\r
216                                                 WriteText ("- WARNING: At least one optional extension has been ignored", 4, 6);\r
217                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) > 0)\r
218                                                 WriteText ("- WARNING: At least one necessary extension has been ignored", 4, 6);\r
219                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) > 0)\r
220                                                 WriteText ("- WARNING: At least one binding is of an unsupported type and has been ignored", 4, 6);\r
221                                         if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) > 0)\r
222                                                 WriteText ("- WARNING: At least one operation is of an unsupported type and has been ignored", 4, 6);\r
223                                                 \r
224                                         hasWarnings = true;\r
225                                 }\r
226                         }\r
227                         \r
228                         if (hasWarnings) WriteText ("",0,0);\r
229                                 \r
230                         string filename = outFilename;\r
231                         bool hasBindings = false;\r
232                         \r
233                         foreach (object doc in references[0].Documents.Values)\r
234                         {\r
235                                 ServiceDescription desc = doc as ServiceDescription;\r
236                                 if (desc == null) continue;\r
237                                 \r
238                                 if (desc.Services.Count > 0 && filename == null)\r
239                                         filename = desc.Services[0].Name + "." + provider.FileExtension;\r
240                                         \r
241                                 if (desc.Bindings.Count > 0 || desc.Services.Count > 0)\r
242                                         hasBindings = true;\r
243                         }\r
244                         \r
245                         if (filename == null)\r
246                                 filename = "output." + provider.FileExtension;\r
247                         \r
248                         if (hasBindings) {\r
249                                 WriteText ("Writing file '" + filename + "'", 0, 0);\r
250                                 StreamWriter writer = new StreamWriter(filename);\r
251                                 \r
252                                 CodeGeneratorOptions compilerOptions = new CodeGeneratorOptions();\r
253                                 provider.GenerateCodeFromCompileUnit (codeUnit, writer, compilerOptions);\r
254                                 writer.Close();\r
255                         }\r
256                         \r
257                         return hasWarnings;\r
258                 }\r
259                 \r
260                 ///\r
261                 /// <summary>\r
262                 ///     Create the CodeNamespace with the generator's signature commented in.\r
263                 /// </summary>\r
264                 ///\r
265                 CodeNamespace GetCodeNamespace()\r
266                 {\r
267                         CodeNamespace codeNamespace = new CodeNamespace(ns);\r
268                         \r
269                         if (applicationSignature != null)\r
270                         {\r
271                                 codeNamespace.Comments.Add(new CodeCommentStatement("\n This source code was auto-generated by " + applicationSignature + "\n"));\r
272                         }\r
273                         \r
274                         return codeNamespace;\r
275                 }\r
276                 \r
277                 ///\r
278                 /// <summary/>\r
279                 ///\r
280                 void WriteCodeUnit(CodeCompileUnit codeUnit, string serviceName)\r
281                 {\r
282                         CodeDomProvider provider = GetProvider();\r
283                         ICodeGenerator generator = provider.CreateGenerator();\r
284                         CodeGeneratorOptions options = new CodeGeneratorOptions();\r
285                         \r
286                         string filename;\r
287                         if (outFilename != null)\r
288                                 filename = outFilename;\r
289                         else\r
290                                 filename = serviceName  + "." + provider.FileExtension;\r
291                         \r
292                         Console.WriteLine ("Writing file '{0}'", filename);\r
293                         StreamWriter writer = new StreamWriter(filename);\r
294                         generator.GenerateCodeFromCompileUnit(codeUnit, writer, options);\r
295                         writer.Close();\r
296                 }\r
297                 \r
298                 ///\r
299                 /// <summary>\r
300                 ///     Fetch the Code Provider for the language specified by the 'language' members.\r
301                 /// </summary>\r
302                 ///\r
303                 private CodeDomProvider GetProvider()\r
304                 {\r
305                         CodeDomProvider provider;\r
306                         Type type;\r
307                         \r
308                         switch (language.ToUpper ()) {\r
309                         case "CS":\r
310                                 provider = new CSharpCodeProvider ();\r
311                                 break;\r
312                         case "VB":\r
313                                 provider = new Microsoft.VisualBasic.VBCodeProvider ();\r
314                                 break;\r
315                         case "BOO":\r
316                                 type = Type.GetType("Boo.Lang.CodeDom.BooCodeProvider, Boo.Lang.CodeDom, Version=1.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67");\r
317                                 if (type != null){\r
318                                         return (CodeDomProvider) Activator.CreateInstance (type);\r
319                                 }\r
320                                 throw new Exception ("Boo.Lang.CodeDom.BooCodeProvider not available");\r
321                                 \r
322                         default:\r
323                                 type = Type.GetType(language);\r
324                                 if (type != null) {\r
325                                         return (CodeDomProvider) Activator.CreateInstance (type);\r
326                                 }       \r
327                                 throw new Exception ("Unknown language");\r
328                         }\r
329                         return provider;\r
330                 }\r
331                 \r
332 \r
333 \r
334                 ///\r
335                 /// <summary>\r
336                 ///     Interperet the command-line arguments and configure the relavent components.\r
337                 /// </summary>\r
338                 ///             \r
339                 void ImportArgument(string argument)\r
340                 {\r
341                         string optionValuePair;\r
342                         \r
343                         if (argument.StartsWith("--"))\r
344                         {\r
345                                 optionValuePair = argument.Substring(2);\r
346                         }\r
347                         else if (argument.StartsWith("/") || argument.StartsWith("-"))\r
348                         {\r
349                                 optionValuePair = argument.Substring(1);\r
350                         }\r
351                         else\r
352                         {\r
353                                 urls.Add (argument);\r
354                                 return;\r
355                         }\r
356                         \r
357                         string option;\r
358                         string value;\r
359                         \r
360                         int indexOfEquals = optionValuePair.IndexOf(':');\r
361                         if (indexOfEquals > 0)\r
362                         {\r
363                                 option = optionValuePair.Substring(0, indexOfEquals);\r
364                                 value = optionValuePair.Substring(indexOfEquals + 1);\r
365                         }\r
366                         else\r
367                         {\r
368                                 option = optionValuePair;\r
369                                 value = null;\r
370                         }\r
371                         \r
372                         switch (option)\r
373                         {\r
374                                 case "appsettingurlkey":\r
375                                 case "urlkey":\r
376                                     appSettingURLKey = value;\r
377                                     break;\r
378 \r
379                                 case "appsettingbaseurl":\r
380                                 case "baseurl":\r
381                                     appSettingBaseURL = value;\r
382                                     break;\r
383 \r
384                                 case "d":\r
385                                 case "domain":\r
386                                     domain = value;\r
387                                     break;\r
388 \r
389                                 case "l":\r
390                                 case "language":\r
391                                     language = value;\r
392                                     break;\r
393 \r
394                                 case "n":\r
395                                 case "namespace":\r
396                                     ns = value;\r
397                                     break;\r
398 \r
399                                 case "nologo":\r
400                                     noLogo = true;\r
401                                     break;\r
402 \r
403                                 case "o":\r
404                                 case "out":\r
405                                     outFilename = value;\r
406                                     break;\r
407 \r
408                                 case "p":\r
409                                 case "password":\r
410                                     password = value;\r
411                                     break;\r
412 \r
413                                 case "protocol":\r
414                                     protocol = value;\r
415                                     break;\r
416 \r
417                                 case "proxy":\r
418                                     proxyAddress = value;\r
419                                     break;\r
420 \r
421                                 case "proxydomain":\r
422                                 case "pd":\r
423                                     proxyDomain = value;\r
424                                     break;\r
425 \r
426                                 case "proxypassword":\r
427                                 case "pp":\r
428                                     proxyPassword = value;\r
429                                     break;\r
430 \r
431                                 case "proxyusername":\r
432                                 case "pu":\r
433                                     proxyUsername = value;\r
434                                     break;\r
435 \r
436                                 case "server":\r
437                                     style = ServiceDescriptionImportStyle.Server;\r
438                                     break;\r
439 \r
440                                 case "u":\r
441                                 case "username":\r
442                                     username = value;\r
443                                     break;\r
444                                         \r
445                                 case "verbose":\r
446                                         verbose = true;\r
447                                         break;\r
448                                         \r
449                                 case "fields":\r
450                                         options &= ~CodeGenerationOptions.GenerateProperties;\r
451                                         break;\r
452                                         \r
453                                 case "sample":\r
454                                         sampleSoap = value;\r
455                                         break;\r
456 \r
457                                 case "?":\r
458                                     help = true;\r
459                                     break;\r
460 \r
461                                 default:\r
462                                         if (argument.StartsWith ("/") && argument.IndexOfAny (Path.InvalidPathChars) == -1) {\r
463                                                 urls.Add (argument);\r
464                                                 break;\r
465                                         }\r
466                                         else\r
467                                             throw new Exception("Unknown option " + option);\r
468                         }\r
469                 }\r
470                 \r
471                 DiscoveryClientProtocol CreateClient ()\r
472                 {\r
473                         DiscoveryClientProtocol dcc = new DiscoveryClientProtocol ();\r
474                         \r
475                         if (username != null || password != null || domain != null)\r
476                         {\r
477                                 NetworkCredential credentials = new NetworkCredential();\r
478                                 \r
479                                 if (username != null)\r
480                                         credentials.UserName = username;\r
481                                 \r
482                                 if (password != null)\r
483                                         credentials.Password = password;\r
484                                 \r
485                                 if (domain != null)\r
486                                         credentials.Domain = domain;\r
487                                 \r
488                                 dcc.Credentials = credentials;\r
489                         }\r
490                         \r
491                         if (proxyAddress != null)\r
492                         {\r
493                                 WebProxy proxy = new WebProxy (proxyAddress);\r
494                                 if (proxyUsername != null || proxyPassword != null || proxyDomain != null)\r
495                                 {\r
496                                         NetworkCredential credentials = new NetworkCredential();\r
497                                         \r
498                                         if (proxyUsername != null)\r
499                                                 credentials.UserName = proxyUsername;\r
500                                         \r
501                                         if (proxyPassword != null)\r
502                                                 credentials.Password = proxyPassword;\r
503                                         \r
504                                         if (proxyDomain != null)\r
505                                                 credentials.Domain = proxyDomain;\r
506                                         \r
507                                         proxy.Credentials = credentials;\r
508                                 }\r
509                         }                       \r
510                         \r
511                         return dcc;\r
512                 }\r
513                 \r
514                 static void WriteText (string text, int initialLeftMargin, int leftMargin)\r
515                 {\r
516                         int n = 0;\r
517                         int margin = initialLeftMargin;\r
518                         int maxCols = 80;\r
519                         \r
520                         if (text == "") {\r
521                                 Console.WriteLine ();\r
522                                 return;\r
523                         }\r
524                         \r
525                         while (n < text.Length)\r
526                         {\r
527                                 int col = margin;\r
528                                 int lastWhite = -1;\r
529                                 int sn = n;\r
530                                 while (col < maxCols && n < text.Length) {\r
531                                         if (char.IsWhiteSpace (text[n]))\r
532                                                 lastWhite = n;\r
533                                         col++;\r
534                                         n++;\r
535                                 }\r
536                                 \r
537                                 if (lastWhite == -1 || col < maxCols)\r
538                                         lastWhite = n;\r
539                                 else if (col >= maxCols)\r
540                                         n = lastWhite + 1;\r
541                                 \r
542                                 Console.WriteLine (new String (' ', margin) + text.Substring (sn, lastWhite - sn));\r
543                                 margin = leftMargin;\r
544                         }\r
545                 }\r
546         }\r
547 }\r
548 \r
549 #endif\r