Labels

Wednesday, August 6, 2014

What, Why REST?

Hi,

 

·         Why REST?

·         What is REST?

·         WCF and REST

 

Why REST?

 

Two reasons – One is soft and the other is hard( likely imposed).

 

1.       First, REST offers some significant features and benefits over RPC technologies in many cases.

2.    Second, Microsoft is moving many of its own implementations away from RPC technologies (such as SOAP) and goings toward REST. This means that even if you are not convinced or motivated to use REST to build your own systems, you'll need to know how to interact with other MS Frameworks & Technologies as they have already moved to REST,

 

What is REST?

 

REST is an architectural style - Used to build software in which clients (User Agents) can make requests of services (Endpoints).

REST means that each unique URL is a representation of some object (Resource).

 

URL

Verbs

Resource/Object

Other Verbs

"/ "

GET

Retun All Years Subscriptions

 

“/{year}"

GET

A particular year's issues

PUT

"/{year}/{issue}"

GET

A particular issue

PUT

"/{year}/{issue}/{article}"

GET

An article

PUT,POST,DELETE

 

E.g. http://localhost/Issues.svc/  and http://localhost/Issues.svc/2007

 

 

 

To add an article to December 2008, the client would POST an article resource to http://localhost/Issues.svc/2008/December and a new article would be added to that issue.

 

To suuport this -  WCF ServiceContract Definition would look like below.

 

 

[ServiceContract]

public interface IMSDNMagazineService

{

    [OperationContract]

    [WebGet(UriTemplate="/")]

    IssuesCollection GetAllIssues();

 

    [OperationContract]

    [WebGet(UriTemplate = "/{year}")]

    IssuesData GetIssuesByYear(string year);

 

    [OperationContract]

    [WebGet(UriTemplate = "/{year}/{issue}")]

    Articles GetIssue(string year, string issue);

 

    [OperationContract]

    [WebGet(UriTemplate = "/{year}/{issue}/{article}")]

    Article GetArticle(string year, string issue, string article);

 

    [OperationContract]

    [WebInvoke(UriTemplate = "/{year}/{issue}",Method="POST")]

    Article AddArticle(string year, string issue, Article article);

}

 

 

WCF & REST

 

WCF is more geared toward RPC (using SOAP). Till Framework 3.0 WCF had the ability to expose and consume REST services as part of the .NET. However what it lacked was a programming model needed to make using REST with WCF easy.

 

This is been mitigated in Framework 3.5 - Both a Programming Model and those pieces of Infrastructure were added to existing System.ServiceModel.Web assembly.

 

The Programming Model additons were –

 

o    WebGetAttribute and WebInvokeAttribute, and

o    URI Template Mechanism - Enables to declare the URI and Verb to which each method. (As show above).

 

The Infrastructure additons were –

 

o    Behavior Infrastructure

o    Binding (WebHttpBinding) and

o    Behavior (WebHttp­Behavior) - Provide the correct networking stack for using REST

 

o    Hosting Infrastructure additons were –

o    Custom Service­Host (WebServiceHost) and

o    ServiceHostFactory (WebServiceHostFactory)

 

WebGetAttribute and WebInvokeAttribute

 

WCF builds connected systems, is by routing messages to methods, defined in your service class.

 

In Non-REST WCF:

 

o    By default, WCF does the routing (also known as Dispatching) based on the concept of action.

o    This system of routing is tightly coupled to SOAP since the SOAP specification's Action header is used by default.

o    The value of Action is based on (method name + the namespace of your service) Or via a custom value (set via the OperationContractAttribute.Action property).

o    For this dispatching to work, an action needs to be present in every message that WCF receives on your behalf.

o    Each unique action is mapped to a particular Action method.

 

In RESTful WCF:

 

o    In this case, the default dispatcher is replaced by one that routes based not on Action, but instead based on the (URI  + HTTP verb being used) in the  request.

o    This routing (done by a class called WebHttpDispatchOperationSelector) enables you to easily implement a RESTful endpoint.

o    This dispatcher is configured on each endpoint by a behavior named WebHttpBehavior, which must be added to each endpoint. (TBD)

o    The key to making this work is for the WebHttpDispatch­OperationSelector to know How To Map Different Uris And Verbs To Your Methods.

o    For this, the WebGetAttribute and WebInvokeAttribute must be added to the methods on your WCF ServiceContract type.

 

WebGetAttribute tells the dispatcher that the method should respond to HTTP GET requests.

WebInvokeAttribute is mapped to HTTP POST by defaul.

Also the WebInvokeAttribute.Method property can be set to support any of the other HTTP verbs (PUT and DELETE being the two most common).

 

UriTemplate and UriTemplateTable

 

In Non-RESt, By default, the URI is determined by the name of the method (added onto the base URI of the endpoint).

In RESTful, what you want to expose as URIs are nouns.

For this reason, WCF + REST,  requires customization of URIs for each method  - This is achvieved by using templates.

Such Templates are set via the UriTemplate property on WebGetAttribute or WebInvokeAttribute.

 

UriTemplate - Enables customization of the URI for each Method And Verb combination, by using a special template syntax (as shown above).

 

WebHttpBinding and WebHttpBehavior

 

WebHttpBinding – Used for a RESTful endpoint. Unlike others this is fairly simple.

It contains only two components: the HTTP transport and the Text Message Encoder (set to not expect or use SOAP, just plain XML).

 

WebHttpBehavior - Is the object that causes the “URI + HTTP Verb” dispatcher to be used.

 

Note: Below Code for self-hosting a WCF RESTful endpoint.

 

·         WebHttpBinding and the WebHttpBehavior are almost always used together

·         You have to specify the WebHttpBinding when adding the endpoint to the ServiceHost.

·         Also you have to explicitly add the WebHttpBehavior to the endpoint to make the URI-plus-verb dispatching system work.

 

 

ServiceHost sh =  new ServiceHost(typeof(MSDNMagazineServiceType));

string baseUri = "http://localhost/MagazineService";

ServiceEndpoint se =   sh.AddServiceEndpoint(typeof(IMSDNMagazineService), new WebHttpBinding(), baseUri);

se.Behaviors.Add(new WebHttpBehavior());

sh.Open();

 

 

 

<configuration>

  <system.serviceModel>

    <services>

      <service name="MSDNMagazine.MSDNMagazineServiceType">

        <endpoint

          address="http://localhost/MagazineService"

          binding="webHttpBinding"

          contract="MSDNMagazine.IMSDNMagazineService"

          behaviorConfiguration="webby"/>

      </service>

    </services>

    <behaviors>

      <endpointBehaviors>

        <behavior name="webby">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>

  </system.serviceModel>

</configuration>

 

Note: Use either code or config.

 

 

 

WebServiceHost and WebServiceHostFactory

 

WCF is complex, in terms of configuration. To alleviate this concern with RESTful endpoints,, Microsoft added two new types to the .NET Framework 3.5

 

·         WebServiceHost and

·         WebServiceHostFactory

 

WebServiceHost:

 

·         Is a ServiceHost-derived type, which simplifies self-hosting scenarios of RESTful endpoints.

·         The code to self-host with WebServiceHost looks like this

 

 

string baseUri = "http://localhost/MagazineService";

WebServiceHost sh =   new WebServiceHost(typeof(MSDNMagazineServiceType), new Uri(baseUri));

sh.Open();

 

 

WebServiceHostFactory:

In the managed hosting scenario with WCF, inside IIS, WCF normally requires an .svc file that points to the service type, plus entries in the web.config file to inform WCF about the endpoint (the binding and behaviors among other configuration). To simplify the managed hosting scenario, Microsoft added WebServiceHostFactory.

 

·         Uses an open WCF extensibility point (using a custom ServiceHostFactory type) in the managed hosting scenario.

·         This enables a configuration-free experience for many RESTful services. The .svc file looks like this

 

 

<%@ ServiceHost

                        Factory="System.ServiceModel.Activation.WebServiceHostFactory"  

                        Service="MSDNMagazine.MSDNMagazineServiceType" %>

 

 

 

·         WebServiceHostFactory creates an instance of the WebServiceHost, and since the WebServiceHost will auto-configure the endpoint using WebHttpBinding and WebHttpBehavior. This no need for any configuration for this endpoint in the web.config at all.

 

 

Why Should You Care about REST?

 

Whether you have used proprietary either of the below two, these are the implementations of the client-server style we've had on the Microsoft platform.

·         RPC systems such as DCOM or .NET Remoting, or

·         Interoperable RPC technologies such as SOAP using ASMX(Web Service) or WCF,

 

So why learn or use REST?

 

·         The two main reason are as mentioned above.

 

The following is a list of other advantages (but don't consider this list exhaustive):

 

 

 

Caching

When RESTful endpoints are asked for data using HTTP, the HTTP verb used is GET.

Resources returned in response to a GET request can be cached in many different ways.

 

Conditional GET, which is a way that a client can check with the service if his version of the data is still the current version, is an optional implementation detail a RESTful endpoint can implement that can further improve speed and scalability.

 

Scale-Out

REST encourages each resource to contain all of the states necessary to process a particular request.

RESTful services are much easier to scale out when they fulfill this constraint and can be stateless.

 

Interoperability

Many people advertize SOAP as being the most interoperable way to implement client-server programs.

But some languages and environments still don't have SOAP toolkits.

And some that do have toolkits are based on older standards that can't always communicate with toolkits that implement newer standards.

 

REST only requires an HTTP library to be available for most operations, and it is Certainly More Interoperable Than Any RPC Technology (including SOAP).

 

Simplicity

Here, the simplicity of using REST relates to URIs representing resources and the uniform interface.

 

Using the uniform interface simplifies development by freeing me from having to build an interface, contract, or API for each service I need to build. The interface (how clients will interact with my service) is set by the constraints of the architecture.

 

Lightweight

REST is Lightweight than SOAP because it does not requires lot of xml markup like SOAP.

 

 

This is not an exhaustive list nor should you take it as conclusive evidence that REST is the one and only true technology to use always.

You should be aware of the advantages so you can leverage them when appropriate

 

REST Vs SOAP - Which is the best approach?

 

Software Architects have been involving a never-ending debate about whether SOAP-based or REST-style web services are the right approach.

Yahoo's web services are using REST and Google using SOAP for their web services. Some organizations have web services for both REST and SOAP.

 

REST is Lightweight than SOAP because it does not requires lot of xml markup like SOAP.

I believe that SOAP will be the primary choice for Intranet & Enterprise Level Applications because SOAP and the WS-* specifications addresses many challenges of enterprise level applications such as Reliability, Distributed Transactions, and other WS-* services.

On the other hand, Internet applications will gear towards to REST because of REST’s explicitly Web-based approach and its simplicity.

 

 

RESTful services for WCF 3.5

 

WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.

By adding the WebGet Attribute, we can define a service as REST based service that can be accessible using HTTP GET operation.


The below code shows how to expose a RESTful service

SOAP Based – WCF 3.0

REST Based – WCF 3.5

 

[ServiceContract]
interface IStock
{
[OperationContract]
int GetStock(string StockId);
}

[ServiceContract]
interface IStock
{
[OperationContract]
[WebGet]
int GetStock(string StockId);
}

 

Regards,

Arun Manglick



 

Wednesday, June 11, 2014

Deployment Performance Patterns - Scaling (Up/Out)

There are below deployment patterns

 

1.       Performance Patterns

a.       Application Farms

b.      Web Farms

c.       Load Balancing Cluster

 

Consider the use of Web farms or Load Balancing Clusters, when designing a Scale Out strategy.

 

2.       Reliability Patterns

a.       Fail-Over Cluster

 

3.       Security Patterns

a.       Impersonation/Delegation

b.      Trusted Subsystem

c.       Multiple Trusted Service Identities

 

1). Performance Patterns:

 

A). WebFarm & Affinity:

 

A Web farm is a collection of load-balanced array of servers where each server replicate/run the same application.

A Web farm with local business logic is a common deployment pattern that places all application components—user interface components (ASP.NET pages), user process components (if used), business components, and data access components—on each Web farm servers.

 

A number of technologies can be used to implement the load-balancing mechanism, including

·         Hardware solutions such as those offered by Cisco and Nortel switches and routers, and

·         Software solutions such as Network Load Balancing

 

Requests from clients are distributed to each server in the farm, so that each has approximately the same loading.

Depending on the routing technology used, it may detect failed servers and remove them from the routing list to minimize the impact of a failure.

In simple scenarios, the routing may be on a "round robin" basis where a DNS server hands out the addresses of individual servers in rotation.

 

This pattern provides the highest performance, because all component calls are local, and only the databases are accessed remotely.

 

Figure 3 illustrates a simple Web farm where each server hosts all of the layers of the application except for the data store.

 

In Non-distributed Architecture - Scaling out Web servers in a Web farm

 

 

Affinity and User Sessions

 

Web applications often rely on the maintenance of Session State between requests from the same user.

A Web farm can be configured to route all requests from the same user to the same server – a process known as Affinity – in order to maintain state where this is stored in memory on the Web server.

However, for maximum performance and reliability, you should use a separate session state store (SqlServer/StateServer) with a Web farm, to remove the requirement for affinity.

 

 

B). Application Farms

 

In Distributed Deployment , where the Business & Data layer runs on different physical tiers from the Presentation layer, Application Farm is used to Scale Out the Business & Data layer.

Applications farms are conceptually similar to Web farms, but they are used to load balance requests for business components across multiple application servers.

 

Similar to Web-Farm,  Application-Farm is a also collection of servers where each server replicate/run the same application.

Requests from clients(presentation tier) are distributed to each server in the farm, so that each has approximately the same loading.

 

 

 

C). Clustering - Load Balancing Cluster

 

When we have multiple processors, we should have provision which can spread multiple requests coming to multiple machines.

The solution can come from a number of mechanisms, but they are all grouped under the term "load balancing."

 

Application/Service can be installed onto multiple servers that are configured to share the workload, as shown below.

This type of configuration is a Load-Balanced Cluster.

 

Two Approaches:

 

·         SLB - Software Load Balancer

·         Clustering

 

Software Load Balancer performs the following functions :

 

        Intercepts network-based traffic (such as web traffic) destined for a site.

        Splits the traffic into individual requests and decides which servers receive individual requests.

        Maintains a watch on the available servers, ensuring that they are responding to traffic. If they are not, they are taken out of rotation.

        Provides redundancy by employing more than one unit in a fail-over scenario.

        Offers content-aware distribution, by doing things such as reading URLs, intercepting cookies, and XML parsing.

 

 

Clustering:

 

Clustering offers a solution to the same problems that SLB addresses, namely high availability and scalability, but clustering goes about it differently.

Clustering is a highly involved software protocol (proprietary to each vendor) running on several servers that concentrate on taking and sharing the load.

 

Clustering involves a group of servers that accept traffic and divide tasks amongst themselves.

This involves a fairly tight integration of server software. This is often called load balancing

 

Load-balanced Servers also serve a failover function by redistributing load to the remaining servers when a server in the load-balanced cluster fails.

 

With clustering, there is a fairly tight integration between the servers in the cluster, with software deciding which servers handle which tasks and algorithms determining the work load and which server does which task, etc.

 

 

 

Load balancing Scales The Performance of server-based programs, such as a Web server, by distributing client requests across multiple servers.

Load balancing technologies, commonly referred to as Load Balancers, receive incoming requests and redirect them to a specific host if necessary.

The Load-Balanced Hosts concurrently respond to different client requests, even multiple requests from the same client.

 

For example, a Web browser may obtain the multiple images within a single Web page from different hosts in the cluster.

This distributes the load, speeds up processing, and shortens the response time to clients.

 

 

2). Reliability Patterns

 

Reliability deployment patterns represent proven design solutions to common reliability problems. The most common approach to improving the reliability of your deployment is to use a fail-over cluster to ensure the availability of your application even if a server fails.

 

Fail-Over Cluster

 

A Failover Cluster is a set of servers that are configured so that if one server becomes unavailable, another server automatically takes over for the failed server and continues processing.

 

Failover is a key technology behind clustering to achieve fault tolerance. By choosing another node in the cluster, the process will continue when the original node fails.

Failing over to another node can be coded explicitly or performed automatically by the underlying platform which transparently reroutes communication to another server.

 

 

 

Application/Service can be installed onto multiple servers that are configured to take over for one another when a failure occurs.

The process of one server taking over for a failed server is commonly known as Failover. Each server in the cluster has at least one other server in the cluster identified as its standby server.

 

 

3). Security Patterns

 

Security patterns represent proven design solutions to common security problems.

 

Impersonation and Delegation approach is a good solution when you must flow the context of the original caller to downstream layers or components in your application.
Trusted Subsystem approach is a good solution when you want to handle authentication and authorization in upstream components and access a downstream resource with a single trusted identity.

 

Impersonation/Delegation

In the impersonation/delegation authorization model, resources (such as tables and procedures in SQL Server) and the types of operation (such as read, write, and delete) permitted on such each resource are secured using Windows Access Control Lists (ACLs) or the equivalent security features of the targeted resource.

Users access the resources using their original identity through impersonation, as below.

 

The impersonation/delegation authorization model

 

 

Trusted Subsystem

In the trusted subsystem (or trusted server) model, users are partitioned into application defined, logical roles.

Members of a particular role share the same privileges within the application.

Access to operations is authorized based on the role membership of the caller.

 

With this role-based (or operations-based) approach to security, access to operations (not back-end resources) is authorized based on the role membership of the caller.

Roles, analyzed and defined at application design time, are used as logical containers that group together users who share the same security privileges or capabilities within the application.

The middle tier service uses a fixed identity to access downstream services and resources, as illustrated in Figure 7.

 

 

 

Multiple Trusted Service Identities

In some situations, you may require more than one trusted identity. For example, you may have two groups of users, one who should be authorized to perform read/write operations and the other read-only operations. The use of multiple trusted service identities provides the ability to exert more granular control over resource access and auditing, without having a large impact on scalability.

 

 

 

Reference: MS Patterns & Practices - Web Application Architecture Guide

 

Hope this helps.

 

Regards,

Arun Manglick