none
Adding a Web reference dynamically at Runtime

    Question

  •  

    Hi,

    There is a web service which sends an array of objects when called. I want to add this web service as a Web Reference in another C# (or ASP .NET) Project at the Run Time dynamically and access the web service’s web methods and get the output.

    Could someone please tell me how to do this? without adding the Web Reference when coding and compiling.

    The application I’m creating is a Migration System which migrates data (objects) from several systems to a centralized database. Data are acquired from other systems through their Web Services. Since I don’t know what are all these web services I want my system to be able to dynamically load a web service and query the methods available and attributes in the output object.

    Please help soon.

    Thanks verymuch

    Riz

    Tuesday, November 27, 2007 5:56 AM

Answers

  • using System;

    using System.Collections.Generic;

    using System.Text;

    using System.Reflection;

    using System.CodeDom;

    using System.CodeDom.Compiler;

    using System.Security.Permissions;

    using System.Web.Services.Description;

     

    namespace ConnectionLib

    {

    internal class WsProxy

    {

    [SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]

    internal static object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args)

    {

    System.Net.WebClient client = new System.Net.WebClient();

    // Connect To the web service

    System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

    // Now read the WSDL file describing a service.

    ServiceDescription description = ServiceDescription.Read(stream);

    ///// LOAD THE DOM /////////

    // Initialize a service description importer.

    ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

    importer.ProtocolName = "Soap12"; // Use SOAP 1.2.

    importer.AddServiceDescription(description, null, null);

    // Generate a proxy client.

    importer.Style = ServiceDescriptionImportStyle.Client;

    // Generate properties to represent primitive values.

    importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

    // Initialize a Code-DOM tree into which we will import the service.

    CodeNamespace nmspace = new CodeNamespace();

    CodeCompileUnit unit1 = new CodeCompileUnit();

    unit1.Namespaces.Add(nmspace);

    // Import the service into the Code-DOM tree. This creates proxy code that uses the service.

    ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

    if (warning == 0) // If zero then we are good to go

    {

    // Generate the proxy code

    CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");

    // Compile the assembly proxy with the appropriate references

    string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };

    CompilerParameters parms = new CompilerParameters(assemblyReferences);

    CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);

    // Check For Errors

    if (results.Errors.Count > 0)

    {

    foreach (CompilerError oops in results.Errors)

    {

    System.Diagnostics.Debug.WriteLine("========Compiler error============");

    System.Diagnostics.Debug.WriteLine(oops.ErrorText);

    }

    throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");

    }

    // Finally, Invoke the web service method

    object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);

    MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);

    return mi.Invoke(wsvcClass, args);

    }

    else

    {

    return null;

    }

    }

    }

    }

    • Proposed as answer by DarkKnight671 Thursday, July 31, 2008 2:24 PM
    • Marked as answer by Riyazarm Wednesday, April 08, 2009 2:57 AM
    Monday, March 03, 2008 4:45 PM
  • No, you can not add a web reference at runtime.  Adding a web reference creates several classes that allow you to interface with the web service; those classes need to be compiled before they can be used.

     

    If you want to dynamically support different types of web services, they'll have to use an consistent interface so that a single set of classes can use the web services.  Otherwise, you'll have to implement something that queries the web service's definition and creates some sort of user interface for the user to enter the data that needs to get to the web service.

    Tuesday, November 27, 2007 5:00 PM
    Moderator

All replies

  • No, you can not add a web reference at runtime.  Adding a web reference creates several classes that allow you to interface with the web service; those classes need to be compiled before they can be used.

     

    If you want to dynamically support different types of web services, they'll have to use an consistent interface so that a single set of classes can use the web services.  Otherwise, you'll have to implement something that queries the web service's definition and creates some sort of user interface for the user to enter the data that needs to get to the web service.

    Tuesday, November 27, 2007 5:00 PM
    Moderator
  • Thanks Peter,

     

    Yes it seems like there's no way of doing this.

     

    I avoided this issue by making my application a Web Service where other interfaces can call in to and send there information. This is way easier than the other options. The only draw back is the other interfaces will need a code change to include to include my web service as a web reference.

     

    Thanks again for your answer.

     

    Thursday, November 29, 2007 12:16 AM
  • using System;

    using System.Collections.Generic;

    using System.Text;

    using System.Reflection;

    using System.CodeDom;

    using System.CodeDom.Compiler;

    using System.Security.Permissions;

    using System.Web.Services.Description;

     

    namespace ConnectionLib

    {

    internal class WsProxy

    {

    [SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]

    internal static object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args)

    {

    System.Net.WebClient client = new System.Net.WebClient();

    // Connect To the web service

    System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

    // Now read the WSDL file describing a service.

    ServiceDescription description = ServiceDescription.Read(stream);

    ///// LOAD THE DOM /////////

    // Initialize a service description importer.

    ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

    importer.ProtocolName = "Soap12"; // Use SOAP 1.2.

    importer.AddServiceDescription(description, null, null);

    // Generate a proxy client.

    importer.Style = ServiceDescriptionImportStyle.Client;

    // Generate properties to represent primitive values.

    importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

    // Initialize a Code-DOM tree into which we will import the service.

    CodeNamespace nmspace = new CodeNamespace();

    CodeCompileUnit unit1 = new CodeCompileUnit();

    unit1.Namespaces.Add(nmspace);

    // Import the service into the Code-DOM tree. This creates proxy code that uses the service.

    ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

    if (warning == 0) // If zero then we are good to go

    {

    // Generate the proxy code

    CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");

    // Compile the assembly proxy with the appropriate references

    string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };

    CompilerParameters parms = new CompilerParameters(assemblyReferences);

    CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);

    // Check For Errors

    if (results.Errors.Count > 0)

    {

    foreach (CompilerError oops in results.Errors)

    {

    System.Diagnostics.Debug.WriteLine("========Compiler error============");

    System.Diagnostics.Debug.WriteLine(oops.ErrorText);

    }

    throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");

    }

    // Finally, Invoke the web service method

    object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);

    MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);

    return mi.Invoke(wsvcClass, args);

    }

    else

    {

    return null;

    }

    }

    }

    }

    • Proposed as answer by DarkKnight671 Thursday, July 31, 2008 2:24 PM
    • Marked as answer by Riyazarm Wednesday, April 08, 2009 2:57 AM
    Monday, March 03, 2008 4:45 PM
  •  

     Thanks howiecii  your solution was very usefull.

     what is still disquieting me is the post from Peter Ritchie saying this can't be done?!

     which is not clear why cause, the code from howiecii  ,provide a way to compile the 

    Web Service interface via his WSDL and by this discover its Web Methods.

     

    Peter Ritchie ,anyone?

     

    Wednesday, March 19, 2008 5:49 PM
  • This code was super useful and a major life saver.  Thank you so much for posting it!!!

     

    Monday, May 05, 2008 8:40 PM
  • The code is very useful. Thanks a lot.

     

    Using this code we can only access UnAuthenticated web services, but is there any mechanism so that we can access Authenticated web services as well (considering tha case that - I am providing Username and Password).

     

    Can someone please help.

     

    Thanks

     

    Wednesday, May 21, 2008 7:39 AM
  • Hi Peter Ritchie/ howiecii,
                       Your code is very useful but i have a scenario like need to add Authenticated Web Services dynamically at runtime to my application. Please suggest me how to send user credentials to the web services.

    Thanks in advance.
    • Edited by MuthuKumara Friday, June 13, 2008 5:43 AM Change the content
    Friday, June 13, 2008 5:41 AM
  • Hi howiecii,

    When the code executes the Line

    return mi.Invoke(wsvcClass, args);

    It throws these two error messages

    "Exception has been thrown by the target of an invocation."

    "The request failed with HTTP status 401: Unauthorized."



    Please help me on this . what will be the issue.
    Wednesday, July 09, 2008 7:59 AM
  • 401 Errors thrown by the site itself require that you make use of credentials before you connect to the site.

    To do this, change the method declaration to:
    internal static object CallWebService(string webServiceAsmxUrl, string userName, string password, string serviceName, string methodName, object[] args) 

    and add the following lines under the
    WebClient client = new WebClient(); 
    statement:
    if(userName.Length>0)  
    {  
        client.Credentials = new NetworkCredential(userName, password);  

    If the site you are connecting to requires a domain to be sent as well, the NetworkCredential class also supports constructors for this. See http://msdn.microsoft.com/en-us/library/system.net.networkcredential.networkcredential.aspx for more on the NetworkCredential class.

    Thursday, July 31, 2008 2:23 PM
  • Works Like a charm

    Thx

    Ziv Israel
    Tuesday, August 05, 2008 6:53 AM
  • Hi firstly thank you for the code sharing it with us;
    i used that code snippet in my project and im having some trouble.
    it always returns null value.
    so when i made ServiceDescriptionImportWarnings warning = 0 wsvcClass returned null. and i don't know why
    any help will be appreciated.
    Tuesday, August 19, 2008 11:23 AM
  • I solved the problem
    It is about Soap12 standards
    For example some service wsdls don't support soap12 standard.
    Declaring soap standard as default solves the problem.

    it works great!
    Friday, September 05, 2008 5:04 PM
  • I want to get the Method List using Type.GetMethods();

    However, this list is huge and shows me all the methods available in the proxy class...

    Discover
    get_SoapVersion
    set_SoapVersion
    get_AllowAutoRedirect
    set_AllowAutoRedirect
    etc..

    I wonder if there's anyway we could show only the remote methods...
    I need this because I want an application where the user may choose the method from the list.. I don't want to hard code it!

    Thanks in advance
    Wednesday, October 01, 2008 4:13 PM
  • Hi,
    did u tried to reflect the assembly using reflection or am i understanding you in a wrong way?

    Software Developer
    Thursday, October 02, 2008 11:10 AM
  • Yes! I've used reflection... I've used the code shown above with some tweaks to get the method list...

    The problem is the number of methods of the proxy class, as I've said, I want to create a very simple interface with the list of methods... like a DropDown with the list of methods that generates a form according to the parameters of the selected method and a button to invoke the service... But with all these methods it is more complicated!


    • Proposed as answer by Deepak Mittal Sunday, October 05, 2008 5:40 AM
    Thursday, October 02, 2008 1:46 PM
  • Hi,

    To check the method is web method or not do the following...

    MethodInfo[] methods = service.GetMethods();  
    foreach (MethodInfo method in methods)  
    {  
      if (isWebServiceMethod(method))  
    {  
     
      //Add in the list box or any container  
    }  
    }  
    public static bool isWebServiceMethod(MemberInfo pMethodInfo) {  
     return (Attribute.GetCustomAttribute(pMethodInfo, typeof(System.Web.Services.Protocols.SoapDocumentMethodAttribute), false)!=null ||  
      Attribute.GetCustomAttribute(pMethodInfo, typeof (System.Web.Services.Protocols.SoapRpcMethodAttribute), false) != null);  
    }  
     
     

    Thanks,
    Deepak M. 
    • Proposed as answer by pedrolopes Monday, October 06, 2008 8:19 AM
    Sunday, October 05, 2008 5:52 AM
  • Well, the trick did it!

    Thank you ;)
    Monday, October 06, 2008 8:19 AM
  • Hi

    How to pass parameter's of the WebMethod? 

    How to set the 'Out' attribute for a parameter?

    for example see this URL, a web service with 'out' parameters...
    http://msdn.microsoft.com/en-us/library/copy.copy.getitem.aspx
    • Edited by Vivekthangaswamy Tuesday, October 21, 2008 2:37 AM elaborating the question
    Wednesday, October 08, 2008 12:51 PM
  • mi.Invoke(wsvcClass, args);
    args means your parameters to pass the service.

    Software Developer
    Tuesday, October 14, 2008 3:36 PM
  • How to set the 'Out' attribute for a parameter?

    for example see this URL, a web service with 'out' parameters...
    http://msdn.microsoft.com/en-us/library/copy.copy.getitem.aspx
    Monday, October 20, 2008 4:08 PM
  • How can we can the web service asynchnorously using wsProxy class?
    Wednesday, December 31, 2008 2:01 PM
  • Hi All,

     object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName); Returns null, I made sure of the web service url and name, I tried it on a vertual web service hosted locally and it works, but with the service I need it Boooms.
    Thursday, March 26, 2009 12:34 PM
  • Check the class name that you are instantiating. You have to include namespace if you have defined namespace as in the following line -
    CodeNamespace nmspace = new CodeNamespace("mynamespace");

    In this case use the following line to instantiate:
    object wsvcClass = results.CompiledAssembly.CreateInstance("mynamespace."+serviceName);

    Wednesday, April 01, 2009 1:18 PM
  • Hi this is working fine for .asmx type service reference, but it is not working with .svc type service.

    Please tell me how can i add service reference, .svc type, dynamically.
    Monday, April 06, 2009 12:56 PM
  • can i give string as parameter instead of object datatype if so how?.........




    Thanks
    Jeyanth
    Wednesday, September 23, 2009 5:57 PM
  • Hello,Anja

    I am facing same issue for which you have give solution ,i tried every possible code but still getting null value in wsvcClass so what should i do now?

    i am new to do work with Web service so don't have deep knowledge into..

    My webservice supports SOAP 1.2

    i have read whole blog ,cant find solution for other then this.my web service currently on my localhost   but it will transfer to server .(just for information)

     

    this is some my code snippet

       CodeNamespace nmspace = new CodeNamespace("ImapEmailClient");

       CodeCompileUnit unit1 = new CodeCompileUnit();

        unit1.Namespaces.Add(nmspace);

    //to invoke WS method

    object wsvcClass = results.CompiledAssembly.CreateInstance("ImapEmailClient"+serviceName);

     MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);

     return mi.Invoke(wsvcClass, args);

     

    please any help..?

     

    Wednesday, August 11, 2010 10:56 AM
  • I found this code amazing and it worked on the first try. My question is: The client provided a WSDL url and a SOAP endpoint URL. By just passing the WSDL url, this worked and i was able to get a result from the web service.

    The client doc specified to do ws.URL = soapEndpoint.

    How did it work with just the WSDL url and do I need the soap endpoint?

    If so, how do i set it. I set the credentials via reflection after it is compiled.

    Thanks!

    Sunday, September 05, 2010 2:21 AM
  • I did use the following code because my webservice has Windows Integrated Security authentication:

    client.Credentials = System.Net.CredentialCache.DefaultCredentials;
    Thursday, November 04, 2010 4:30 PM
  • I need to get specific values inside the returned array, but I receive the error: "Cannot apply indexing with [] to an expression of type 'object.'" How do I fix this?

    EDIT:

    I now have the answer: cast the returned object to IEnumerable.

     

    Thursday, November 11, 2010 4:15 PM
  • If user enter the service URL in a text box. What should I put in ServiceName? I guess any name, it doesn't matter. Right? I tried with namespace and without. Still get null in wsvcClass.

    CodeNamespace nmspace = new CodeNamespace();
    
    CodeCompileUnit unit1 = new CodeCompileUnit();
    
    unit1.Namespaces.Add(nmspace);
    
    object wsvcClass = results.CompiledAssembly.CreateInstance("MyService");
    
    
    
    
    
    

    Edit: I figured out that the Namespace and ServiceName should exactly match with your web service otherwise it won't work. It is kind of wierd that we are adding reference dynamically so how will I know the exact namespace/servicename? Does anyone know a way to get them dynamically if user just passes the service url?
    Monday, March 14, 2011 1:38 PM
  • Hi Howiecii,

     

    That was very helpful. I am stuck with a small issue. The parameters for the web methods are enumerators. How do I pass these values. I would like to pass this as string, and when the code is compiled in the proxy assembly this has to be passed as Enum types.

    Any help would be appreciated.

     

    thank you.


    Ravi
    Tuesday, April 12, 2011 1:09 PM
  • how to call this method what will we pass to object[] args parameter.
    Tuesday, April 19, 2011 9:50 AM
  • Hi,

    How do I can add soap headers to this code?

    Thanks.

    Thursday, May 12, 2011 6:29 PM
  • In Visual Studio Solution Explorer you can right-click the "References" node. Add a "Service reference" and type the MS CRM http address.

    For metadata service is something like this:
    http://<server name>:<port>/MSCRMServices/2007/MetadataService.asmx

    For crm service:
    http://<server name>:<port>/MSCrmServices/2007/CrmServiceWsdl.aspx?uniquename=<CRM Organization name>

    Thursday, May 12, 2011 9:58 PM
  • Hi,

     

    This is really awesome. But what does ServiceName in the parameters refer to. I understand webserviceasmxurl and method, but what is service name and how do I get it??

     

    please reply soon.

     

    Thanks! 


    Jlo
    Wednesday, August 24, 2011 2:03 AM
  • Got it. Just add a web reference to the URL and you will find the namespace in the name of the service. Run during debug and type out the namespace and a "." and you will get the name of the service.

     

    Also if you open the webservce url ina browser you will find the serviceName in the blueColor heading at the TOP. in my case the serviceName was "Service"


    Jlo
    Wednesday, August 24, 2011 3:00 AM
  • I've used this part with my IIS set to Anonymous. I want to use it with Windows Auth... I tried giving the webclient credentials, but this doesn't work. Everytime I hit the Invoke, I get an 401 Unauthorized error. Any clue on how to solve this?
    Monday, September 26, 2011 11:37 AM
  • Hi howiecii,

     

    I am getting following error:

    "Exception has been thrown by the target of an invocation."

    on this line:

     return mi.Invoke(wsvcClass, args);

     

    Please help me with the problem.

    Monday, October 31, 2011 12:33 PM
  • When I call the below method it throws the exception Ambiguous match found.

    wsvcClass.GetType().GetMethod(methodName);

    Monday, January 21, 2013 10:49 AM
  • Hi,

    I am looking for the same answer if you sorted kindly help me to solve this.

    Regards

    Hi this is working fine for .asmx type service reference, but it is not working with .svc type service.

    Please tell me how can i add service reference, .svc type, dynamically.

    • Proposed as answer by ranjanritesh Monday, June 17, 2013 7:09 AM
    • Unproposed as answer by ranjanritesh Monday, June 17, 2013 7:09 AM
    Tuesday, May 28, 2013 9:51 AM
  • Following code can help you do this for .svc type

    Uri mexAddress = new Uri(uri);
                MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;
    
                // Get Metadata file from service
                MetadataExchangeClient mexClient = new MetadataExchangeClient();
                mexClient.ResolveMetadataReferences = true;
                MetadataSet metaSet = mexClient.GetMetadata(mexAddress, mexMode);
    
                //Import all contracts and endpoints
                WsdlImporter importer = new WsdlImporter(metaSet);
    
                Collection<ContractDescription> contracts = importer.ImportAllContracts();
                ServiceEndpointCollection allEndpoints = importer.ImportAllEndpoints();
    
                //Generate type information for each contract
                ServiceContractGenerator generator = new ServiceContractGenerator();
                var endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();
    
                foreach (ContractDescription contract in contracts)
                {
                    generator.GenerateServiceContractType(contract);
                    // Keep a list of each contract's endpoints
                    endpointsForContracts[contract.Name] = allEndpoints.Where(se => se.Contract.Name == contract.Name).ToList();
                }
    
                if (generator.Errors.Count != 0)
                    throw new Exception("There were errors while calling the service.");
    
                // Generate a code file for the contracts 
                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.BracingStyle = "C";
                CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");
    
                // Compile the code file to an in-memory assembly
                // Don't forget to add all WCF-related assemblies as references
                CompilerParameters compilerParameters = new CompilerParameters(
                    new string[] { 
                        "System.dll", "System.ServiceModel.dll", 
                        "System.Runtime.Serialization.dll" });
                compilerParameters.GenerateInMemory = true;
    
                CompilerResults results = codeDomProvider.CompileAssemblyFromDom(compilerParameters, generator.TargetCompileUnit);
    
                if (results.Errors.Count > 0)
                {
                    throw new Exception("There were errors during generated code compilation");
                }
    
                // Find the proxy type that was generated for the specified contract
                // (identified by a class that implements 
                // the contract and ICommunicationbject)
                Type clientProxyType = results.CompiledAssembly.GetTypes().First(t => t.IsClass && t.GetInterface(contractName) != null && t.GetInterface(typeof(ICommunicationObject).Name) != null);
    
                // Get the first service endpoint for the contract
                ServiceEndpoint serviceEndPoint = endpointsForContracts[contractName].First();
                object instance = results.CompiledAssembly.CreateInstance(clientProxyType.Name, false, System.Reflection.BindingFlags.CreateInstance, null, new object[] { serviceEndPoint.Binding, serviceEndPoint.Address }, CultureInfo.CurrentCulture, null);

    Wednesday, January 08, 2014 10:18 PM
  • thanks a lot for the code.

    I have a query.

    How can we send input parameters of different datatypes as an array of objects(i.e args() in the above code)  to the web method.

    For eg.

    I have a web method in which I have to pass a String array and string. How can I pass them under same array of objects.

    Thanks a lot in advance. 


    Tuesday, September 16, 2014 3:25 AM
  • Thanks people.  Follow my version with X509 certificate:

     /// <summary>
        /// by yop038 on http://stackoverflow.com/questions/2066489/how-can-you-add-a-certificate-to-webclient-c
        /// </summary>
        public class CertificateWebClient : WebClient
        {
            private readonly X509Certificate2 certificate;
    
            public CertificateWebClient(X509Certificate2 cert)
            {
                certificate = cert;
            }
    
            protected override WebRequest GetWebRequest(Uri address)
            {
                HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
    
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
                {
                    return true;
                };
    
                request.UnsafeAuthenticatedConnectionSharing = false;
                request.ClientCertificates.Add(certificate);
    
                return request;
            }
        }
    
        internal class WsProxy
        {
    
            internal static object CallWebService(X509Certificate2 x509cert, string webServiceAsmxUrl, string serviceName, string methodName, object[] args)
            {
    
                var client = new CertificateWebClient(x509cert);
    
                
                // Connect To the web service
                System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
    
                // Now read the WSDL file describing a service.
                ServiceDescription description = ServiceDescription.Read(stream);
    
                ///// LOAD THE DOM /////////
                // Initialize a service description importer.
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
    
                importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
    
                importer.AddServiceDescription(description, null, null);
    
                // Generate a proxy client.
                importer.Style = ServiceDescriptionImportStyle.Client;
    
                // Generate properties to represent primitive values.
                importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
    
                // Initialize a Code-DOM tree into which we will import the service.
                CodeNamespace nmspace = new CodeNamespace();
    
                CodeCompileUnit unit1 = new CodeCompileUnit();
    
                unit1.Namespaces.Add(nmspace);
    
                // Import the service into the Code-DOM tree. This creates proxy code that uses the service.
                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
    
                if (warning == 0) // If zero then we are good to go
                {
    
                    // Generate the proxy code
                    CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
    
                    // Compile the assembly proxy with the appropriate references
                    string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
    
                    CompilerParameters parms = new CompilerParameters(assemblyReferences);
    
                    CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
    
                    // Check For Errors
                    if (results.Errors.Count > 0)
                    {
    
                        foreach (CompilerError oops in results.Errors)
                        {
    
                            System.Diagnostics.Debug.WriteLine("========Compiler error============");
    
                            System.Diagnostics.Debug.WriteLine(oops.ErrorText);
    
                        }
    
                        throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");
    
                    }
    
                    // Finally, Invoke the web service method
                    object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
    
                    var webService = wsvcClass as HttpWebClientProtocol;
    
                    if (webService!= null)
                    {
                        webService.UnsafeAuthenticatedConnectionSharing = false;
                        webService.ClientCertificates.Add(x509cert);
                    }
                    
                    MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
    
                    return mi.Invoke(wsvcClass, args);
    
                }
    
                else
                {
    
                    return null;
    
                }
    
            }
    
        }

    Wednesday, September 24, 2014 7:28 PM
  • nice post :)
    Wednesday, March 18, 2015 9:17 AM
  • really ? And what howiecii code does ? Landing on moon without wings ?
    Tuesday, February 06, 2018 10:40 AM