Wcf architecture overview
Upcoming SlideShare
Loading in...5
×
 

Wcf architecture overview

on

  • 2,658 views

This is a fundamental understanding of WCF services.

This is a fundamental understanding of WCF services.

Statistics

Views

Total Views
2,658
Views on SlideShare
2,658
Embed Views
0

Actions

Likes
1
Downloads
112
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Wcf architecture overview Wcf architecture overview Presentation Transcript

  • WCF Architecture OverviewSunday, December 16, 2012 Arbind
  • WCF ServiceA service exposes endpoints(Endpoint: a port to communicate with outside world)Sunday, December 16, 2012 Arbind
  • A ClientExchanges messages with one or more Endpoints.May also expose an Endpoint to receive Messages from a Service in a duplex message exchange pattern.Sunday, December 16, 2012 Arbind
  • Endpoint: Has 1. An Address 2. A Binding 3. A ContractSunday, December 16, 2012 Arbind
  • Address:A network location where the Endpoint resides.Represented by an EndpointAddress ClassEndpointAddress is a URI, a collection of AddressHeader and identitySunday, December 16, 2012 Arbind
  • Bindings: Has 1. A name 2. A namespace 3. A collection of binding elementsSunday, December 16, 2012 Arbind
  • Collection of binding elements:Each binding elements describe how to communicate with the end point 1. TcpTransportBindingElement indicates that the Endpoint will communicate with the world using TCP as the transport protocol. 2. ReliableSessionBindingElement indicates that the Endpoint uses reliable messaging to provide message delivery assurances. 3. SecurityBindingElement indicates that the Endpoint uses SOAP message security.Sunday, December 16, 2012 Arbind
  • Contracts:Refers to the collection of operations which specify what endpoint will communicate to out side worldSunday, December 16, 2012 Arbind
  • ContractDescription class is used to describe WCF Contracts and their operations.Each Contract Operation have OperationDescriptions andeach operationDescription have MessageDescriptionSunday, December 16, 2012 Arbind
  • Duplex Contract: Defines two Logical Operations 1. A set that the Service exposes for the Client to call 2. A set that the Client exposes for the Service to callSunday, December 16, 2012 Arbind
  • Contract: Has 1. Name 2. Namespace 3. IdentitySunday, December 16, 2012 Arbind
  • Contract:Sunday, December 16, 2012 Arbind
  • Behaviors:Are types which modifies services or client functionalitiesSunday, December 16, 2012 Arbind
  • ServiceBehavior is a type which implements IServiceBehavior and applies to serviceSunday, December 16, 2012 Arbind
  • ChannelBehavior is a type which implements IChannelBehavior and applies to clientSunday, December 16, 2012 Arbind
  • Service and Channel DescriptionsThe ServiceDescription class describes a WCF Service including the Endpoints exposed by the Service, the Behaviors applied to the Service, and the type (a class) that implements the Service.ServiceDescription is used to create metadata, code/config, and channels.Sunday, December 16, 2012 Arbind
  • Behavior:Sunday, December 16, 2012 Arbind
  • ChannelDescription describes a WCF Clients Channel to a specific EndpointServiceDescription can have multiple endpoint butChannelDescription have only one endpointSunday, December 16, 2012 Arbind
  • WCF Runtime:The set of objects responsible for sending and receiving messagesSunday, December 16, 2012 Arbind
  • Message:The unit of data exchange between a Client and an EndpointA message should be of SOAP message type and can be serialized using the WCF binary format, text XML, or any other custom format.Sunday, December 16, 2012 Arbind
  • Channels:Channels are the core abstraction for sending Messages to and receiving Messages from an Endpoint.Sunday, December 16, 2012 Arbind
  • Two Category of channel:1. Transport Channels handle sending or receiving opaque octet streams using some form of transport protocol such as TCP, UDP, or MSMQ.2. Protocol Channels, implement a SOAP-based protocol by processing and possibly modifying messages.Sunday, December 16, 2012 Arbind
  • Procedure to define WCF ServiceStep1: Defining and Implementing a Contractusing System.ServiceModel;[ServiceContract]public interface IMath{ [OperationContract] int Add(int x, int y);}Step2: Define a service classThis contract (interface IMath) is implemented to a class which becomes a service classpublic class MathService : IMath{ public int Add(int x, int y) { return x + y; }}Sunday, December 16, 2012 Arbind
  • Step3: Defining Endpoints and Starting the Service(endpoint can be defined in code or in config)In Code:public class WCFServiceApp{ public void DefineEndpointImperatively() { //create a service host for MathService ServiceHost sh = new ServiceHost(typeof(MathService)); //use the AddEndpoint helper method to //create the ServiceEndpoint and add it //to the ServiceDescription sh.AddServiceEndpoint( typeof(IMath), //contract type new WSHttpBinding(), //one of the built-in bindings "http://localhost/MathService/Ep1"); //the endpoints address //create and open the service runtime sh.Open(); } public void DefineEndpointInConfig() { //create a service host for MathService ServiceHost sh = new ServiceHost (typeof(MathService)); //create and open the service runtime sh.Open(); }}Sunday, December 16, 2012 Arbind
  • Endpoint in config file:<!-- configuration file used by above code --><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"><system.serviceModel><services><!-- service element references the service type --><service type="MathService"><!-- endpoint element defines the ABCs of the endpoint --><endpoint address="http://localhost/MathService/Ep1" binding="wsHttpBinding" contract="IMath"/></service></services></system.serviceModel></configuration> Sunday, December 16, 2012 Arbind
  • Step4: Sending Messages to the Endpointusing System.ServiceModel;//this contract is generated by svcutil.exe//from the services metadatapublic interface IMath{ [OperationContract] public int Add(int x, int y) { return x + y; }}//this class is generated by svcutil.exe//from the services metadata//generated config is not shown herepublic class MathProxy : IMath{ ... }Continue……….Sunday, December 16, 2012 Arbind
  • In the following code first way to send the message to endpoint is like SendMessageToEndpoint part. This hides the channel creation which is happening behind the sceneSecond way (SendMessageToEndpointUsingChannel) does it explicitly.public class WCFClientApp{ public void SendMessageToEndpoint() { //this uses a proxy class that was //created by svcutil.exe from the services metadata MathProxy proxy = new MathProxy(); int result = proxy.Add(35, 7); } public void SendMessageToEndpointUsingChannel() { //this uses ChannelFactory to create the channel //you must specify the address, the binding and //the contract type (IMath) ChannelFactory<IMath> factory=new ChannelFactory<IMath>( new WSHttpBinding(), new EndpointAddress("http://localhost/MathService/Ep1")); IMath channel=factory.CreateChannel(); int result=channel.Add(35,7); factory.Close(); }}Sunday, December 16, 2012 Arbind
  • Step5: Defining custom behaviorWe need to implement IServiceBehavior for service and IChannelBehavior for clientAll behaviors can be applied imperatively by adding an instance of the behavior to the ServiceDescription (or the ChannelDescription on the client side).ServiceHost sh = new ServiceHost(typeof(MathService)); sh.AddServiceEndpoint( typeof(IMath), new WSHttpBinding(), "http://localhost/MathService/Ep1");//Add the behavior imperatively// InspectorBehavior is a custom behaviorInspectorBehavior behavior = new InspectorBehavior(); sh.Description.Behaviors.Add(behavior);sh.Open(); Sunday, December 16, 2012 Arbind
  • Secure Hosting and Deployment of WCF ServicesService host is a execution environment for service codeService has to be hosted before deploymentSunday, December 16, 2012 Arbind
  • Why host is required? Provide security context for the execution of WCF service Providing a mechanism to configure the WCF service Providing a mechanism to monitor the statistics and health of WCF service Provide rapid fail protection and tools for WCF service managementSunday, December 16, 2012 Arbind
  • Type of host 1. Managed Application / Self Host 2. Managed Windows Service 3. IIS 4. WASSunday, December 16, 2012 Arbind
  • Criteria for Choosing a WCF Service HostConsider following things before coming to conclusionA. Target Deployment PlatformB. Protocol to be supported by the service Sunday, December 16, 2012 Arbind
  • Example:If service needed to support HTTP, TCP, MSMQ and Named Pipe and platform is Windows longhorn server – IIS 7.0 with WAS should be usedIf service needed to support HTTP and platform is Windows server 2003 – IIS 6.0 should be usedif TCP, MSMQ and Named Pipe required to be supported and platform is Windows server 2003 - Managed Windows Service can be usedIf service need to support HTTP, TCP, MSMQ and Named Pipe protocols on Windows Vista – IIS 7.0 along with WAS should be usedOn Windows XP, IIS 5.1 should be used if supported protocol is HTTP and Windows service can be used for TCP, MSMQ and Named PipeSunday, December 16, 2012 Arbind
  • How to select host?Managed Application / Self HostAny .NET managed application can host a WCF service by creating an instance of ServiceHost ClassServiceHost Class is a member of System.ServiceModel namespace(Hosting a Service in managed application is also called Self Hosting)Sunday, December 16, 2012 Arbind
  • Point to note: Self host does not provide features like message based activation, mechanism to monitor service health or service host resources or recycling of the service host process upon detection of error conditions.And so: This is useful in development environment but not in production environmentSunday, December 16, 2012 Arbind
  • In Self Hosting, the Service Host has to be instantiated at the time of the managed application startup and closed before the managed application shutdown.Sunday, December 16, 2012 Arbind
  • The security context in Self Host is the identity under which the managed application runsSunday, December 16, 2012 Arbind
  • A WCF Service hosted in a managed application can be exposed over TCP, HTTP, HTTPS, Named Pipe and MSMQ protocols.Sunday, December 16, 2012 Arbind
  • Code sample for creating a Service Host in managed applicationUsing(ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService))){ //Open the Service Host to start receiving messages serviceHost.Open(); // The service is now ready to accept requests ….. ….. // Close the ServiceHost to shutdown the service. serviceHost.Close();}Sunday, December 16, 2012 Arbind
  • The base address and the endpoints for the service host have to be configured in the <services> sub section of the <system.serviceModel> section of the App.Config as shown below:<system.serviceModel> <services> <service name="SecureHosting.Samples.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:9000/SecureHostingSamples/service"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="SecureHosting.Samples.ICalculator" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="CalculatorServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> Sunday, December 16, 2012 Arbind
  • Base Address and endpoint can also be configured programmatically instead of configuring in App.Config file// Create a ServiceHost for the CalculatorService type. using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService),new Uri("http://localhost:9000/SecureHostingSamples/service"))) { //Configure the service with an end point serviceHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), ""); // Open the ServiceHost to start receiving messages serviceHost.Open(); …. …. …. //Close the service host to shutdown the service serviceHost.Close ();}Sunday, December 16, 2012 Arbind
  • Managed Window Service(A Window Service running under managed environment)Service can be installed using Installutil tool.The service can be exposed to HTTP, TCP, MSMQ and Named Pipe protocolSunday, December 16, 2012 Arbind
  • The window service which host the service inherits from the ServiceBase class and also implements contractSunday, December 16, 2012 Arbind
  • Windows Service provides the facility to manage the lifecycle of the service via the Service Control Manager (SCM) consoleSunday, December 16, 2012 Arbind
  • Windows Service Host does not provide a message based activationSunday, December 16, 2012 Arbind
  • Window service leverages the OnStart event to create service host and host closes on OnStop event.Sunday, December 16, 2012 Arbind
  • Security context can be configured using Installer Class with the help of ServiceProcessInstaller.Sunday, December 16, 2012 Arbind
  • Sample Code to create Managed Window Servicepublic class CalculatorService : ServiceBase, ICalculator{ public ServiceHost serviceHost = null; public static void Main() { ServiceBase.Run(new CalculatorService()); } public CalculatorService() { ServiceName = "WCFWindowsCalculatorService"; } //Start the Windows service. protected override void OnStart(string[] args) { if (serviceHost != null) { serviceHost.Close(); } // Create a ServiceHost for the Service serviceHost = new ServiceHost(typeof(CalculatorService)); // Start Listening for the Messages serviceHost.Open(); } //Stop the Windows Service protected override void OnStop() { if (serviceHost != null) { serviceHost.Close(); serviceHost = null; } }} Sunday, December 16, 2012 Arbind
  • IISAllows the Services to be hosted in the App Domains inside the ASP.NET worker processSupported IIS: 5.1, 6.0, 7.0 8.0(BETA)(Only Http and Https can be handled)Sunday, December 16, 2012 Arbind
  • IIS handles the service request in the same way as it handles web requestSupports message based activation and service instance is created only after receiving the first message.Sunday, December 16, 2012 Arbind
  • The security context for the WCF Service hosted inside the ASP.NET worker process is provided by the service account under which the worker process runs. (Knowledge Sharing) WHAT WILL BE THE SECURITY TO BE IMPLEMENTED?Sunday, December 16, 2012 Arbind
  • Hosting a service in IIS requires .SVC file to be createdIf required a Custom Service Host we can create it using System.ServiceModel.Activation.ServiceHostFactory Class(Virtual applications are created and DLLs and sources are deployed to the physical path associated with the virtual application)Sunday, December 16, 2012 Arbind
  • The configuration for the service endpoints has to be defined in the Web.ConfigThe .SVC file should contain code like:<%@ServiceHost language=c# Debug="true" Service=" SecureHosting.Samples.CalculatorService" %>Sunday, December 16, 2012 Arbind
  • Web.Config for IIS Host:<system.serviceModel> <services> <service name="SecureHosting.Samples.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior"> <!-- This endpoint is exposed at the base address provided by host: http://localhost/securehostingsamples/service.svc --> <endpoint address="" binding="wsHttpBinding" contract="SecureHosting.Samples.ICalculator" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <!--For debugging purposes set the includeExceptionDetailInFaults attribute to true-- > <behaviors> <serviceBehaviors> <behavior name="CalculatorServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>Sunday, December 16, 2012 Arbind
  • WAS (Windows Activation Service)WAS enables IIS 7.0 to leverage message based activation for protocols such as TCP, MSMQ and Named Pipes in addition to the HTTP protocolAvailable with Windows Vista and Windows Longhorn ServerService deployment process for IIS 7.0/WAS is same as discussed earlier for IIS hostSunday, December 16, 2012 Arbind
  • Note:1. web sites need to be configured via the APPCMD utility to support non HTTP protocols2. To do this command shell must be started in “Run as Administrator” modeSunday, December 16, 2012 Arbind
  • Command to run:%windir%system32inetsrvappcmd.exe set site "Default Web Site" -+bindings.[protocol=net.tcp,bindingInformation=808:*] FOR TCP%windir%system32inetsrvappcmd.exe set site "Default Web Site" -+bindings.[protocol=net.msmq,bindingInformation=*] FOR MSMQ%windir%system32inetsrvappcmd.exe set site "Default Web Site" -+bindings.[protocol=net.pipe,bindingInformation=*] FOR NAMED PIPESunday, December 16, 2012 Arbind
  • After running the command APPCMD updates configuration file for WAS ApplicationHost.Config<system.applicationHost> <sites> <site name="Default Web Site" id="1"> <bindings> <binding protocol="http" bindingInformation="*:80:" /> <binding protocol="net.pipe" bindingInformation="*" /> <binding protocol="net.tcp" bindingInformation="808:*" /> <binding protocol="net.msmq" bindingInformation="*" /> </bindings> </site> </sites></system.applicationHost>Sunday, December 16, 2012 Arbind
  • To enable the TCP protocol (in addition to the HTTP protocol) for the “SecureHostingSamples” application, the following command should be run from an administrator shell: %windir%system32inetsrvappcmd.exe set app "Default Web Site/securehostingsamples" /enabledProtocols:http,net.tcpSunday, December 16, 2012 Arbind
  • Selecting Binding:Criteria to select Bindings:1. Consider the deployment environment whether it is for Internet, Intranet, Federated Environment, Windows only or a Heterogeneous Environment2. Security to be implemented3. Performance IssuesSunday, December 16, 2012 Arbind
  • A WCF service can be assigned: 1. Transport level security, 2. Message level security or 3. A combination of transport and message level security.Sunday, December 16, 2012 Arbind
  • A service can be defined with an authentication mode of 1. None, 2. Username, 3. Windows, 4. Certificates and 5. IssuedToken. Authentication process between the client and the service includes the authentication of service to the client as well as the authentication of the client to the service.Sunday, December 16, 2012 Arbind
  • Deploying a WCF Service over Windows Only Intranet In Windows only Intranet, if all the service clients are WCF clients, the service can be deployed using NetTCPBinding and transport level security to achieve maximum performance.(NetTCPBinding by default uses transport level security along with TCP channel and binary message encoding)ClientCredentialType is set to Windows to enable Windows AuthenticationCode Sample:<bindings> <netTcpBinding> <binding name="Binding1"> <security mode="Transport" /> <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/> </security> </binding> </netTcpBinding></bindings>Sunday, December 16, 2012 Arbind
  • Interoperability with web servicesThe WCF service can be configured to use BasicHttpBinding with transport level security.HTTP/GET metadata should be enabled for the service in the service behavior section.Sunday, December 16, 2012 Arbind
  • Deploying a WCF Service over Internet or in a Heterogeneous Environment(needs to potentially interact with the clients on non-windows platforms)--BasicHttpBinding or WSHttpBinding can be used depending upon the level of conformance required with the commonly used security standardsIf interoperability is required with web service only BasicHttpBinding should be used.Sunday, December 16, 2012 Arbind
  • To support SOAP Message Security UserName Token Profile version 1.0, the WCF service should be configured with BasicHttpBinding with security mode of TransportWithMessageCredential and client credential type of UserName.Example:<basicHttpBinding> <binding name="Binding1"> <security mode="TransportWithMessageCredential"> <message clientCredentialType="UserName" /> </security> </binding></basicHttpBinding>Sunday, December 16, 2012 Arbind
  • Deployment in Federated EnvironmentWCF Service client obtains a security token from Security Token Service (STS) which is trusted by WCF ServiceWCF Service should be configured for WSFederatedHttpBindingThe security token also contains the address of the endpoint to retrieve metadata of STSthe certificate used by STS for signing the security token should be added to the list of known certificates in the service credential section.Sunday, December 16, 2012 Arbind
  • <bindings><wsFederationHttpBinding> <binding name="Binding1"> <security mode ="Message"> <message issuedKeyType ="SymmetricKey" issuedTokenType ="http://docs.oasis-open.org/wss/oasis- wss-saml-token-profile-1.1#SAMLV1.1" > <issuerMetadata address ="http://localhost:8888/sts/mex" > <identity> <certificateReference storeLocation ="CurrentUser" storeName="TrustedPeople" x509FindType ="FindBySubjectDistinguishedName" findValue ="CN=STS" /> </identity> </issuerMetadata> </message> </security> </binding></wsFederationHttpBinding></bindings><behaviors> <serviceBehaviors> <behavior name ="ServiceBehaviour" > <serviceCredentials> <issuedTokenAuthentication> <knownCertificates> <add storeLocation ="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectDistinguishedName" findValue="CN=STS" /> </knownCertificates> </issuedTokenAuthentication> <serviceCertificate storeLocation ="LocalMachine" storeName ="My" x509FindType ="FindBySubjectDistinguishedName" findValue ="CN=localhost"/> </serviceCredentials> </behavior> </serviceBehaviors></behaviors>Sunday, December 16, 2012 Arbind
  • Assignment For All Create a WCF service to convertFahrenheit to Celsius and vice versa and to be hosted in IIS If done: mail it on arbindkumar_tiwari@satyam.comSunday, December 16, 2012 Arbind
  • Sunday, December 16, 2012 Arbind