The purpose of this tutorial is to show you how to make a call to a Web Service in the context of a WPF application. The following common tasks will be examined:
- Adding a reference.
- Creating a new instance of the service.
- Making call to the service.
The process of developing a Web Service is beyond the scope of this tutorial. For more information read here.
This tutorial will use the Northwind database, which can be download it from here.
For the purpose of this tutorial will be used a service that exposes the following method:
- LoadCategories - load all categories from the Categories table in the Northwind database.
Adding A Reference
The first step is to add a new service reference to your application. In order to do that you need to perform the following steps:
- Select the "References" folder, right click with your mouse button and choose "Add Service Reference..."
- A popup window appears, hit the Discover button to find the web service or enter the service location. Press 'OK' to add it.
You have the ability to choose the type of the collections that the service returns. In order to do that you need to open the Service Reference Settings dialog from the Advanced button.
When a service reference is added to a project, any types defined in the service are generated in the local project. In many cases, this creates duplicate types when a service uses common .NET Framework types or when types are defined in a shared library. To avoid this problem, types in referenced assemblies are shared by default. If you want to disable type sharing for one or more assemblies, you can do so in the Service Reference Settings dialog.
Once the Web service is added all needed assemblies and configuration files will be included in your project automatically.
Creating New Instance of the Service
Creating new instance of the service is pretty simple process.
WebService.SampleWebServiceSoapClient serviceClient = new WebService.SampleWebServiceSoapClient();
Dim serviceClient As New WebService.SampleWebServiceSoapClient()
Don't forget to give a meaningful name for your Web Service namespace. In the previous example the namespace is "WebService".
Making Call to the Service
In order to make a call to your service, you just need to invoke the exposed by the service method.
foreach( Categories c in serviceClient.LoadCategories() )
this.Categories.Add( c );
For Each c As Categories In serviceClient.LoadCategories()