Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / IIS

Call WebService Dynamically and Read WebService Definition

5.00/5 (5 votes)
17 Apr 2012CPOL 37.3K  
How to Call WebService Dynamically and Read WebService Definition

Introduction

This tip shows how to call a WebService dynamically and read the WebService definition.

Using the code

Calling the WebService dynamically;

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Reflection;
using System.CodeDom.Compiler;
using System.Web.Services.Description;
using System.Xml.Serialization;
using System.CodeDom;
using System.Collections;
using System.Text.RegularExpressions;
 
 
namespace TestingProject
{
    public partial class Temp : System.Web.UI.Page
    {        
 
        protected void Page_Load(object sender, EventArgs e)
        {
            CallingWebService();
        }
 
        void RegExpForCountryCity(string strHTML)
        {
            Regex qariRegex = new Regex(@"<Table>\s*<Country>(?<Country>" + 
               @"[\s\S]*?)</Country>\s*<City>(?<City>[\s\S]*?)</City>\s*</Table>", 
               RegexOptions.IgnoreCase | RegexOptions.Multiline);
            MatchCollection mc = qariRegex.Matches(strHTML);
            string strCountryCity = "";
            for (int i = 0; i < mc.Count; i++)
            {
                if (string.IsNullOrEmpty(strCountryCity))
                    strCountryCity = "Country: " + "<b>" + mc[i].Groups["Country"].Value + 
                      "</b>" + " " + "City: " + "<b>" + mc[i].Groups["City"].Value + "</b>" + "</br>";
                else
                    strCountryCity += "</br>" + "Country: " + "<b>" + mc[i].Groups["Country"].Value + 
                      "</b>" + " " + "City: " + "<b>" + mc[i].Groups["City"].Value + "</b>" + "</br>";
            }
            Response.Write(strCountryCity);
        }
 
        void CallingWebService()
        {
            System.Net.WebClient client = new System.Net.WebClient();
            System.IO.Stream stream = 
                   client.OpenRead("http://www.webservicex.net/globalweather.asmx?wsdl");          
            ServiceDescription description = ServiceDescription.Read(stream);         
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
            importer.ProtocolName = "Soap12";  
            importer.AddServiceDescription(description, null, null);           
            importer.Style = ServiceDescriptionImportStyle.Client;          
            importer.CodeGenerationOptions = 
                     System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            CodeNamespace nmspace = new CodeNamespace();
            CodeCompileUnit unit1 = new CodeCompileUnit();
            unit1.Namespaces.Add(nmspace);
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
            if (warning == 0)
            {              
                CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");               
                string[] assemblyReferences = 
                  new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
                CompilerParameters parms = new CompilerParameters(assemblyReferences);
                CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
                object[] args = new object[1];
                args[0] = "India";              
                object wsvcClass = results.CompiledAssembly.CreateInstance("GlobalWeather");
                MethodInfo mi = wsvcClass.GetType().GetMethod("GetCitiesByCountry");
                RegExpForCountryCity(mi.Invoke(wsvcClass, args).ToString());              
            }
            else
            {                
                Console.WriteLine("Warning: " + warning);
            }
        }    
 
    }
}

Read WebService definition:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Reflection;
using System.CodeDom.Compiler;
using System.Web.Services.Description;
using System.Xml.Serialization;
using System.CodeDom;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;

namespace TestingProject
{
    public partial class ReadWebServiceDefinition : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DynamicInvocation();
        }

        void RegExp(string strHTML)
        {
            Hashtable ht = new Hashtable();           
            Regex qariRegex = new Regex(@"<Table>\s*<Country>([" + 
               @"\s\S]*?)</Country>\s*<City>([\s\S]*?)</City>\s*</Table>");
            MatchCollection mc = qariRegex.Matches(strHTML);
            //CaptureCollection cc = mc[0].Captures;
            ht.Add(mc[0].Captures, mc[1].Captures);          
        }

        void DynamicInvocation()
        {
            Uri uri = new Uri("http://www.webservicex.net/globalweather.asmx?WSDL");
            WebRequest webRequest = WebRequest.Create(uri);
            System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
            ServiceDescription sd = ServiceDescription.Read(requestStream);
            string sdName = sd.Services[0].Name;
            ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
            servImport.AddServiceDescription(sd, String.Empty, String.Empty);
            servImport.ProtocolName = "Soap";
            servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;
            CodeNamespace nameSpace = new CodeNamespace();
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            codeCompileUnit.Namespaces.Add(nameSpace);
            ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);
            if (warnings == 0)
            {
                StringWriter stringWriter = new StringWriter
                    (System.Globalization.CultureInfo.CurrentCulture);
                Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
                prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());
                string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
                CompilerParameters param = new CompilerParameters(assemblyReferences);
                param.GenerateExecutable = false;
                param.GenerateInMemory = true;
                param.TreatWarningsAsErrors = false;
                param.WarningLevel = 4;
                CompilerResults results = new CompilerResults(new TempFileCollection());
                results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
                Assembly assembly = results.CompiledAssembly;
                string strClassName = string.Empty;
                string strMethodName = string.Empty;
                Type[] types = assembly.GetTypes();
                ArrayList arrl = new ArrayList();
                foreach (Type cls in types)
                {
                    arrl.Add("Namespace: " + cls.FullName);
                    if (cls.IsAbstract)
                        arrl.Add("Abstract Class Name: " + cls.Name.ToString());
                    else if (cls.IsPublic)
                        arrl.Add("Public Class Name: " + cls.Name.ToString());
                    else if (cls.IsSealed)
                        arrl.Add("Sealed Class Name: " + cls.Name.ToString());
                }

                for (int i = 0; i < arrl.Count; i++)
                {
                    if (string.IsNullOrEmpty(strClassName))
                        strClassName = arrl[i].ToString();
                    else
                        strClassName += "</br>" + arrl[i].ToString();
                }

                strMethodName = strClassName + "</br>";
                foreach (MethodInfo t in assembly.GetType(sdName).GetMethods())
                {
                    if (t.Name == "Discover")
                        break;

                    if (string.IsNullOrEmpty(strMethodName))
                        strMethodName = "MethodName : " + t.Name + "</br>" + t.ToString();
                    else
                        strMethodName += System.Environment.NewLine + 
                         "</br></br>" + "MethodName : " + t.Name + "</br>" + t.ToString();
                }
             
                Response.Write(strMethodName);
            }
        }
    }
}

Keep smiling ;)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)