/// /// MonoWSDL.cs -- a WSDL to proxy code generator. /// /// Author: Erik LeBel (eriklebel@yahoo.ca) /// Lluis Sanchez (lluis@ximian.com) /// /// Copyright (C) 2003, Erik LeBel, /// using System; using System.Xml; using System.Xml.Schema; using System.Collections; using System.CodeDom; using System.CodeDom.Compiler; using System.IO; using System.Net; using System.Web.Services.Description; using System.Web.Services.Discovery; using Microsoft.CSharp; namespace Mono.WebServices { /// /// /// Source code generator. /// /// class SourceGenerator { string applicationSiganture = null; string appSettingURLKey = null; string appSettingBaseURL = null; string language = "CS"; string ns = null; string outFilename = null; string protocol = "Soap"; bool server = false; /// /// /// public string Language { // FIXME validate set { language = value; } } /// /// /// public string Namespace { set { ns = value; } } /// /// /// The file to contain the generated code. /// /// public string Filename { set { outFilename = value; } } /// /// /// public string Protocol { // FIXME validate set { protocol = value; } get { return protocol; } } /// /// /// public string ApplicationSignature { set { applicationSiganture = value; } } /// /// /// public string AppSettingURLKey { set { appSettingURLKey = value; } } /// /// /// public string AppSettingBaseURL { set { appSettingBaseURL = value; } } /// /// /// public bool Server { set { server = value; } } /// /// /// Generate code for the specified ServiceDescription. /// /// public bool GenerateCode (ArrayList descriptions, ArrayList schemas) { // FIXME iterate over each serviceDescription.Services? CodeNamespace codeNamespace = GetCodeNamespace(); CodeCompileUnit codeUnit = new CodeCompileUnit(); bool hasWarnings = false; codeUnit.Namespaces.Add(codeNamespace); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.ProtocolName = protocol; if (server) importer.Style = ServiceDescriptionImportStyle.Server; foreach (ServiceDescription sd in descriptions) importer.AddServiceDescription(sd, appSettingURLKey, appSettingBaseURL); foreach (XmlSchema sc in schemas) importer.Schemas.Add (sc); ServiceDescriptionImportWarnings warnings = importer.Import(codeNamespace, codeUnit); if (warnings != 0) { if ((warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) > 0) Console.WriteLine ("WARNING: No proxy class was generated"); if ((warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) > 0) Console.WriteLine ("WARNING: The proxy class generated includes no methods"); if ((warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) > 0) Console.WriteLine ("WARNING: At least one optional extension has been ignored"); if ((warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) > 0) Console.WriteLine ("WARNING: At least one necessary extension has been ignored"); if ((warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) > 0) Console.WriteLine ("WARNING: At least one binding is of an unsupported type and has been ignored"); if ((warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) > 0) Console.WriteLine ("WARNING: At least one operation is of an unsupported type and has been ignored"); hasWarnings = true; } ServiceDescription rootDesc = null; foreach (ServiceDescription desc in descriptions) { if (desc.Services.Count > 0) { rootDesc = desc; break; } } if (rootDesc != null) { string serviceName = rootDesc.Services[0].Name; WriteCodeUnit(codeUnit, serviceName); } return hasWarnings; } /// /// /// Create the CodeNamespace with the generator's signature commented in. /// /// CodeNamespace GetCodeNamespace() { CodeNamespace codeNamespace = new CodeNamespace(ns); if (applicationSiganture != null) { codeNamespace.Comments.Add(new CodeCommentStatement("\n This source code was auto-generated by " + applicationSiganture + "\n")); } return codeNamespace; } /// /// /// void WriteCodeUnit(CodeCompileUnit codeUnit, string serviceName) { CodeDomProvider provider = GetProvider(); ICodeGenerator generator = provider.CreateGenerator(); CodeGeneratorOptions options = new CodeGeneratorOptions(); string filename; if (outFilename != null) filename = outFilename; else filename = serviceName + "." + provider.FileExtension; Console.WriteLine ("Writing file '{0}'", filename); StreamWriter writer = new StreamWriter(filename); generator.GenerateCodeFromCompileUnit(codeUnit, writer, options); writer.Close(); } /// /// /// Fetch the Code Provider for the language specified by the 'language' members. /// /// private CodeDomProvider GetProvider() { // FIXME these should be loaded dynamically using reflection CodeDomProvider provider; switch (language.ToUpper()) { case "CS": provider = new CSharpCodeProvider(); break; case "VB": provider = new Microsoft.VisualBasic.VBCodeProvider(); break; default: throw new Exception("Unknow language"); } return provider; } } /// /// /// monoWSDL's main application driver. Reads the command-line arguments and dispatch the /// appropriate handlers. /// /// public class Driver { const string ProductId = "Mono Web Services Description Language Utility"; const string UsageMessage = "wsdl [options] {path | URL} \n\n" + " -d, -domain:domain Domain of username for server authentication.\n" + " -l, -language:language Language of generated code. Allowed CS (default)\n" + " and VB.\n" + " -n, -namespace:ns The namespace of the generated code, default\n" + " namespace if none.\n" + " -nologo Surpress the startup logo.\n" + " -o, -out:filename The target file for generated code.\n" + " -p, -password:pwd Password used to contact the server.\n" + " -protocol:protocol Protocol to implement. Allowed: Soap (default),\n" + " HttpGet or HttpPost.\n" + " -server Generate server instead of client proxy code.\n" + " -u, -username:username Username used to contact the server.\n" + " -proxy:url Address of the proxy.\n" + " -pu, -proxyusername:username Username used to contact the proxy.\n" + " -pp, -proxypassword:pwd Password used to contact the proxy.\n" + " -pd, -proxydomain:domain Domain of username for proxy authentication.\n" + " -urlkey, -appsettingurlkey:key Configuration key that contains the default\n" + " url for the generated WS proxy.\n" + " -baseurl, -appsettingbaseurl:url Base url to use when constructing the\n" + " service url.\n" + " -sample:[binding/]operation Display a sample SOAP request and response.\n" + " -? Display this message\n" + "\n" + "Options can be of the forms -option, --option or /option\n"; SourceGenerator generator = null; ArrayList descriptions = new ArrayList (); ArrayList schemas = new ArrayList (); bool noLogo = false; bool help = false; bool hasURL = false; string sampleSoap = null; string proxyAddress = null; string proxyDomain = null; string proxyPassword = null; string proxyUsername = null; string username; string password; string domain; string url; /// /// /// Initialize the document retrieval component and the source code generator. /// /// Driver() { generator = new SourceGenerator(); generator.ApplicationSignature = ProductId; } /// /// /// Interperet the command-line arguments and configure the relavent components. /// /// void ImportArgument(string argument) { string optionValuePair; if (argument.StartsWith("--")) { optionValuePair = argument.Substring(2); } else if (argument.StartsWith("/") || argument.StartsWith("-")) { optionValuePair = argument.Substring(1); } else { hasURL = true; url = argument; return; } string option; string value; int indexOfEquals = optionValuePair.IndexOf(':'); if (indexOfEquals > 0) { option = optionValuePair.Substring(0, indexOfEquals); value = optionValuePair.Substring(indexOfEquals + 1); } else { option = optionValuePair; value = null; } switch (option) { case "appsettingurlkey": case "urlkey": generator.AppSettingURLKey = value; break; case "appsettingbaseurl": case "baseurl": generator.AppSettingBaseURL = value; break; case "d": case "domain": domain = value; break; case "l": case "language": generator.Language = value; break; case "n": case "namespace": generator.Namespace = value; break; case "nologo": noLogo = true; break; case "o": case "out": generator.Filename = value; break; case "p": case "password": password = value; break; case "protocol": generator.Protocol = value; break; case "proxy": proxyAddress = value; break; case "proxydomain": case "pd": proxyDomain = value; break; case "proxypassword": case "pp": proxyPassword = value; break; case "proxyusername": case "pu": proxyUsername = value; break; case "server": generator.Server = true; break; case "u": case "username": username = value; break; case "sample": sampleSoap = value; break; case "?": help = true; break; default: throw new Exception("Unknown option " + option); } } DiscoveryClientProtocol CreateClient () { DiscoveryClientProtocol dcc = new DiscoveryClientProtocol (); if (username != null || password != null || domain != null) { NetworkCredential credentials = new NetworkCredential(); if (username != null) credentials.UserName = username; if (password != null) credentials.Password = password; if (domain != null) credentials.Domain = domain; dcc.Credentials = credentials; } if (proxyAddress != null) { WebProxy proxy = new WebProxy (proxyAddress); if (proxyUsername != null || proxyPassword != null || proxyDomain != null) { NetworkCredential credentials = new NetworkCredential(); if (proxyUsername != null) credentials.UserName = proxyUsername; if (proxyPassword != null) credentials.Password = proxyPassword; if (proxyDomain != null) credentials.Domain = proxyDomain; proxy.Credentials = credentials; } } return dcc; } /// /// /// Driver's main control flow: /// - parse arguments /// - report required messages /// - terminate if no input /// - report errors /// /// int Run(string[] args) { try { // parse command line arguments foreach (string argument in args) { ImportArgument(argument); } if (noLogo == false) Console.WriteLine(ProductId); if (help || !hasURL) { Console.WriteLine(UsageMessage); return 0; } DiscoveryClientProtocol dcc = CreateClient (); dcc.DiscoverAny (url); dcc.ResolveAll (); foreach (object doc in dcc.Documents.Values) { if (doc is ServiceDescription) descriptions.Add ((ServiceDescription)doc); else if (doc is XmlSchema) schemas.Add ((XmlSchema)doc); } if (descriptions.Count == 0) throw new Exception ("No WSDL document was found at the url " + url); if (sampleSoap != null) { ConsoleSampleGenerator.Generate (descriptions, schemas, sampleSoap, generator.Protocol); return 0; } // generate the code if (generator.GenerateCode (descriptions, schemas)) return 1; else return 0; } catch (Exception exception) { Console.WriteLine("Error: {0}", exception.Message); // FIXME: surpress this except for when debug is enabled //Console.WriteLine("Stack:\n {0}", exception.StackTrace); return 2; } } /// /// /// Application entry point. /// /// public static int Main(string[] args) { Driver d = new Driver(); return d.Run(args); } } }