How to consume a web service in code directly

As well as using a wizard it is possible to access web services using code. These are the steps.

  1. Open a Visual Studio Command Prompt
  2. Navigate to a suitable directory e.g. c:\Temp
  3. Use WSDL. Examples
    C# is default language
    wsdl http: //  …myservice.asmx
    For VB use
    wsdl /language:vb http://.. myservice.asmx
    Your service might be .svc
  4. Press return and the wsdl program should write out a file for your consumption
  5. This creates a web service proxy, which will talk to the service.
  6. In your project create a folder say named Service
  7. Add in your new file
  8. Add reference to System.Web.Services
  9. Add code similar to:

myService MyService1 = new myService()

var result = myService.myMethod();

To create a batch file to do this automatically

Thanks to:

http://stackoverflow.com/questions/5879076/how-to-create-a-batch-file-for-visual-studio-command-prompt

call “C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat” x86
wsdl /language:vb /out:MyServiceName.vb http:// … myservice.svc
pause

Why does the consumed service return arrays when I specified a List(of T)

WCF tries hard to not create services which are .Net dependent. So by default the return of List(Of T) will return an array.

If you add a service using the .Net UI, then there is an option:

Configure Service Reference > Always Generate Message Contracts > Collection Type > Change to what you want, which may be a System.Collections.Generic.List.

There is a similar option with svcutil and probably wsdl, but I have not used this yet.

The End.

Advertisements