Sunday, April 19, 2009

Simple C# webservice and consuming it in windows form application

I was toying with the idea of implementing the version check routine for Getbhavcopy as a webservice. While doing so I am thinking of adding a facility where important messages (like stock splits and bonus data) can be sent to users.

This led me to test the concept with a simple addition webservice

1. Creating the webservice

Since I already have an account at www.somee.com, which supports ASP.NET I decided to go ahead and see if it supports web services. Thankfully it did without issues so the biggest issue of finding a free host was not an issue. I recommend it as a free ASP.NET host. They are good and stable, but if you need support then do not use them.

Start Visual Web Developer 2008 Express edition. Create a New web site, of the type ASP.NET web service.


In the Solution Explorer, you will notice namely 3 files created, Service.asmx, App_Code\Service.cs and Web.config.

The Service.asmx file has the following code

<%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs" Class="Service" %>

We see that the code behind is in the Service.cs file. Open the Service.cs file; change the namespace and add the AddInts method to it. Now the code looks as follows

using System;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://www.getbhavcopy.com")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
 public Service () {

     //Uncomment the following line if using designed components
     //InitializeComponent();
 }

 [WebMethod]
 public string HelloWorld() {
     return "Hello World";
 }

 [WebMethod]
 public int AddInts(int a, int b)
 {
     return (int)(a + b);
 }

}

It is always advisable to change the namespace to something more meaningful. Each XML Web service needs a unique namespace in order for client applications to distinguish it from other services on the Web. http://tempuri.org/ is available for XML Web services that are under development, but published XML Web services should use a more permanent namespace.

Your XML Web service should be identified by a namespace that you control. For example, you can use your company's Internet domain name as part of the namespace. Although many XML Web service namespaces look like URLs, they need not point to actual resources on the Web. (XML Web service namespaces are URIs.)

The WebMethod attribute before the function means that this function is to be exposed as a webservice function.

In this example we are using simple data types as the input and output parameters. However in real world scenarios this is not often the case. If we want to return complex data or more than one simple data types then we are better off creating structures types to hold the data.

2. Test if you can read the WSDL of the webserivice as follows.

I have the same file above exposed on my site http://hemenkapadia.somee.com.

To get the WSDL for this service the URL will be http://hemenkapadia.somee.com/service.asmx?wsdl

If the WSDL opens without issues you are done creating the web service

3. Consuming the web service in a windows app.

Start Microsoft Visual C# Express Edition and create a new Console application.

To consume the Web service we need to create a web reference to it. To do so, in the Solution Explorer, right click 'References' and select 'Add Service Reference'.

In the window that pops up click the 'Advanced' button. In the advanced window click the 'Add Web Reference' button. This will popup another window.

In the URL field add the web service WSDL http://hemenkapadia.somee.com/service.asmx?wsdl. Click the 'Go' button on the window.



Click the 'Add Reference' button.



This will add the 'Web References' folder in the Solution Explorer. Browse to the location of the solution in the file system. Notice that the 'Web References' folder is added on the project folder too. It will have a folder com.somee.hemenkapadia and will have a Reference.cs file within as well as the wsdl. The cs file defines a partial class Service that provides an Object Oriented way of calling the Web service. To consume the service you can create an instance of this service class and call the appropriate method on it.

Now add the following code to Program.cs

using System;
using _05ConsumingWebService.com.somee.hemenkapadia;

namespace _05ConsumingWebService
{
  class Program
  {
      static void Main(string[] args)
      {
          Console.WriteLine("*** Testing Webservice Application ***");
          if (args.Length != 2)
          {
              Console.WriteLine("Incorrect Usage");
              Console.WriteLine("Usage: TestWebService integer integer");
          }
          else
          {
              int a = int.Parse(args[0]);
              int b = int.Parse(args[1]);
              Console.WriteLine("Invoking Webservice with parameters : {0} {1}", a, b);

              //now make the call to the Webservice
              Service ws = new Service();
              Console.WriteLine("WS output: {0}", ws.AddInts(a, b).ToString());
          }
          Console.ReadLine();
      }
  }
}


Compile the app to generate the executable and try to execute it from the command prompt with two integer arguments, you will notice the added output returned from the webservice,

No comments:

Post a Comment