Friday, July 22, 2011

Demystifying the Cloud
An introduction to Cloud Computing



Understanding Cloud Computing

If you are wondering what is so special about the ‘Cloud’ in Cloud Computing, here s the explanation. Traditionally, developers and architects used a picture of cloud to illustrate a remote resource connected via the web. Eventually cloud became the logical connector between the local and remote resources on the Internet.
Most of the developers get confused when they encounter the term Cloud Computing. According to them, their Web Services are already hosted on the Cloud and that can be potentially called as Cloud Services. While there is some truth in this argument, it is a not very accurate way of describing Cloud Computing. Let’s look at Cloud Computing through the eyes of a developer.
Think Web Services
Most of the developers are familiar with Web Services. Web Services are based on a few simple concepts. Every Web Service accepts a request and returns a response (even if there is no explicit return value, a HTTP 200 OK return value is considered as a response). They are units of code that can be invoked over the web. Typically, Web Services accept one or more input parameters and invoke processing logic which will result in an output. Web Services are a part of web applications that run on a typical stack that has hardware, a Server OS, application development platform. For a while, think how you can expose every layer that is powering your web application as a Web Service.
Cloud OS
Visualize a scenario where the hardware and the Operating System (OS) are exposed as a Web Service over the public Internet. Based on the principles of Web Services, we could send a request to this service along with a few parameters.Since the OS is expected to act as an interface to the CPU and the devices, we can potentially invoke a service that accepts a ‘job’ that will be processed by the OS and the underlying hardware. Technically, this Web Service has just turned the OS + H/W combination into a ‘Service’. We can start consuming this service by
submitting CPU intensive tasks to this new breed of Web Service. What do you call an OS that is exposed on the web as a service? May be a Cloud OS? We will answer this in the coming sections.
Cloud FX
Developers always develop and deploy their applications on the application development platforms. Some of the most popular application development platforms are .NET and Java. In the last scenario, we have seen how the OS + H/W combination is offered as a service. Now, imagine a scenario where the application development platform is offered to you as a service. Through this, you will be able to develop and test your applications on a low end, inexpensive notebook PC but will able to ‘submit’ my code to run on the most powerful hardware infrastructure. It is the same programming language, SDK and the runtime that runs on your
development environment. If the hardware, OS, the language runtime and the SDK are offered to you as a service, what would you call this? A Cloud Platform or may be Cloud FX? We will address this in the next section.
Cloud Application
Today, most of the traditional desktop applications like word processors and spreadsheet packages are available over the web. These new breed of applications just need a browser and offer high fidelity with the desktop software. This fundamentally changes the way software is deployed and licensed. You need not double click setup.exe to install an Office suite on your desktop. Just subscribe to the applications and the features that you need and only pay for what you use. This is almost equivalent to exposing the application as a service.These applications
may be called as Cloud Applications. We will take a relook at this later.
Welcome to the World of Services
Infrastructure as a Service
In the previous section we discussed the Cloud OS. All that the Cloud OS offers is the infrastructure services. You may choose to use REST API to manage this OS or use SSH or Remote Desktop console. Technically, when you are able to delegate a program to execute on a remote OS running on the Web, you are leveraging Infrastructure as a Service (IaaS). This is different from classic web hosting. Web hosting only hosts web pages and cannot execute code that needs low level access to the OS API. Web hosting cannot dynamically scale on demand. IaaS enables you to run your computing task on virtually unlimited number of machines. Remember that through IaaS, you have just moved a server running in your backyard into the
Cloud. You pretty much own the managing, patching, securing and the health of the remote servers. Amazon EC2 is an example of commercial IaaS offering.
Platform as a Service
Platform as a Service or PaaS goes one level above the Cloud OS. Through this, developers can leverage a scalable platform to run their applications. The advantage of PaaS is that the developers need not worry about installing, maintaining, securing and patching the server. The PaaS provider takes the responsibility of the infrastructure and exposes the platform alone as a service. Through this, the developers can achieve higher level of scalability, reliability and
availability of their applications. Microsoft Azure and Google App Engine are examples of PaaS.
Software as a Service
Software as a Service (SaaS) is a silent revolution in the world of traditional software products. With the availability of Intel Atom based Netbooks and abundant bandwidth, most of the applications are moving to the Cloud to be offered as services. Consumers can now use inexpensive devices that are capable of connecting to the web to get their work done. This reduces the upfront investment in software and brings the Pay-as-you-go model. Google Apps,
Salesforce.com and Microsoft Online Services are examples of SaaS.

Saturday, July 16, 2011

Calling Cross Domain WCF service using Jquery/Javascript


This article is about to call the cross domain WCF service from you page i.e Calling WCF service hosted on one domain and calling the service form jquery/javascript of page which is hosted on some other domain.
But before we start its better to get understand about the format of the data get exchange from one server to other server.

JSONP
Ajax allows to get data in the background without interfering with the display. Ajax call done by using XMLHttpRequest object, which is allow the client side javascript code to make HTTP connections.

But Ajax call does not allow to get data from cross-domain because of restrictions imposed by the browser. Security error get issued when requesting data from a other domain. one way to avoid security errors is to control remote server where data resides and every request goes to the same domain, that rise question what's the fun if data come form own server only? What to do if data require to get form the other server?

There is one way to come out form this limitation is to insert a dynamic script element in the Web page, one whose source is pointing to the service URL in the other domain and gets the data in the script itself. When the script loads, it executes. It works because the same-origin policy doesn't prevent dynamic script insertions and treats the scripts as if they were loaded from the domain that provided the Web page. But if this script tries to load a document from yet another domain, it will fail. Fortunately, you can improve this technique by adding JavaScript Object Notation (JSON) to the mix.

JSONP or "JSON with padding" is a complement to the base JSON data format, a pattern of usage that allows a page to request data from a server in a different domain. As a solution to this problem, JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.

Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML script tag element. Taking advantage of the open policy for script tag elements, some pages use them to retrieve Javascript code that operates on dynamically-generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON, but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter, not parsed by a JSON parser.

Calling Cross Domain WCF service
Now in following discuss I am going to show you how easily you can call the WCF service hosted on the other domain from the page hosted on the other domain.

Following is list of article you should look first before moving further

Create, Host(Self Hosting, IIS hosting) and Consume WCF servcie
Steps to Call WCF Service using jQuery

To start first create new solution and Add new Project which is WCF service and follow below steps

Step 1
In new release of .net 4.0 the WCF developer team added support for JSONP. There is a new property added which enable to call WCF service from other domain by setting its true.
CrossDomainScriptAccessEnabled - Gets or sets a value that determines if cross domain script access is enabled.

Change your WCF servcie config file as below
As you can see in above config code I have set crossdomainscriptaccessenabled to true and aspnetcompatibilityenabled is to true so that the WCF service works as a normal ASMX service and supports all existing ASP.NET features.

Step 2

SVC file of the service should be like as below
<%@ ServiceHost Language="C#" Debug="true"
Service="WcfService1.Service1"
CodeBehind="Service1.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>
Don't forget to add Factory attribute because it cause error if you remove it. Following are the reason to add Factory attribute
1. Service host factory is the mechanism by which we can create the instances of service host dynamically as the request comes in.

2. This is useful when we need to implement the event handlers for opening and closing the service.

3. WCF provides ServiceFactory class for this purpose.

Step 3

CS file for the WCF file is
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
namespace WcfService1
{
[DataContract]
public class Customer
{
[DataMember]
public string Name;
[DataMember]
public string Address;
}
[ServiceContract(Namespace = "JsonpAjaxService")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Customer GetCustomer()
{
return new Customer() { Name = "Pranay", Address = "1 Ahmedabad" };
}
}
}
As you can see in the above code I have created Service class which is service contract which servs data and Customer class is DataContract which get served as respose.
In the service class GetCustomer method service data in Json format.

Once the WCF service created to move further Add new project >> Asp.Net service. So that both the WCF service and website runs on tow different like both hosted on different domain.

There is two solution to call the Cross Domain WCF service.

Solution 1 : Call WCF service by using JQuery

Jquery already have support to handle the jsonp. Jquery library provided function ajax and getJson which can allow to call the WCF service which send jsonp data in response.

CallService - Generic function is used to call the WCF servcie, which get called by other javascript function to get and display data
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
var method;
//Generic function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function (msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
ServiceFailed - is get called when call to service fail.
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
ServiceSucceeded - is get called when the service successfully return response. As you can see in the function I am checking DataType is jsonp which is just to demonstrate that service is returning jsonp data.
function ServiceSucceeded(result) {
if (DataType == "jsonp") {
resultObject = result.GetEmployeeResult;
var string = result.Name + " \n " + result.Address ;
alert(string);
}
}
GetEmployee - is function that get called to request data from WCF service hosted on other domain. As you can see in code DataType value is get set to jsonp.
function GetEmployee() {
var uesrid = "1";
Type = "GET";
Url = "http://localhost:52136/Service1.svc/GetCustomer";
DataType = "jsonp"; ProcessData = false;
method = "GetCustomer";
CallService();
}
$(document).ready(
function () {
GetEmployee();
}
);
Solution 2 : Call WCF Service by Javascript

To call the service using javascript make use of ScriptManager
in above code I set the servicereferance to the WCF service hosted on other domain.
makeCall - is function that get called to request data from WCF service hosted on other domain.
function makeCall() {
var proxy = new JsonpAjaxService.Service1();
proxy.set_enableJsonp(true);
proxy.GetCustomer(onSuccess, onFail, null);
}
onSuccess - is called when the result from the service call is received and display data.
function onSuccess(result) {
alert( result.Name + " " +result.Address);
}
onFail - is called if the service call fails
function onFail(){
alert("Error");
}
Summary
So after the addition to the special property by the WCF team its quite easy to call cross domain WCF service.