Representational State Transfer (REST)

by Ajit Singh 1. July 2011 17:08

I am starting to post the series of articles on REST concept, RESTfull web services and WCF support to write the RESTfull services.

Below are the lists of Topics will covered in the series of my posts:

1.    Overview of REST

2.    RESTfull Web Services

3.    WCF support to write the RESTfull web Services

4.    Step-by-step to create the RESTfull web Service using .NET 4.0 WCF

5.    Comparison between SOAP and RESTfull web services approach.  

 

Below is the first topic about REST concept.

 

Representational State Transfer (REST):

 

Representational State Transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web.

 

REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource.

At any particular time, a client can either be in transition between application states or "at rest." A client in a rest state is able to interact with its user, but creates no load and consumes no per-client storage on the servers or on the network.

The client begins sending requests when it is ready to make the transition to a new state. While one or more requests are outstanding, the client is considered to be in transition. The representation of each application state contains links that may be used next time the client chooses to initiate a new state transition.

REST was initially described in the context of HTTP, but is not limited to that protocol. RESTful architectures can be based on other Application Layer protocols if they already provide a rich and uniform vocabulary for applications based on the transfer of meaningful representational state. RESTful applications maximize the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimize the addition of new application-specific features on top of it.

Fundamental Characteristics / Constraints of REST:

 

The REST architectural style describes the following six constraints applied to the architecture, while leaving the implementation of the individual components free to design:

Client–server

Clients are separated from servers by a uniform interface. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface is not altered.

 

Stateless

The client–server communication is further constrained by no client context being stored on the server between requests. Each request from any client contains all of the information necessary to service the request, and any session state is held in the client. The server can be stateful; this constraint merely requires that server-side state be addressable by URL as a resource. This not only makes servers more visible for monitoring, but also makes them more reliable in the face of partial network failures as well as further enhancing their scalability.

Cacheable

As on the World Wide Web, clients are able to cache responses. Responses must therefore, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or inappropriate data in response to further requests. Well-managed caching partially or completely eliminates some client–server interactions, further improving scalability and performance.

Layered system

A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load balancing and by providing shared caches. They may also enforce security policies.

Code on demand (optional)

Servers are able to temporarily extend or customize the functionality of a client by transferring logic to it that it can execute. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript.

Uniform interface

A uniform interface (like HTTP GET, POST, DELETE, PUT) is to be used to access a resource, simplifies and decouples the architecture, which enables each part to evolve independently. The four guiding principles of this interface are detailed below.

 

Key goals

Key goals of REST include:

  • Scalability of component interactions
  • Generality of interfaces
  • Independent deployment of components
  • Intermediary components to reduce latency, enforce security and encapsulate legacy systems

RESTful web services:

A RESTful web service (also called a RESTful web API) is a simple web service implemented using HTTP and the principles of REST. It is a collection of resources, with three defined aspects:

  • the base URI for the web service, such as http://example.com/resources/
  • the Internet media type of the data supported by the web service. This is often JSON, XML or YAML but can be any other valid Internet media type.
  • the set of operations supported by the web service using HTTP methods (e.g., POST, GET, PUT or DELETE).

The following table shows how the HTTP methods are typically used to implement a web service.

RESTful Web Service HTTP methods

Resource

GET

PUT

POST

DELETE

Collection URI, such ashttp://example.com/resources/

List the URIs and perhaps other details of the collection's members.

Replace the entire collection with another collection.

Create a new entry in the collection. The new entry's URL is assigned automatically and is usually returned by the operation.

Delete the entire collection.

Element URI, such ashttp://example.com/resources/ef7d-xj36p

Retrieve a representation of the addressed member of the collection, expressed in an appropriate Internet media type.

Update the addressed member of the collection.

Treat the addressed member as a collection in its own right and create a new entry in it.

Delete the addressed member of the collection.

The PUT and DELETE methods are idempotent methods. The GET method is a safe method, meaning that calling it produces no side-effects (this also implies idempotence).

Unlike SOAP-based web services, there is no "official" standard for RESTful web services. This is because REST is an architecture, unlike SOAP, which is a protocol. Even though REST is not a standard, a RESTful implementation such as the Web can use standards like HTTP, URI, XML, etc.

 

Tags:

Transaction in WCF

by Administrator 2. June 2011 11:44

 

To enable WCF transaction is a 6 step procedure. So let’s create two WCF services and let’s try to call them in one transaction.

 

Step 1 :- Create two WCF service

The first step is to create two WCF service projects which will participate in one transaction. In both of these WCF services we will do database transactions and we will try to understand how a WCF transaction unifies them. We have also created a web application with name ‘WCFTransactions’ which will consume both the service in one transaction scope.
 

Step 2:- Apply Attribute interface methods with TransactionFlow 
 

In both the WCF service we will create a method called as ‘InsertData’ which will do insert in to the database. So the first thing is to create the interface class with ‘ServiceContract’ attribute and the method ‘InsertData’ with ‘OperationContract’ attribute. In order to enable transaction in ‘InsertData’ method we need to attribute it with ‘TransactionFlow’ and we have specified that transactions are allowed for this method using ‘TransactionFlowOption.Allowed’ enum.

 

[ServiceContract]

public interface IService1

{

[OperationContract]

[TransactionFlow(TransactionFlowOption.Allowed)]

void InsertData();

}

 

Step 3:- Attribute the implementation with ‘TransactionScopeRequired’ 
 

The 3rd step is to attribute the implementation of the WCF services with ‘TransactionScopeRequired’ as true. Below is the code snippet which has a simple database inserting function i.e. ‘InsertData’ which is attributed by ‘TransactionScopeRequired’ attribute.
 

[OperationBehavior(TransactionScopeRequired = true)]

public void InsertData()

{

SqlConnection objConnection = new SqlConnection(strConnection);

objConnection.Open();

SqlCommand objCommand = new SqlCommand("insert into Customer(CustomerName,CustomerCode) values('sss','sss')",objConnection);

objCommand.ExecuteNonQuery();

objConnection.Close();

}

 

Step 4:- Enable transaction flow using WCF service config file
 

We also need to enable transactions for ‘wsHttpBinding’ by setting the ‘transactionFlow’ attribute to true.
 

<bindings>

<wsHttpBinding>

<binding name="TransactionalBind" transactionFlow="true"/>

</wsHttpBinding>

</bindings>

 

The transaction enabled binding we need to attach with the end point through which our WCF service is exposed.
 

<endpoint address="" binding="wsHttpBinding" bindingConfiguration="TransactionalBind" contract="WcfService1.IService1">

 

Step 5:- Call both service methods in one transaction
 

Now that we are done with our server side transaction enablement, it’s time to call the above 2 services in 1 transaction. We need to use the ‘TransactionScope’ object to group the above 2 WCF services in one transaction. To commit all the WCF transactions we call the ‘Complete’ method of the ‘Transactionscope’ object. To rollback we need to call the ‘Dispose’ method.
Below is the complete code snippet in which we have grouped both the WCF transactions in one scope as shown below.
 

using (TransactionScope ObjTran = new TransactionScope(TransactionScopeOption.RequiresNew))

{

try

{

ServiceReference1.Service1Client objser1 = new ServiceReference1.Service1Client();

objser1.InsertData();

ServiceReference2.Service1Client objser2 = new ServiceReference2.Service1Client();

objser2.InsertData();

ObjTran.Complete();

}

catch (Exception ex)

{

ObjTran.Dispose();

}

}

 

Now test if the transactions really work. We are calling two services both of these services are doing an insert. After the first WCF service call we are forcing an exception. In other words the data insert of the first WCF service should revert back. If you check the database records you will see no records are inserted by the WCF service.

 

Tags:

WCF

Abstract Vs. Interfaces

by Administrator 11. May 2011 11:27

 

Q Where we use abstract class and where we use interfaces?

Ans.  Abstract classes are used if you need common functionality for releted class and interface are used if you need common functionality for unreleated classes.

Abstract Vs. Interfaces

Feature

Interface

Abstract class

Multiple inheritance

A class may inherit several interfaces.

A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties

Core VS Peripheral

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity

If various implementations only share method signatures then it is better to

Tags:

OOPS

Deploying a WCF Service with IIS

by Administrator 28. April 2011 17:59

To deploy the WCF Services with IIS, you need to publish the WCF Project after publish you will get the .svc file the you need to follow the below steps:

1.      Copy .svc file into a web site folder on the server or if u create a virtual directory for WCF then you have to place .scv file their,

2.      Copy .dll file into a root  \bin folder in the web site,

3.      Copy the <system.serviceModel> section from publish Web.Config file and put it into root  web.config file . It has to have the endpoint configuration.

4.      "%windir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe" -r -y

 

Tags:

WCF

Extension Method

by Administrator 26. April 2011 12:19

Extension method is new to C#.Its allow you to add new method to the existing class.

Extension method allows you to add new method to the existing class without modifying the code, recompiling or modifying the original code. Extension method are special kind of static method but they are called using instance method syntax. Their first parameter specify which type the method operate on, and the parameter is precede by  “this” modifier. Extension method are only in scope when you explicitly import the namespace into your source code with “using” directive.

For Example in string object there is no method call “ReverseData()”  function .But if you need to extend the string …. 

C# Code

 

namespace ExtMethods
{
    public static class ExtClass
    {
        public static string ReverseData(this String str)
        {
            char[] charArray = new char[str.Length];
     int len = str.Length - 1;
         for (int i = 0; i <= len; i++)
     {
        charArray[i] = str[len-i];
     }
     return new string(charArray);
        }
    }
}

How to call 

string s = "Hello Calling";

string strGetReverseData = s.ReverseData();

Tags:

C#

Call Controller using Jquery

by Administrator 26. April 2011 11:50

To Call the MVC Controller from the jquery Ajax. you need to call either $.get or $post function of jquey ajax. In controller you can write your business logic. here i am returning name of the usercontrol and object.

Script

<script type="text/javascript">

function getControl()

{ var URL = "/AddRows/" + (new Date()).getTime();

$.get(URL, function(data)

{ $("#DivGrid").html(data); });

} </script>

Controller
public ActionResult AddRows(string id)
        {
            try
            {
                    
                 return PartialView("GRID", ObjShip); 
            }
            catch
            {
                return View();
            }
        }

NOLOCK In Sql Server

by Administrator 7. April 2011 21:56

Using the NOLOCK query optimiser hint is generally considered good practice in order to improve
concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are
taken when data is read. The result is a Dirty Read, which means that another process could be
updating the data at the exact time you are reading it. There are no guarantees that your query will
retrieve the most recent data. The advantage to performance is that your reading of data will not block
updates from taking place, and updates will not block your reading of data. SELECT statements take
Shared (Read) locks. This means that multiple SELECT statements are allowed simultaneous access, but
other processes are blocked from modifying the data. The updates will queue until all the reads have
completed, and reads requested after the update will wait for the updates to complete. The result to
your system is delay(blocking).

Tags:

Sql Server

About the author

Something about the author

Month List

Page List