Saturday, July 19, 2008

Flexible consumption of Webservice

A quick way to consume a web service is to add Web Reference to the project. This works well most of the time.

However, imagine a scenario where you are supporting multiple sites in different countries and assuming that each of these sites are hosting the similar webservice locally. If you were to use web reference then you will need to compile a copy for each of theses sites (after changing the reference).

A much better way is to:
  1. Create a proxy class using the wsdl.exe tool from Microsoft.
  2. Copy the constructor from the proxy class and create one that will take the url as a parameter.
  3. Use this new constructor in the project that needs to consume the webservice and refer to the config file for the url (so you just need to change that value for each site).
To create the proxy class, just run the following command:

"c:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin\wsdl.exe" /o:samplews.vb /l:vb /n:MyService http://localhost/sampleSrv/Service1.asmx?wsdl

Depending on which version of VS you have, the wsdl.exe may be in a different folder. For VS 2008, it is in c:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\wsdl.exe

In the above example, my webservice is http://localhost/sampleSrv/Service1.asmx and I created a proxy program in VB (Visual Basic) and saved it in a file samplews.vb. I also indicated that the class be placed with a namespace MyService.

The following is a snippet of the code generated:
' <autogenerated>
' This code was generated by a tool.
' Runtime Version: 1.1.4322.2407
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </autogenerated>

Option Strict Off
Option Explicit On

Imports System
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml.Serialization

'This source code was auto-generated by wsdl, Version=1.1.4322.2407.
Namespace MyService

<System.Diagnostics.DebuggerStepThroughAttribute(), _
System.ComponentModel.DesignerCategoryAttribute("code"), _
System.Web.Services.WebServiceBindingAttribute(Name:="WriterServicesSoap", [Namespace]:="")> _
Public Class Service1
Inherits System.Web.Services.Protocols.SoapHttpClientProtocol

Public Sub New()
Me.Url = "http://localhost/sampleSrv/Service1.asmx"
End Sub

Make a copy of the new subroutine and change it as follows:

Public Sub New(byval pUrl As String)
Me.Url = pUrl
End Sub

Either add this new source code to your project or create it as an independent assembly (dll) and reference it.

To use it then, you create:

Dim vSvc as New MyService.Service1(url)
' Where url is a string variable which you get the value from your application config file.

instead of

Dim vSvc As New MyService.Service1()

1 comment:

Strovek said...

You can find wsdl in C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin for Framework 2.0