Thursday, 15 November 2007

Call webservice without adding webreference:

1. Create a class as with "DynamicWebService" and new method "CallWebService".
2. Create an object od this class and call method "CallWebService" with web service url and other paramaters.

Create a new class and replace the code for this:


Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Security.Permissions
Imports System.Web.Services.Description
Imports System.Reflection

Public Class DynamicWebService

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

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()

'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)
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============")
Throw New System.Exception("Compile Error Occured 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)
Return Nothing
End If
Catch ex As Exception
Throw ex
End Try
End Function
End Class


Call this web service in a form or method etc... as below..

Dim WebserviceUrl As String = ""

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

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

'Paraments 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)


Nikolas said...

Thank you for your very helpful code. It saved my day!

I have only one remark:
Add the following line

parms.GenerateInMemory = True

when you create the compiler parameters. It has two advantages:
First it is faster and second you don't run in the "Failed to grant permission to execute
" error.

Cris said...

HI friends, this information is very interesting, I would like read more information about this topic, thanks for sharing.

homes for sale in costa rica

Liz said...

Hello .. firstly I would like to send greetings to all readers. After this, I recognize the content so interesting about this article. For me personally I liked all the information. I would like to know of cases like this more often. In my personal experience I might mention a book called Generic Viagra in this book that I mentioned have very interesting topics, and also you have much to do with the main theme of this article.

aMo said...

Hi! im getting this error msg: "An exception has been thrown by the target of an invocation." I have already set the credentials but still no luck. Please help.

rantoblogs said...

Hi.. I've same problem with aMo, but when I did inner tracing, I've got an inner exception like this "Method may only be called on a Type for which Type.IsGenericParameter is true." actually when you Declare the MethodInfo.. Can u fix this problem?

just information, I've convert your code to C#, because I'm using it on my project...