Jacob Mason
Jacob Mason

Reputation: 1395

Generating proxy class from WSDL on the fly?

I'm currently working a Windows Service which when started takes a load of scripts and compiles them for running on a schedule, however some of these scripts need to access ASMX web services.

My preference would be to use these WSDL files in code to generate the .vb file ready for me to compile.

How could I achieve this without the command line?

Upvotes: 4

Views: 347

Answers (1)

lokusking
lokusking

Reputation: 7456

I dont really get, why you dont want to use the native/legacy-Tools from CommandLine, but here you go:

var wsdlDescription = ServiceDescription.Read(YourWSDLFile);
      var wsdlImporter = new ServiceDescriptionImporter();
      wsdlImporter.ProtocolName = "Soap12"; //Might differ
      wsdlImporter.AddServiceDescription(wsdlDescription, null, null);
      wsdlImporter.Style = ServiceDescriptionImportStyle.Server;
      wsdlImporter.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
      var codeNamespace = new CodeNamespace();
      var codeUnit = new CodeCompileUnit();
      codeUnit.Namespaces.Add(codeNamespace);
      var importWarning = wsdlImporter.Import(codeNamespace, codeUnit);
      if (importWarning == 0) {
        var stringBuilder = new StringBuilder();
        var stringWriter = new StringWriter(stringBuilder);
        var codeProvider = CodeDomProvider.CreateProvider("Vb");
        codeProvider.GenerateCodeFromCompileUnit(codeUnit, stringWriter, new CodeGeneratorOptions());
        stringWriter.Close();
        File.WriteAllText(WhereYouWantYourClass, stringBuilder.ToString(), Encoding.UTF8);

      } else {

        Console.WriteLine(importWarning);

      }

Note

This is depending on System.CodeDom and System.CodeDom.Compiler
You can also generate a c# file by replacing CodeDomProvider.CreateProvider("Vb") with CodeDomProvider.CreateProvider("CSharp")
This Code is tested with this WSDL wich is pretty simple.

Upvotes: 2

Related Questions