Showing posts with label General Programming. Show all posts
Showing posts with label General Programming. Show all posts

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,

Tuesday, March 24, 2009

TripleDES encrypt and decrypt interoperability in Java and .NET

Recently while working to integrate the Cross Site Authentication framework, I developed in my current project, with a Hosted Service used by the client; I ran into an unexpected issue whereby the assertion generated by our system could not be decrypted by the hosted service. This was inspite of us using a proper standard encryption algorithm like TripleDES.

It took me some effort to actually dig deeper into the system when I finally understood the root cause of the issue. This blog article is to explain the issue and to document the solution so that it can act as a ready reference for me and for others too.

TripleDES is a block cipher, which means a block of data (64 bits) gets encrypted at a time. The data that we need to encrypt may not always be an exact multiple of 64 bits, hence we need data padding. Moreover to make the algorithm more secure we can use the encrypted out of the first block of 64 bits while encrypting the second block of 64 bit and so on. This is called as feedback mode.

The list of various feedback modes and padding options availabe for TripleDES and other similar block ciphers is available in the Cipher section of JCE documentation.

In my implementation I was using ECB feedback mode (which means no feedback) and PKCS5Padding.

The cause of the issue seems to be the way .NET implements TripleDES ECB mode. As per the RFC ECB mode should not use any feedback, however it seems that the .NET implementation for ECB mode does use the Initialization Vector for decryption. Moreover if it is not set, it uses a random value for IV and starts decryption L. This will definitely cause the decryption to fail.

So the solution is to set the Initialization Vector to 00 00 00 00 00 00 00 00 (64 bits 0). This has the effect that now when the IV is XORed with the first 64 bits of the raw data to be decrypted, it does not cause any data change, hence eliminating feedback and resulting in proper decryption.

Thursday, March 19, 2009

HTML to RSS conversion

Some time ago I was looking to publish a RSS feed for the blog like updates I did to my site http://hemenkapadia.somme.com. While the site itself is simple HTML (actually asp) there was no direct way to convert it into a RSS feed.

The solution to this issue is to use various "HTML to RSS" utilities that are available online. A simple google search for the term yielded multiple sites that serve the purpose, so now the issue was to find out which one was the best.

Initially I tried RSSxl (and it is still implemented on my site) as i found it to serve my purpose the best. It actually had the feature of allowing good regular expression parsing to help generate a RSS feed with all elements I needed with proper syntax. But it seems the site exceeded its bandwidth and is running into issues.

Feedity is hardly anything impressive (dont even bother using it).

The best one I found was Feed43. It has the most flexible and powerful regular expression parser that helped me generate the RSS feed exactly as I wanted to. It is even better than RSSxl.

I have stopped updating http://hemenkapadia.somee.com ever since I purchased my own domain http://www.getbhavcopy.com and hosted it on Webs.com.

However I noticed that the RSS feed of the stock Blog App provided by Webs does not honor HTML tags in the CDATA section in the 'description' tag of the field. This creates an RSS feed where the main content does not contain any HTML tags to aid formatting and the feed content looks like a huge paragraph of gibberish text (basically not very presentable) (View the original feed)

This brought me to Feed43. It took me about 10 minutes to figure out the set of regular expressions and I was in business. The RSS feed for the same Blog App generated by Fee43 contains all the same HTML tags as in the original post and that makes that feed extremely presentable. (View the same feed processed by Feed43)

The best part is that Feed43 is a Free service, which will suffice most people. They also have advanced paid service in case of heavy usage.