a presentation on wcf & rest

27
Presented By: Santhosh Janagam September 2013 Software Services WCF and RESTful WCF

Upload: santhu-rao

Post on 18-Nov-2014

659 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: A presentation on WCF & REST

Presented By: Santhosh Janagam

September 2013

Software Services

WCF and RESTful WCF

Page 2: A presentation on WCF & REST

AGENDA

• Introduction to WCF• WCF Architecture• Web Services Vs WCF• WCF Fundamental• Endpoint• ABC’s of Service• WCF Hosting• Metadata Exchange• Metadata Exchange Endpoint• Instance Management• Transfer Mode• Buffered Vs Streamed Transfer

• Resource-Oriented Architecture• REST• REST Principles• webHttpBinding• WebServiceHost• [WebGet] And [WebInvoke]• UriTemplate• REST and HTTP• SOAP Vs REST

2

Page 3: A presentation on WCF & REST

Introduction to WCF

• Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying

network-distributed services.

3

Page 4: A presentation on WCF & REST

WCF Architecture

4

Page 5: A presentation on WCF & REST

Web Service Vs WCF

Features Web Service WCF

Hosting It can be hosted in IISIt can be hosted in IIS, windows activation service, Self-hosting, Windows service

Programming [WebService] attribute has to be added to the class

[ServiceContraact] attribute has to be added to the class

Model [WebMethod] attribute represents the method exposed to client

[OperationContract] attribute represents the method exposed to client

OperationOne-way, Request- Response are the different operations supported in web service

One-Way, Request-Response, Duplex are different type of operations supported in WCF

XML System.Xml.serialization name space is used for serialization

System.Runtime.Serialization namespace is used for serialization

EncodingXML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom

XML 1.0, MTOM, Binary, Custom

Transports Can be accessed through HTTP, TCP, Custom

Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom

Protocols Security Security, Reliable messaging, Transactions

5

Page 6: A presentation on WCF & REST

WCF Fundamental

• End Point• Bindings and Behaviour• Contracts and Service host• Message and Channel• WCF client and Metadata

6

Page 7: A presentation on WCF & REST

End Point

• WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.

• All the WCF communications are take place through end point. End point consists of three components.– Address– Binding– Contract

7

Page 8: A presentation on WCF & REST

ABC’s of Service

• Address:Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.ghttp://localhost:8090/MyService/SimpleCalculator.svc

• Binding:Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements– Transport– Encoding(optional)– Protocol(optional)

Types of Binding:– BasicHttpBinding, WSHttpBinding, NetNamedPipeBinding etc.

8

Page 9: A presentation on WCF & REST

Contract

Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

Mainly there are four types of contracts available in WCF

– Service Contract Operation Contract

– Data Contract– Message Contract– Fault Contract

[ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1, int num2); }

9

[DataContract] public class Employee { private string m_Name; [DataMember] public string Name { get { return m_Name; } set { m_Name = value; } }

[MessageContract] public class EmployeeDetails { [MessageHeader] public string EmpID; [MessageBodyMember] public string Name;}

public int Add(int num1, int num2) { //Do something CustomException ex = new CustomException(); ex.Title = "Error Funtion:Add()"; ex.InnerException = "Inner exception message from serice"; ex.StackTrace = "Stack Trace message from service."; throw new FaultException(ex,"Reason: Testing the Fault contract") ;

Page 10: A presentation on WCF & REST

Code Snippets

• Endpoints will be mentioned in the web.config file on the created service.

10

<system.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address="http://localhost:8090/MyService/MathService.svc" contract="IMathService" binding="wsHttpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>

Page 11: A presentation on WCF & REST

WCF Hosting

• IIS hosting• Self hosting• Windows Activation Service• Windows Service

Hosting Environment Supported protocol

Windows console and form application

HTTP,net.tcp,net.pipe,net.msmq

Windows service application (formerly known as NT services)

HTTP,net.tcp,net.pipe,net.msmq

Web server IIS6 http, wshttp

Web server IIS7 - Windows Process Activation Service (WAS)

HTTP,net.tcp,net.pipe,net.msmq

11

Page 12: A presentation on WCF & REST

Metadata Exchange

• WCF provides rich infrastructure for Exporting, Publishing, retrieving and Importing the metadata. WCF uses the Metadata to describe how to interact with the service endpoint. Using the metadata, client will create the proxy class for the service usingSvcUtil.exe

• Exporting Service MetadataIt is the process of describing the service endpoint so that client can understand how to use the service.

• Publishing Service MetadataIt is the process publishing metadata. It involves converting CLR type and binding information into WSDL or some other low level representation.

• Retrieving Service MetadataIt is the process of retrieving the metadata. It uses WS-MetadataExchange or HTTP protocol for retrieving the metadata. Importing Service Metadata - It is the process of generating the abstract representation of the service using metadata.

• There are two way to publish metadata, either HTTP-GET or through message exchange endpoint.

By default service metadata is turn-off due to security reason. WCF metadata infrastructure resides in System.ServiceModel.Description namespace. • Service metadata can be used for following purpose

Automatically generating the client for consuming serviceImplementing the service descriptionUpdating the binding for a client

12

Page 13: A presentation on WCF & REST

Metadata Exchange Endpoint

• Exposing the metadata using HTTP-GET has a disadvantage, such that there is no guarantee that other platforms you interact will support it. There is other way of exposing the using special endpoint is called as Metadata Exchange Endpoint. You can have as many metadata exchange endpoints as you want.

<behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <!-Setting httpGetEnabled you can publish the metadata --> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors>

13

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

//Programming Model://Create a URI to serve as the base address Uri httpUrl = new //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(smb); Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding (); //Adding metadata exchange endpoint host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");

Page 14: A presentation on WCF & REST

Instance Management

• Instance management refers to the way a service handles a request from a client. Instance management is set of techniques WCF uses to bind client request to service instance, governing which service instance handles which client request. It is necessary because application will differ in their need for scalability, performance, durability, transaction and queued calls.

• Basically there are three instance modes in WCF:

1) Per-Call instance mode2) Per-Session instance mode3) Singleton Instance Mode

14

[ServiceContract()] public interface IMyService { [OperationContract] int MyMethod(); } [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class MyService:IMyService { public int MyMethod() { //Do something } }

Page 15: A presentation on WCF & REST

Transfer mode

WCF supports two modes for transferring messages• Buffer transfer• Stream transfer

StreamRequestStreamRespone

<bindings > <netTcpBinding> <binding name="MyService.netTcpBinding" transferMode="Buffered" closeTimeout ="0:01:00" openTimeout="0:01:00"></binding> </netTcpBinding> </bindings>

15

Page 16: A presentation on WCF & REST

Buffered Vs Streamed Transfers

Buffered Streamed

Target can process the message once it is completely received.

Target can start processing the data when it is partially received

Performance will be good when message size is small

Performance will be good when message size is larger(more than 64K)

Native channel shape is IDuplexSessionChannel

Native channels are IRequestChannel and IReplyChannel

16

Page 17: A presentation on WCF & REST

Resource-Oriented Architecture

In software engineering, a resource-oriented architecture (ROA) is a style of software architecture and programming paradigm for designing and developing software in the form of resources with "RESTful" interfaces. These resources are software components  which can be reused for different purposes. ROA design principles and guidelines are used during the phases of software development and system integration.

• "REST, an architectural style for building distributed hypermedia driven applications, involves building Resource-Oriented Architecture (ROA) by defining resources that implement uniform interfaces using standard HTTP verbs (GET, POST, PUT, and DELETE), and that can be located/identified by a Uniform Resource Identifier (URI)."

• Any Service which follows this REST architecture style is called as RESTful service. It became very popular because of it behaviour, it is similar to the website i.e. we can load the server information using web url in the browser. similarly we can also access/modify the server resource using URL in RESTful service

• RESTful service will allow the client (written in different language)to access or modify the resource in the server using URL.

• RESTful service uses the http protocol for its communication and it is stateless• RESTful service can transfer the data in XML,JSON,RSS,ATOM

17

Page 18: A presentation on WCF & REST

REpresentational State Transfer

• Fully Defined in Dissertation of R.T. Fielding– Fielding is co-author of HTTP RFC2616– Generalized Description of Web Architecture

• REST is about– Resources

• Everything can be identified with an identifier• Identifier space forms uniform interface

– Representations• Everything has one or more representations• Resources are manipulated by transferring representations• one or more representations• Resources are manipulated by transferring representations

18

Page 19: A presentation on WCF & REST

REST Principles

• All communication is stateless– Client process holds per-request state– Server process holds no state– Resources map to state

• Requests are independent– Representations are composite– Client state transforms to next state by navigating links

• Manipulation by Transfer of Representations– Uniform interface– All resource manipulation is done in the same way

19

Page 20: A presentation on WCF & REST

webHttpBinding

• New “web-friendly” WCF Binding in Fx 3.5– Allows for the development of RESTful services– Does not use SOAP envelopes– HTTP and HTTPS Transports Only

• Supports several wire formats:– XML– JSON– Binary (streams)

20

Page 21: A presentation on WCF & REST

WebServiceHost

• Specialized SerivceHost for RESTful services– Eliminates need for lots of configuration– Automatically configures address, binding, contract

• Optimized for single-endpoint services• Use from .svc file:

21

<%@ ServiceHost Language="C#" Debug="true" Service="Caching1.FeedService" Factory=“System.ServiceModel.Activation.WebServiceHostFactory” %>"%>

Page 22: A presentation on WCF & REST

[WebGet] And [WebInvoke]

• Binds a WCF operation to URI space and HTTP method

• Indicate the HTTP Method for the operation– WebGet – Don’t make me write it– WebInvoke – All verbs other than GET (Method parameter takes in the

name of the Verb)• Other Parameters

– BodyStyle – Indicates whether the Request/ Response are wrapped or not

– RequestFormat – Json or Xml– ResponseFormat – Json or Xml– UriTemplate – Rich binding to URI

22

Page 23: A presentation on WCF & REST

UriTemplate

• String that allows you to define the structure of the URI, as well as to define “Holes” – The “Holes” are variables– You Bind the template with parameters to

fill the holes

• {productId} hole / variable gets bound to productId parameter in operation

23

[OperationContract][WebGet(UriTemplate=“product/{productId}")]Product GetProduct(int productId);

Page 24: A presentation on WCF & REST

WebGet/WebInvoke Code Snippets

[OperationContract][WebGet( ResponseFormat=WebMessageFormat.Json, UriTemplate=“product/{productId}")]ProductData GetProduct(int productId);

24

[OperationContract][WebInvoke( Method=“PUT", ResponseFormat=WebMessageFormat.Json, UriTemplate=“product/{productId}")]Product UpdateProduct(int productId, product p);

Page 25: A presentation on WCF & REST

REST and HTTP

• Resources identified by URIs– http://www.example.com/customers/3626283– http://www.example.com/weather/us/wa/redmond

• Representations identified by Media Types– text/html, text/xml, application/rss+xml, image/png

• Uniform Interface– GET: Retrieve representation from resource– DELETE: Delete resource– POST: Add/Update resource supplying representation– PUT: Add/Update resource supplying representation

25

Page 26: A presentation on WCF & REST

SOAP Vs REST

• SOAP

- A service architecture- XML based- Runs on HTTP but

envelopes the message- Slower than REST- Very mature, a lot of

functionality- Not suitable for browser-

based clients

• REST

- A service architecture (resource-oriented)

- Uses the HTTP headers to hold meta information

(although it is protocol- agnostic)- Can be used with XML,

JSON or whatever necessary- Usually used with JSON due to the easily parse able content- Faster than SOAP

26

Page 27: A presentation on WCF & REST

27