Friday, January 29, 2010

Windows Communication Foundation

In this posting, let us share our experience of working with WCF (Windows Communication Foundation), an API that got introduced with .Net Framework 3.0. Earlier we used to work with various features like
  • Web Services 
  • .Net Remoting
  • Distributed Transactions and
  • Message Queues.

WCF, designed based upon SOA (Service Oriented Architecture) supporting distributed computing, address the above features as a single entity.

The major advantage of WCF is, it supports synchronous, asynchronous and REST style communications utilizing various protocols like http, netnamedpipebinding etc. We used netnamedpipebinding protocol for on-machine communication where the end point will be defined based on protocol type.

Various steps to create a WCF Service are:

Step 1: Create Interface Class and define the class with Service Contract attribute and methods with Operation Contract attribute.

namespace CalculatorService
{
    [ServiceContract(Namespace = "http://CalculatorService", SessionMode = SessionMode.Required)]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);
        [OperationContract]
        double Subtract(double n1, double n2);
        [OperationContract]
        double Multiply(double n1, double n2);
        [OperationContract]
        double Divide(double n1, double n2);
    }
}


Step 2: Create Service Class that implements the interface defined with Service Contract attribute and define the class with Service Behavior attribute. The Service Behavior attribute have two different parameters such as Instance Context mode and Concurrency mode. In Instance Context mode we have to specify the Service instance is single ton or it will be created for each call or each session. In Concurrency mode we have to specify whether it is single threaded or multi threaded.

namespace CalculatorService
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class CalculatorService : ICalculator
    {
     
        public double Add(double n1, double n2)
        {
            return n1 + n2;
        }
        public double Subtract(double n1, double n2)
        {
            return n1 - n2;
        }
        public double Multiply(double n1, double n2)
        {
            return n1 * n2;
        }
        public double Divide(double n1, double n2)
        {
            return n1 / n2;
        }
    }
}


Step 3: Host the Service as Console based application using the ServiceHost.

internal static ServiceHost myServiceHost = null;

internal static void StartService()
{
    try
    {
        myServiceHost = new ServiceHost(typeof(CalculatorService.CalculatorService));
        myServiceHost.Open();
    }
    catch (Exception ex)
    {
    }
}

internal static void StopService()
{
    try
    {
        if (myServiceHost.State != CommunicationState.Closed)
            myServiceHost.Close();
    }
    catch (Exception ex)
    {
    }
}



Step 4: Define the configuration in the host environment with protocol name and endpoint address.

  <system.serviceModel>
    <services>
      <service name="CalculatorService.CalculatorService" behaviorConfiguration="metadataSupport">
        <host>
          <baseAddresses>
           <add baseAddress="net.pipe://localhost/CalculatorService" />
          </baseAddresses>
        </host>
        <endpoint address="" binding="netNamedPipeBinding" contract="CalculatorService.ICalculator" />
        <endpoint address="mex" binding="mexNamedPipeBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataSupport">
          <serviceMetadata />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>


Step 5: This step helps in generating the proxy object. Before generating the proxy, first run the service using command prompt. The following command will generate the service proxy object and configuration file.

Svcutil net.pipe://localhost/CalculatorService  /config:App.Config

The following will be the output

C:\Documents and Settings\WCFDeveloper >svcutil net.pipe://localhost/CalculatorService /config:App.Config
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.648]
Copyright (c) Microsoft Corporation.  All rights reserved.

Attempting to download metadata from 'net.pipe://localhost/CalculatorService ' using
WS-Metadata Exchange. This URL does not support DISCO.
Generating files...
C:\Documents and Settings\WCFDeveloper \CalculatorService.cs
C:\Documents and Settings\WCFDeveloper \App.Config

Client will connect to a service using a Proxy Object, which is connected to the specified endpoint of the service. Both the file need to be added in the client project.

Step 6: Calling the Service from client through the service proxy object.

Here CalculatorClient is the generated service proxy object.

CalculatorClient client= new CalculatorClient();;

private void uxAdd_Click(object sender, EventArgs e)
{
    Double num1 = Convert.ToDouble(uxNumber1.Text.Trim());
    Double num2 = Convert.ToDouble(uxNumber2.Text.Trim());
    uxResult.Text = client.Add(num1, num2).ToString();
}

            Now both the client and service are ready for deployment.

http://msdn.microsoft.com/en-us/library/ms751519.aspx          

Thursday, January 21, 2010

SQL Azure

My first step with SQL Azure:-

Though I am an active one way communicator (i.e., only posting queries) in Azure’s forum, I am here to share my experience of kick starting with the SQL Azure. Before going hands on with MS Azure, my mind got into nostalgic mood by rushing through the user friendly services offered by MS. After my successful interaction with MS Azure, I whole heartedly appreciate Microsoft for offering such a user friendly experience with programming interface etc, which make a lot of difference with various other cloud service providers.


Getting an Account:-

To access SQL Azure you might want to get an invitation code from Microsoft

https://connect.microsoft.com/site681

Once you request an ID you will receive an E-mail with ID in couple of days and then you are ready to use SQL Azure.

Creating First Data Base:-

Browse to the following page where you will see the Server Administration of SQL Azure

https://sql.azure.com/ProjectViewer.aspx

http://csslab.s3.amazonaws.com/csslabs/Siva/Apps/Dash+Board.bmp

http://csslab.s3.amazonaws.com/csslabs/Siva/Apps/List+Of+Data+Base.bmp


In the above image (List Of Data Base.bmp) there is a tab called Firewall Settings where you need to configure the firewall settings to all your system to access it.

How to Create new Data Base?

Make sure you will be able to create data bases only through web portal; management console will not help you to do that.

Firewall settings:-

Most important step is your Local Network port 1433 has to be opened to talk with the Data base which is created through Application or SQL Server 2008 Management console.

SQL 2008 Management Console:-

You need SQL Server 2008 Management Console to do all administrative activities.

   1. Enter your credentials as like shown in below
http://csslab.s3.amazonaws.com/csslabs/Siva/Apps/SQL+Authendication.bmp

   2. Click Options
http://csslab.s3.amazonaws.com/csslabs/Siva/Apps/DB+Selection.bmp

   3. In the Connection Properties tab you need to enter the data base that you want to connect against the filed “Connect to Database”

   4. Once you hit Connect button then you are ready to use and perform all operations.

Sample ASP.Net application is available in the following link for your reference.

http://csslab.s3.amazonaws.com/csslabs/Siva/Apps/SQLServerApp.rar

Best Practice:-

I always recommend you not to send parameters as part of query instead use “SqlParameterCollection” to avoid injection. Since most of the time you are on Internet and probability of hacking is high.

http://msdn.microsoft.com/en-us/library/ms998271.aspx

RSA-SHA1 Signature

After enabling the users to explore their S3 accounts in AWS using
CloudBuddy, our development team got into exploring Cloud Front Private
Content feature which will enable the users to share their content(s) in
secure manner.

To know more about Cloud Front Private Content feature:
http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/index.html?PrivateContent.html

Since Amazon provides the private key in PEM file format, our technology
research associates got into identifying ways to generate an URL with
RSA-SHA1 private key signing. They are unable to come out with a sequence
of steps which will facilitate in generating the private key using C#.

After a couple of days, our Open Source Specialist highlighted a solution
in Linux based system using SSL feature. The next challenges is to convert
that code into windows compatible. After a indepth understanding of logic
involved in generation private keys, we provide below our four step
methodology of builiding it using Open SSL in C++ and some wrapper for C#.

Step 1: Converting PEM as XML

As C# method takes the private signature key as a XML file we had converted
PEM file into XML using the C# code provided in the following link
http://csslab.s3.amazonaws.com/csslabs/Siva/opensslkey.cs

Step 2: SHA1 Hashing

The hash string has to be computed for the Policy (in CloudBuddy it  can be
any string that need to be encrypted)

      string strPolicy = "{\"Statement\":[{\"Resource\":\"http://*\

      ",\"Condition\":{\"IpAddress\":{\"AWS:SourceIp\":\"0.0.0.0/0
\"},\"DateLessThan\":{\"AWS:EpochTime\":1261153938}}}]}\n"; // String to be
signed
            byte[] buffer = Encoding.ASCII.GetBytes(strPolicy);
            SHA1CryptoServiceProvider cryptoTransformSHA1 = new
SHA1CryptoServiceProvider();
            buffer = cryptoTransformSHA1.ComputeHash(buffer);

Step 3 : Signing

Generated SHA1 Hash has to be signed using RSA algorithm with the Private
Key which is provided by Amazon. As we have already converted the PEM file
into an XML content it is a easy task to sign the policy hash string with
Private Key using the following code

            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            XmlDocument xmlPrivateKey = new XmlDocument();
            xmlPrivateKey.Load(@"D:\PEM.xml"); // PEM.xml has been
generated out from Step 1
            RSA.FromXmlString(xmlPrivateKey.InnerXml);
            RSAPKCS1SignatureFormatter RSAFormatter = new
RSAPKCS1SignatureFormatter(RSA);
            RSAFormatter.SetHashAlgorithm("SHA1");
            byte[] SignedHash = RSAFormatter.CreateSignature (buffer) ;

Now you have signed policy so you are all set to use it right away? NO...
there is one more step ahead to get the result what is that?

Step 4: Encoding

Signed hash string has to be encoded as form 64, which can be achieved by
following code:

      string strSignedPolicy = System.Convert.ToBase64String(SignedHash );

The above generated code (strSignedPolicy) need to be appended with the
generated URL which helps in private sharing of contents.

Example:-
http://d2qgjra4ybtnjf.cloudfront.net/Videos/20051210-w50s.flv?Expires=1274534865&Signature=cnJh3q5dgAkMYYcjCItXn6u49Z56A5Lc1Ti8uVZBRQn3NDRlxorlrhzyqvzid~JCOqGhCTQMDWOBzM5XtS0jrF2VD2ljETaKH1FdOKfVoJ0c51fIpyRxio67yloyq4E7lkhVqIP0DxdVnyUEATU9E6NEElKch2UABJ4ys3jItjU_&Key-Pair-Id=APKAJW3NCIJJGAVSTATQ

Out of which query string Signature has been generated using above
mechanism.

The Spinneret Framework

Before briefing about the framework, we would like to share our thought process which was the inspiration to develop this framework. Every one of us wants a better approach to develop our GUIs and to integrate the presentation layer with the other layers. Coding the business layer, service layer and persistence layer is actually the up-hill task but we have never felt it as complex, as it is pure java code and also testing it is easy.

But when it comes to a presentation layer and bringing the GUI in place, we identified several difficulties like

•    Bringing data at runtime to front end
•    Confusion over scope of objects
•    Handling multiple form submits
•    Rich User Interface
•    Compatibility with multiple browsers etc


This is what urged us to come up with a dynamic presentation framework, thus Spinneret evolved.

When we were thinking about this, we came to know about GWT, an open source AJAX based web application framework from Google.

It provides a set of core JAVA APIs and Widgets which allows you to write your client-side AJAX application in Java and then compile the Java source code to a highly optimized JavaScript that runs successfully in multiple browsers. So the developer need not be an expert in browser quirks, XMLHttpRequest, and JavaScript. Also GWT has some additional features like JavaScript Native Interface (JSNI), JavaScript Overlay Types, Deferred Binding, Code splitting and so on.

Spinneret fits into the presentation tier of the enterprise layer and takes care of rendering the UI based on the configuration. Spinneret is integrated with Struts 1.1, which takes care of the listener for the GUI objects of the Spinneret framework from the view. Every Spinneret action is submitted to the ActionServlet of struts and is routed via struts.

Spinneret has in-built, programmable templates, which is based on the GWT layouts available. These templates are extendable and user can even write their own template.