Click here to Skip to main content
Licence CPOL
First Posted 11 Sep 2009
Views 21,348
Bookmarked 11 times

Call a Web Service Without Adding a Web Reference

Calling a Web Service without adding a web reference
   3.75 (8 votes)
1 vote, 12.5%
1

2
1 vote, 12.5%
3

4
6 votes, 75.0%
5
3.75/5 - 8 votes
μ 3.75, σa 2.60 [?]
 

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:
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:

    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)

About the Author

Aslam.Iqbal@electoralreform.co.uk



United Kingdom United Kingdom

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralInvoking Sharepoint Web Service return 401 error Pinmemberstefets1232:53 11 Nov '09  
GeneralRe: Invoking Sharepoint Web Service return 401 error PinmemberLukeWatson0:36 11 May '10  
GeneralRe: Invoking Sharepoint Web Service return 401 error Pinmembererwinlagac18:52 2 Feb '11  
GeneralRe: Invoking Sharepoint Web Service return 401 error PinmemberAndrew M. Obial19:08 2 Feb '11  
GeneralNice - however problem to discover complex types Pinmembermaxxnostra8:04 15 Sep '09  
GeneralC# Version Pinmemberwvd_vegt2:12 15 Sep '09  
GeneralVoted a 3 PinmemberRob Eckert4:49 12 Sep '09  
GeneralNo Code Explanation PingroupMd. Marufuzzaman9:04 11 Sep '09  
GeneralMy vote of 2 PinmemberComputafreak7:45 11 Sep '09  
GeneralMy vote of 1 PinmvpDave Kreskowiak7:41 11 Sep '09  
GeneralRe: My vote of 1 PinmemberAslam.Iqbal@electoralreform.co.uk23:11 27 Sep '09  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120222.1 | Last Updated 11 Sep 2009
Article Copyright 2009 by Aslam.Iqbal@electoralreform.co.uk
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid