Click here to Skip to main content
Click here to Skip to main content

Call WebService Dynamically and Read WebService Definition

, 17 Apr 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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;

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:

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 Wink | ;)

License

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

Share

About the Author

abhinavshastri
Software Developer (Senior)
India India
IT professional completed B.Tech in Computer Science with 7 years experience in design and development of Web and Windows application using Microsoft .NET Technology, C#.Net, VB.Net, ASP.NET with database in MS SQL Server 2000/2005/2008/2012 and MYSQL, Experience on full Software Development life cycle (SDLC) of software applications on web based environments.

Comments and Discussions

 
GeneralCongrats PinmemberEcalgarotto24-Oct-13 10:14 
GeneralRe: Congrats Pinmemberabhinavshastri9-Nov-14 20:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150326.1 | Last Updated 17 Apr 2012
Article Copyright 2012 by abhinavshastri
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid