Sunday, June 20, 2010

Consuming Web Services

This is a continuation from the post on Web Services. To read the first part, click here.

In the last post, I introduced Web Services to you. We created a service named ForexService that has one operation that accepts two input currencies as strings and returns the exchange rate as double.

To consume the web service, let’s create a separate application (note that it can be any type of application, windows or web). This application will act as a client. Here you need to add a web reference (right click on the project in solution explorer and say add web reference) in your client application for the service (in our case, I can use the HTTP URL http://localhost/Forex/ForexService.asmx because I created the web service on HTTP). You can experiment on different ways to add web reference.

When you add a web reference, a .discomap file is added to your solution. I named the reference to service as Forex and my file looks like:



What is important to notice in this file is the two DiscoveryClientResult details:
  • System.Web.Services.Discovery.ContractReference 
  • System.Web.Services.Discovery.DiscoveryDocumentReference
The ContractReference url is http://localhost/Forex/Service.asmx?wsdl. This is the URL of the contract that the host puts forward for every client that wants to consume the service provided by the host. Now what is a contract? We mentioned about some restrictions when I was explaining our Forex requirement scenario earlier, remember? A contract is a document that is published to the client whenever the client requests for a service. The contract document lists all details about the service e.g. name and location of the service, list of operations available in the service, the in and out message requirements for communication, port types and so on. Every client must send a request exactly as described in the contract document, otherwise the service will not be rendered. In our example, the Forex webservice extends only one operation, namely GetConversionRate. If you try the URL in a browser, you will be shown details as below. Btw, to explain it further, WSDL stands for Web Service Description Language. That explains it all!



In fact, when we created the service and run it, it displayed us the list of available operations, remember? In the same screen, there is a link on top as Service Description.  If you had tried the link, you must have visited the WSDL file already for our service.

The DiscoveryDocumentReference url is http://localhost/Forex/Service.asmx?disco. It contains details on where the service can be found. Try the URL in browser.

Now that the web reference is added, my client application can consume the web service. Here is a code snippet from the client application:
public partial class _Default : System.Web.UI.Page 
{
   protected void Page_Load(object sender, EventArgs e)
   {
     Forex.ForexService forex = new Forex.ForexService();
     Response.WriteLine("1 US Dollar = " + forex.GetConversionRate("USD", "INR").ToString() + " Indian Rupees");
     Response.WriteLine("1 Euro = " + forex.GetConversionRate("EUR", "INR").ToString() + " Indian Rupees");
   }
}
The code is easy enough to understand, but to put it in short: we have created an object of the class (the service class) and called the GetConversionRate method. The result will be two lines on the page, something like:

1 US Dollar = 49.2 Indian Rupees
1 Euro = 67.3 Indian Rupees

Let us summarize what we know about web services so far. A web service is a code segment placed on a host (server) that can be invoked by a client using an HTTP URL. The host publishes a contract that defines what operations are available to be invoked by client, what inputs are required and in what format the result can be expected. A client can consume a web service by using the reference to the service and invoking its method.

In our example, we used two strings as input and a double as output. In the next post, I will talk about serialization and using more complex types as parameters.

Introducing Web Services

I talked about WCF in brief in one of my earlier postings, but that brought forward a need for a posting on the basics of web services. So, today I am going to talk about web services at a simpler level using a scenario about foreign exchange rates. I am not talking about forex process and it’s just for example’s sake…so don’t post back saying forex rates are not decided that way! ;-)

The central bank in the country decides the forex rate for every particular day. So let’s say, today the US Dollar to Indian Rupee is 46.01 and Euro to Indian Rupee is 56.99. These rates change every day. There are numerous other websites where these rates are displayed and they need to be updated on a daily basis. It is natural that the owners of these websites will request the Central Bank to provide them some automatic mechanism so that the websites can automatically get themselves updated by the changed rates every day.  If I were the system admin at the Central Bank, what would be my options? Give them a read-only access to a file or a table? Or send them this info every day? Or put the rates on some server, some xml file for them to read?

No convincing solution? What about giving them access to some code that is on my server, but the code will return the rates to them by accessing my database? I have to make sure that they access the code in the most secure way possible. Why not give them an HTTP URL that will access our code and return them some data? Even better, why not put some restriction in code so that the incoming data and outgoing data follow the standards posed by the restrictions? And of course, the best way to receive and send data will be XML!

SOAP stands for Service Oriented Access Protocol.  As it is a protocol, it is a standard in which messages are sent across in XML format. Each SOAP message contains a SOAP envelope that has a SOAP header (optional) and SOAP body. I won’t deviate from topic explaining more about SOAP here, but if you want to get a glance of what SOAP is, you can visit this simple tutorial on W3Schools or SOAP on W3C if you are serious about it. It suffices now to understand that SOAP uses XML as a mode of communication; it is an obvious choice for our scenario. What we now need is some sort of application or code running on our server that can interact using SOAP as the protocol. That is what web services are for. So, web services are applications (chunks of code) that reside on the server (the host) and can be invoked by a client by sending a request.

Web services can be written in any language which is obvious because XML is the mode of communication. The client need not know which language the service is written in as long as the request is accepted in XML and the response is sent in XML. You can create an ASP.NET web service in Visual Studio.


Note that I have not used the file system to create the web service; instead used HTTP since I will be using an HTTP based URL to access the service. The picture below should give you enough insight on the web service created. Note the method GetConversionRate that accepts two strings as currencies and returns the rate as double.


Btw, if the images are not clear, you can always click on them and it will open in its original size.

If you run the solution, you should see the page as below. The page just explains that you have accessed the ForexService web service that has only one operation exposed i.e. GetConversionRate.


Click on the method name GetConversionRate and the screen that follows is worth diving into detail. It gives us a test screen where I can type in the required values and invoke the service. Good enough. Let’s look what is below the test module. You notice the SOAP message formats for both 1.1 and 1.2 versions.


When the client sends a request for service to server, the following message is being sent. The data types in blue and bold will be replaced by the appropriate values. You notice that it has got a soap body in a soap envelope, as I mentioned above. The rest should be pretty understandable.
POST /Forex/ForexService.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<soap12:envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soap12:body>
  <getconversionrate xmlns="http://tempuri.org/">
   <currencytoconvertfrom>string</currencytoconvertfrom>
   <currencytoconvertto>string</currencytoconvertto>
  </getconversionrate>
 </soap12:body>
</soap12:envelope>
Similarly, when the server has received the request and processed it, the result is sent in the following message format. This again has an envelope and a body.
HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
 <soap12:Body>
  <getconversionrateresponse xmlns="http://tempuri.org/">
   <getconversionrateresult>double</GetConversionRateResult>
  </GetConversionRateResponse>
 </soap12:Body>
</soap12:Envelope>
So you see, the message formats used when a client sends a service request to a web service and the server responds to the request is based on the SOAP protocol. Since the communication does not have any language specific restrictions, the client and the server (host) in a Service Oriented Architecture can be in different languages. Wonderful! Cross-language, cross-platform freedom!

Now is the time to see how a client can consume this web service. Check this post.

Saturday, June 12, 2010

Microsoft is going the jQuery way

With jQuery gaining popularity day by day and Microsoft extending support towards it through its Visual Studio IDE, it looks like the future in ASP.NET is going to rely heavily on jQuery. Before I move forward with the integration part which is the actual topic of this blog, let me give you an idea on what jQuery is. If you don't know about jQuery yet or have not followed it recently, you must now. Use of jQuery is getting serious not only with .NET environment but any other environment. To me, it looks like jQuery is going to mean much more in the near future; this I can guess from the increasing number of code examples on the web using jQuery just the way you might have noticed the increasing usage of LINQ.

jQuery is a light weight JavaScript library that is about to change the way you write JavaScript. I have seen people getting addicted to jQuery once they come across it, and why not?...so are its virtues! The latest version of jQuery library is just 24 KB and using just this library in your application, you can do miracles. If you visit the jQuery site, the tag-line says "write less, do more".  And that's true. To use jQuery, all you have to do is visit the jQuery site I gave earlier and download the latest version of the library. If you want it only for use on your website, you can pick the production (minified) version, or if you want to explore it further, you may go for the development version. Once the .js file is downloaded, copy the file to your project folder and start using it by including the file in your source just the way you would include any .js file.

Here is a snapshot where I have used jQuery to display an alert on click of an anchor text. Thios i to give you an idea on how you can use jQuery in Visual Studio. I believe you can carry it forward from here.

How about writing some JavaScript that will fade or slide a <div> when user clicks on it? Just a style change of "display:none" is going to disappear the div...but we want to make it a smooth slide out. You are already thinking of a plethora of code with usage of opacity and setTimeouts, right? But then you also have to put some additional checks to make sure the code is compatible with different browsers!...I know I am scaring you, but now that you have the jQuery library with you, look at what you need to write to get all the above done:
$("div").click(function ()
{
      $(this).hide("slide", { direction: "down" }, 1000);
});
Not only this, what about implementing the complete AJAX based callback in just this much of code:
$(document).ready(function()
{
     $.ajax({
          type: "POST",
          url: "pagemethod.aspx/sayHello",
          contentType: "application/json; charset=utf-8",
          data: "{}",
          dataType: "json",
          success: AjaxSucceeded,
          error: AjaxFailed
    });
});

function AjaxSucceeded(result)
{
    alert(result.d);
}

function AjaxFailed(result) 
{
    alert(result.status + ' ' + result.statusText);
}
That's impressive, isn't it? I am not going to focus on jQuery tutorial here. There are plenty of tutorials available on the web you can access. Best place to start with is the jQuery site's tutorial itself. When I post more articles on jQuery adventure in .NET, I will put some code examples. You can already find some jQuery snippets for Visual Studio in Codeplex that you might want to experiment with once you have done with your basics on jQuery.

What is important to observe how Microsoft is incorporating jQuery into .NET developers' world by extending support to jQuery and even making code contributions to it. In 2008, Scott Gutherie already committed a lot for jQuery from Microsoft in his blog. He mentioned that Microsoft will be shipping jQuery with next version so Visual Studio. In fact, when you create a new web site in Visual Studio 2010, you will find the jQuery files in a scripts folder added by default. I still have to experiment more with it in the 2010 version; will let you know.


Besides, jQuery team has developed a version of jQuery library that is documented as per Microsoft XML comment standards because of which jQuery objects and their properties and methods are now also available in Visual Studio intellisense. You can visit the downloads page on jQuery site and download the Visual Studio version. When you include this documented .js file in your code, the intellisense will guide you through jQuery syntax as you can see below in one of my experiment's screenshot:

This should be possible with Visual Studio 2008 since this IDE has good support for JavaScript. However if you don't have the Service Pack 1 of the IDE, you may face some issues. In that case, get the Service Pack and then refer this knowledge base.

It is pretty sure now that the forthcoming ASP.NET AJAX will be built on jQuery or at least will be largely based on it, make it more important for .NET developers to make jQuery a part of their lives.

A little while ago, Microsoft added jQuery templates and data linking which you can read about here. I will get back to this in some other post with a bit of study. But continuing the effort towards jQuery. Microsoft came up with jQuery Globalization plugin just yesterday. The System.Globalization namespace and CultureInfo class in .NET framework gives you enough liberty to globalize or localize your code. You know how easy it is to convert some date or numeric value into a specific format. For example, I can easily convert my date to English or Dutch format in my server side code as:
using System;
using System.Globalization;
using System.Threading;
public class FormatDate
{
   public static void Main()
   {
      DateTime dt = DateTime.Now;        // Sets the CurrentCulture property to U.S. English.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      Console.WriteLine(dt.ToString("d")); // Creates a CultureInfo for German in Germany.
      CultureInfo ci = new CultureInfo("de-DE");
      Console.WriteLine(dt.ToString("d"));
   }
}
This is just a simple example. In fact, the power of globalization in .NET extends to every datatype and conversion, making it so handy to format our data. Unfortunately, it isn't that easy in JavaScript or the client side code to do the same. This Globalization jQuery plugin is here to solve the same problem, at least making it very very simple. By using language tags, it is not only possible to imitate the CultureInfo scenario but extend the same power into your JavaScript Code. You can read about the plugin here. I will post more as I discover more, but the moral of the story remains: jQuery is here to stay and get more and more involved. If you want to stay afloat, gulp it!