Click here to Skip to main content
15,895,667 members
Articles / Web Development / ASP.NET

Call a Web Service Without Adding a Web Reference

Rate me:
Please Sign up or sign in to vote.
4.75/5 (10 votes)
11 Sep 2009CPOL 106.1K   17   17
Calling a Web Service without adding a web reference

Introduction

A client requested that for some reason he cannot add a Web Reference and wanted to specify the web service URL in web.config or hardcode it. Hence, my first article:)

Background

I did create this source more than a year ago. I used the internet to get information/ideas regarding this.

I am copying from my blog.

Using the Code

  1. Create a class as with "DynamicWebService" and new method "CallWebService".
  2. Create an object of this class and call method "CallWebService" with web service URL and other parameters:
VB.NET
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Security.Permissions
Imports System.Web.Services.Description
Imports System.Reflection

Public Function CallWebService(ByVal webServiceAsmxUrl As String, _
       ByVal serviceName As String, ByVal methodName As String, _
       ByVal args() As Object) As Object

    Try
    Dim client As System.Net.WebClient = New System.Net.WebClient()

    '-Connect To the web service
    Dim stream As System.IO.Stream = _
        client.OpenRead(webServiceAsmxUrl + "?wsdl")

    'Read the WSDL file describing a service.
    Dim description As ServiceDescription = ServiceDescription.Read(stream)

    'LOAD THE DOM'''''''''''''''''''''''''''

    '--Initialize a service description importer.
    Dim importer As ServiceDescriptionImporter = New ServiceDescriptionImporter()
    importer.ProtocolName = "Soap12" ' Use SOAP 1.2.
    importer.AddServiceDescription(description, Nothing, Nothing)

    '--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.
    Dim nmspace As CodeNamespace = New CodeNamespace()
    Dim unit1 As CodeCompileUnit = New CodeCompileUnit()
    unit1.Namespaces.Add(nmspace)

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

    Dim warning As ServiceDescriptionImportWarnings = _
                   importer.Import(nmspace, unit1)

    If warning = 0 Then

            '--Generate the proxy code
            Dim provider1 As CodeDomProvider = _
                      CodeDomProvider.CreateProvider("VB")
            '--Compile the assembly proxy with the // appropriate references
            Dim assemblyReferences() As String
            assemblyReferences = New String() {"System.dll", _
                "System.Web.Services.dll", "System.Web.dll", _
                "System.Xml.dll", "System.Data.dll"}
        	Dim parms As CompilerParameters = New CompilerParameters(assemblyReferences)
	parms.GenerateInMemory = True '(Thanks for this line nikolas)
        	Dim results As CompilerResults = provider1.CompileAssemblyFromDom(parms, unit1)

        '-Check For Errors
        If results.Errors.Count > 0 Then

            Dim oops As CompilerError
            For Each oops In results.Errors
                System.Diagnostics.Debug.WriteLine("========Compiler error============")
                System.Diagnostics.Debug.WriteLine(oops.ErrorText)
            Next
            Throw New System.Exception("Compile Error Occurred calling webservice.")
        End If

        '--Finally, Invoke the web service method
        Dim wsvcClass As Object = results.CompiledAssembly.CreateInstance(serviceName)
        Dim mi As MethodInfo = wsvcClass.GetType().GetMethod(methodName)
        Return mi.Invoke(wsvcClass, args)

    Else
        Return Nothing
    End If

    Catch ex As Exception
    Throw ex
    End Try
End Function

Calling

Call this web service in a Webform or windows form or method, etc... as shown below:

VB.NET
Dim WebserviceUrl As String = _
"http://www.abc.com/lgl/test/webservice/v1_00/security.asmx"

'specify service name
Dim serviceName As String = "SecurityAndSessionManagement"

'specify method name to be called
Dim methodName As String = "Session_Start"

'Arguments passed to the method
Dim arArguments(1) As String
arArguments(0) = "abc"
arArguments(1) = "xxxx"

Dim objCallWS As New DynamicWebService
sSessionID = objCallWS.CallWebService(WebserviceUrl, serviceName, _
                                      methodName, arArguments)
MsgBox("new SessionID: " & sSessionID)

History

  • 11th September, 2009: Initial post

License

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


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGet Structures in the webservice Pin
Member 1108277221-May-15 3:06
Member 1108277221-May-15 3:06 
QuestionRegarding Calling Web Service without adding Web Reference Pin
Priyatam Upadrasta11-May-15 0:39
Priyatam Upadrasta11-May-15 0:39 
QuestionWhat about WebServices over SSL? Pin
MiCRo_28-Nov-12 21:24
MiCRo_28-Nov-12 21:24 
Questioncan you show the .asmx file ? Pin
rantoyusuf6-Sep-12 23:21
rantoyusuf6-Sep-12 23:21 
Questionhow if the address of the .asmx was unknown? Pin
scot12345678915-Jul-12 17:31
scot12345678915-Jul-12 17:31 
GeneralInvoking Sharepoint Web Service return 401 error Pin
stefets12311-Nov-09 1:53
stefets12311-Nov-09 1:53 
GeneralRe: Invoking Sharepoint Web Service return 401 error Pin
LukeWatson10-May-10 23:36
LukeWatson10-May-10 23:36 
GeneralRe: Invoking Sharepoint Web Service return 401 error Pin
erwinlagac2-Feb-11 17:52
erwinlagac2-Feb-11 17:52 
GeneralRe: Invoking Sharepoint Web Service return 401 error Pin
Andrew M. Obial2-Feb-11 18:08
Andrew M. Obial2-Feb-11 18:08 
GeneralRe: Invoking Sharepoint Web Service return 401 error Pin
jose_israel_17_26-Jul-16 5:43
jose_israel_17_26-Jul-16 5:43 
GeneralNice - however problem to discover complex types Pin
Goran Bacvarovski15-Sep-09 7:04
Goran Bacvarovski15-Sep-09 7:04 
GeneralC# Version Pin
wvd_vegt15-Sep-09 1:12
professionalwvd_vegt15-Sep-09 1:12 
For those looking for a CSharp port:

I've made the DynamicWebService class static so it saves a couple of instances lingering around.

I also added some examples of how to decode the output.

The first example webservice returns a dataset,
the second one returns an array of objects containing
weatherinfo. I used some code from
Making ASP.NET databinding via # work, without reflection to cast without reflection for a change.

1) The DynamicWebService class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//Added for samplecode
using System.CodeDom.Compiler;
using System.Security.Permissions;
using System.Web.Services.Description;
using System.Reflection;
using System.CodeDom;
using System.Diagnostics;

namespace DynamicSoap
{

    public static class DynamicWebService
    {

        public static Object CallWebService(string webServiceAsmxUrl,
           string serviceName, string methodName, object[] args)
        {

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

                //-Connect To the web service
                System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

                //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 codenamespace = new CodeNamespace();
                CodeCompileUnit codeunit = new CodeCompileUnit();
                codeunit.Namespaces.Add(codenamespace);

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

                ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);

                if (warning == 0)
                {

                    //--Generate the proxy code
                    CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

                    //--Compile the assembly proxy with the 
                    //  appropriate references
                    string[] assemblyReferences = new string[]  {
                       "System.dll", 
                       "System.Web.Services.dll", 
                       "System.Web.dll", 
                       "System.Xml.dll", 
                       "System.Data.dll"};

                    //--Add parameters
                    CompilerParameters parms = new CompilerParameters(assemblyReferences);
                    parms.GenerateInMemory = true; //(Thanks for this line nikolas)
                    CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
                    
                    //--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 Exception("Compile Error Occured calling WebService.");
                    }

                    //--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;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}


2) An example form with one Textbox and two Buttons:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DynamicSoap
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Clear();

            //Specify service Url without ?wsdl suffix.
            String WSUrl = "http://www.jasongaylord.com/webservices/zipcodes.asmx";

            //Specify service name
            String WSName = "ZipCodes";

            //Specify method name to be called
            String WSMethodName = "ZipCodeToDetails";

            //Parameters passed to the method
            String[] WSMethodArguments = new String[1];
            WSMethodArguments[0] = "20500";

            //Create and Call Service Wrapper
            Object WSResults = DynamicWebService.CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);

            //Decode Results
            if (WSResults is DataSet)
            {
                textBox1.Text += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
            }
            else if (WSResults.GetType().IsArray)
            {
                Object[] oa = (Object[])WSResults;

                //Retrieve a property value withour reflection...
                PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
                foreach (Object oae in oa)
                {
                    textBox1.Text += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
                }
            }
            else
            {
                textBox1.Text += ("Result: \r\n" + WSResults.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();

            //Specify service Url without ?wsdl suffix.
            String WSUrl = "http://360.org/services/WeatherService.asmx";

            //Specify service name
            String WSName = "WeatherService";

            //Specify method name to be called
            String WSMethodName = "Query";

            //Parameters passed to the method
            String[] WSMethodArguments = new String[1];
            WSMethodArguments[0] = "Maastricht";

            //Create and Call Service Wrapper
            Object WSResults = DynamicWebService.CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);

            //Decode Results
            if (WSResults is DataSet)
            {
                textBox1.Text += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
            }
            else if (WSResults.GetType().IsArray)
            {
                Object[] oa = (Object[])WSResults;

                //Retrieve a property value withour reflection...
                PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
                foreach (Object oae in oa)
                {
                    textBox1.Text += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
                }
            }
            else
            {
                textBox1.Text += ("Result: \r\n" + WSResults.ToString());
            }
        }
    }
}


3) Raw output first service:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <ZipCodeToDetailsResponse xmlns="http://www.jasongaylord.com/webservices/zipcodes">
            <ZipCodeToDetailsResult>
                <xs:schema
                    id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
                    <xs:element
                        name="NewDataSet"
                        msdata:IsDataSet="true"
                        msdata:UseCurrentLocale="true">
                        <xs:complexType>
                            <xs:choice
                                minOccurs="0"
                                maxOccurs="unbounded">
                                <xs:element
                                    name="Details">
                                    <xs:complexType>
                                        <xs:sequence>
                                            <xs:element
                                                name="latitude"
                                                type="xs:string"
                                                minOccurs="0" />
                                            <xs:element
                                                name="longitude"
                                                type="xs:string"
                                                minOccurs="0" />
                                            <xs:element
                                                name="city"
                                                type="xs:string"
                                                minOccurs="0" />
                                            <xs:element
                                                name="state"
                                                type="xs:string"
                                                minOccurs="0" />
                                            <xs:element
                                                name="county"
                                                type="xs:string"
                                                minOccurs="0" />
                                            <xs:element
                                                name="addresstype"
                                                type="xs:string"
                                                minOccurs="0" />
                                            <xs:element
                                                name="noaazone"
                                                type="xs:string"
                                                minOccurs="0" />
                                        </xs:sequence>
                                    </xs:complexType>
                                </xs:element>
                            </xs:choice>
                        </xs:complexType>
                    </xs:element>
                </xs:schema>
                <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
                    <NewDataSet xmlns="">
                        <Details
                            diffgr:id="Details1"
                            msdata:rowOrder="0">
                            <city>WASHINGTON</city>
                            <state>DC</state>
                            <county>DISTRICT OF COLUMBIA</county>
                            <addresstype>STANDARD</addresstype>
                            <noaazone>DCZ001</noaazone>
                        </Details>
                    </NewDataSet>
                </diffgr:diffgram>
            </ZipCodeToDetailsResult>
        </ZipCodeToDetailsResponse>
    </soap:Body>
</soap:Envelope>

4) Raw Output second service:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <QueryResponse xmlns="http://360.org/xml/schemas/cwml/2009/01">
            <QueryResult>
                <weatherInfo
                    locationId="933"
                    dateTimeUtc="2009-09-15T06:00:00">
                    <locationInfo>
                        <latitude>50.9166679</latitude>
                        <longitude>5.7833333</longitude>
                        <description>Maastricht Airport Zuid Limburg</description>
                        <country>Netherlands</country>
                    </locationInfo>
                    <temperatureInfo>
                        <celcius>11</celcius>
                        <fahrenheit>43</fahrenheit>
                    </temperatureInfo>
                </weatherInfo>
                <weatherInfo
                    locationId="4232"
                    dateTimeUtc="2009-09-15T04:00:00">
                    <locationInfo>
                        <latitude>50.9166679</latitude>
                        <longitude>5.7833333</longitude>
                        <description>Meetstation Maastricht</description>
                        <country>The Netherlands</country>
                    </locationInfo>
                    <temperatureInfo>
                        <celcius>10.8</celcius>
                        <fahrenheit>42.8</fahrenheit>
                    </temperatureInfo>
                </weatherInfo>
            </QueryResult>
        </QueryResponse>
    </soap:Body>
</soap:Envelope>

GeneralVoted a 3 Pin
Rob Eckert12-Sep-09 3:49
Rob Eckert12-Sep-09 3:49 
GeneralNo Code Explanation Pin
Md. Marufuzzaman11-Sep-09 8:04
professionalMd. Marufuzzaman11-Sep-09 8:04 
GeneralMy vote of 2 Pin
0x3c011-Sep-09 6:45
0x3c011-Sep-09 6:45 
GeneralMy vote of 1 Pin
Dave Kreskowiak11-Sep-09 6:41
mveDave Kreskowiak11-Sep-09 6:41 
GeneralRe: My vote of 1 Pin
askaslam27-Sep-09 22:11
askaslam27-Sep-09 22:11 

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

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