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