Successfully reported this slideshow.

WCF

2,145 views

Published on

WCF

  1. 1. Yellow Pepper Mobile Financial SolutionsWindow Communication Foundation August 2010 Presenter: Mai Phi Long
  2. 2. Agenda – Overview – WCF Architecture – WCF Configuration and Hosting – End Point (ABC) – Contacts – Binding – Service Behaviors – New features in WCF 4.0
  3. 3. Overview
  4. 4. WCF Design Goals “The unified programming model for rapidly building service- oriented applications on the Windows Unifies today’s distributed technology stacks Unification Composable functionality Appropriate for use on-machine, in the intranet, and cross the Internet Productive Service-oriented programming model Service-Oriented Programming Supports 4 tenets of service-orientation Maximized developer productivity Interoperability & WS-* interoperability with applications running Integration on other platforms Interoperability with today’s distributed stacks
  5. 5. Unified Model Enterprise ASMX Services Fast Basic Secure Open Binary Interop Txns Remotin WSE g MSMQ Secure Fast Queued Open Secure Txns Interop Binary
  6. 6. Before WCF Remote Procedure Call COM+ .NET Remoting ASP.net web service Hard code TCP Socket MSMQ…
  7. 7. WCF .net 3.5
  8. 8. Unified Model Benefits Programming model – Consistency – Write less code when using multiple technologies Flexibility – Environments • Productivity in development environment • Simplify Automated Integration Testing • Deployment options in production – Design for distribution, run local
  9. 9. WCF Architecture
  10. 10. WCF Architecture Application … Error Metadata InstanceService Model Behavior Behavior Behavior Throttling Transaction Type Integ. Concurrency Behavior Behavior Behavior Behavior Messaging … Secure Channel Reliable Channel Text/XML Encoder HTTP TCP Queue Binary … Channel Channel Channel Encoder Hosting WAS ASP.NET WPF WinForm NT Service COM+ Environments
  11. 11. WCF Architecture: Messaging Runtime Service Contract Client and Dispatcher Behaviors Protocol(s) Protocol(s) Encoder Binding Encoder Transport Transport Address
  12. 12. WCF Architecture: Composition & Behaviors Formatter Transaction Security TCP Behavior Behavior Channel TransportService Code Formatter Message Instancing Security TCP Behavior Inspector Behavior Channel Transport Service Model Layer Messaging Layer Influences system operation Moves messages back and forth based on incoming and outgoing messages. and adds transfer semantics. Effects of behaviors are local. Channels are symmetric.
  13. 13. Ways to Talk / Service Contract (MEPs) One Way Client Service Request-Reply Duplex (Dual) One Way: – Datagram-style delivery Request-Reply – Immediate Reply on same logical thread Duplex – Reply “later” and on backchannel (callback-style)
  14. 14. Elements in WCF
  15. 15. WCF Configuration and Hosting
  16. 16. WCF Configuration and Hosting WCF Service can be configured in code WCF Service can be configured in XML or mix. 3 different ways to host WCF – Self Hosting – IIS Hosting – Windows Service
  17. 17. Implement WCF in code ServiceHost serviceHost = new ServiceHost(typeof(StockService), newUri("http://localhost:8000/EssentialWCF")); serviceHost.AddServiceEndpoint( typeof(IStockService), new BasicHttpBinding(), ""); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; serviceHost.Description.Behaviors.Add(behavior); serviceHost.AddServiceEndpoint( typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); serviceHost.Open(); // The service can now be accessed. Console.WriteLine("The services is ready. Press <ENTER> toterminate.nn"); Console.ReadLine(); // Close the ServiceHostBase to shutdown the service. serviceHost.Close();
  18. 18. WCF Configuration File<system.serviceModel> <services> <service name="EssentialWCF.StockService" behaviorConfiguration="myServiceBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:8000/EssentialWCF"/> </baseAddresses> </host> <endpoint address="" binding="basicHttpBinding" contract="EssentialWCF.IStockService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="myServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
  19. 19. Demo Self Hosting IIS Hosting Windows Service
  20. 20. End Point
  21. 21. Services and Clients
  22. 22. Endpoints Client Service Endpoint Endpoint Message EndpointThe service endpoint contains the information about the Address,Binding, Contract, and Behavior required by a client to find andinteract with the service at this endpoint.
  23. 23. Address, Binding, Contract Client Service A B C C B A Message A B C Address Binding Contract (Where) (How) (What)
  24. 24. How client knows WCF service  mexMetadata tells client how to connect & communicate to web service.Design time, client sends request defined in WS-Metadata exchange standard and getWSDL in return.WSDL is then used to create proxy class and create config file at client
  25. 25. Expose mex endpoint by code or config file httpGetEnabled allows client to query mex through Http Get method.<system.serviceModel> <services> <service name="WCFServiceApplication.Service1"behaviorConfiguration="WCFServiceApplication.Service1Behavior"> <endpoint address="" binding="wsHttpBinding"contract="WCFServiceApplication.IService1"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding"contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WCFServiceApplication.Service1Behavior"> <!-- To avoid disclosing metadata information, set the value below to falseand remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors></system.serviceModel>
  26. 26. Some tools to debug, and test WCF WCF Test Client WCF Service Configuration Editor
  27. 27. Contracts
  28. 28. Three Types of Contracts Service Contract => WSDL – Maps the class methods of a .NET type to WSDL services, port types, and operations. Operation contracts within service contracts describe the service operations, which are the methods that implement functions of the service. Data Contract => XSD – Describe data structures that are used by the service to communicate with clients. A data contract maps CLR types to XML Schema Definitions (XSD) and defines how they are serialized and deserialized. Data contracts describe all the data that is sent to or from service operations. Message Contract => SOAP – Map CLR types to SOAP messages and describe the format of the SOAP messages and affect the WSDL and XSD definitions of those messages. Message contracts provide precise control over the SOAP headers and bodies.
  29. 29. Service Contractusing System.ServiceModel;[ServiceContract]public interface ICalculate{ [OperationContract] double Add( double a, double b); [OperationContract] double Subtract( double a, double b);}
  30. 30. Synchronous vs Asynchronous Request ResponseMain Thread Service BeginOperation New Thread EndOperation client.AddCompleted += new EventHandler<MathPlayer. MathService.AddCompletedEventArgs>(client_AddCompleted); client.AddAsync(int.Parse(txtA.Text), int.Parse(txtB.Text));
  31. 31. Service Contract: OneWay[ OperationContract(IsOneWay = true)]void DoBigAnalysisFast(string ticker);[OperationContract]void DoBigAnalysisSlow(string ticker);The client just needs acknowledgement of successful delivery; it doesnot need an actual response from the service
  32. 32. Duplex Communication Use wsDualHttpBinding Since two endpoints are used, we can define two different bindings, protocol for each channels
  33. 33. Service Contract: Duplex Asymmetric[ServiceContract(Session=true, CallbackContract=typeof(ICalculatorResults)]public interface ICalculatorProblems{ [OperationContract(IsOneWay=true)] void SolveProblem (ComplexProblem p);}public interface ICalculatorResults{ [OperationContract(IsOneWay=true)] void Results(ComplexProblem p);}
  34. 34. Service Contract: Duplex Symmetric[ServiceContract(Session=true, CallbackContract=typeof(IChat)]public interface IChat{ [OperationContract(IsOneWay=true)] void Talk(string text);}
  35. 35. Demo Request –Reply One Way One Service many EndPoints
  36. 36. Data Contract[DataContract]public class ComplexNumber{ [DataMember] public double Real = 0.0D; [DataMember] public double Imaginary = 0.0D; public ComplexNumber(double r, double i) { this.Real = r; this.Imaginary = i; }}
  37. 37. Demo Basic data type data contract Class data type data contract Hierarchy data type data contract Collection data contract
  38. 38. Service Contract: Faults[ServiceContract(Session=true)]public interface ICalculator{ [OperationContract] [FaultContract(typeof(DivideByZero))] ComplexProblem SolveProblem (ComplexProblem p);}try { return n1 / n2;}catch (DivideByZeroException e) { DivideByZero f = new DivideByZero (“Calculator”); throw new FaultException<DivideByZero>(f);}
  39. 39. Message Contract[MessageContract]public class ComplexProblem{ [MessageHeader] public string operation; [MessageBody] public ComplexNumber n1; [MessageBody] public ComplexNumber n2; [MessageBody] public ComplexNumber solution; // Constructors…}
  40. 40. Bindings
  41. 41. Bindings & Binding Elements Binding HTTP Text Security Reliability TX Transport Encoders Protocol TCP HTTP Text Security Reliability MSMQ IPC Binary TX .NET Custom Custom Custom
  42. 42. Standard Bindings in WCF.net 3.0Binding Interop Security Session TX DuplexBasicHttpBinding BP 1.1 N, T N N n/aWSHttpBinding WS M, T, X N, T, RS N, Yes n/aWSDualHttpBinding WS M RS N, Yes YesWSFederationBinding Federation M N, RS N, Yes NoNetTcpBinding .NET T, M T ,RS N, Yes YesNetNamedPipeBinding .NET T T, N N, Yes YesNetPeerTcpBinding Peer T N N YesNetMsmqBinding .NET T, M, X N N, Yes NoMsmqIntegrationBinding MSMQ T N N, Yes n/a N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions
  43. 43. New bindings in WCF.net 3.5 ws2007HttpBinding ws2007FederationBinding
  44. 44. Supported Features of Each Binding
  45. 45. Choose a binding that suits your need
  46. 46. Reliability and Transactions End-to-end Reliable messaging – In-order guarantees – Exactly once guarantees Transport-Independent Sessions – Integration with ASP.NET Sessions in IIS-Hosted compatibility mode Transactions – Guaranteed atomic success or failure across services
  47. 47. Bindings & Behaviors: Reliable Sessions Client Service A B C C B A A B C A B C Bindings provide Session and GuaranteesReliable Messaging: in-order and exactly once (similar toMSMQ and MQSeries guarantees).
  48. 48. Bindings & Behaviors: Transactions Client Service A B C C B A A B C A B C Be Be Bindings Flow Transactions Behaviors AutoEnlist and AutoComplete1- Multistep business process : Long running transaction WF integrates withWCF2- Short running transaction
  49. 49. Defining Endpoints<?xml version="1.0" encoding="utf-8" ?><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0 "> <system.serviceModel> <services> <service serviceType="CalculatorService"> <endpoint address="Calculator" bindingSectionName="basicProfileBinding" contractType="ICalculator" /> </service> </services> </system.serviceModel></configuration>
  50. 50. Configuring Bindings<endpoint address="Calculator" bindingSectionName="basicProfileBinding" bindingConfiguration="Binding1" contractType="ICalculator" /><bindings> <basicProfileBinding> <binding configurationName="Binding1" hostnameComparisonMode="StrongWildcard" transferTimeout="00:10:00" maxMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" </binding> </basicProfileBinding></bindings>
  51. 51. Custom Bindings<bindings> <customBinding> <binding configurationName="Binding1"> <reliableSession bufferedMessagesQuota="32" inactivityTimeout="00:10:00" maxRetryCount="8" ordered="true" /> <httpsTransport manualAddressing="false" maxMessageSize="65536" hostnameComparisonMode="StrongWildcard"/> <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16" messageVersion="Default" encoding="utf-8" /> </binding> </customBinding></bindings>
  52. 52. Multiple EndPoints in a Service Scenarior: SilverLight app can connect to basicHttpBinding while WPF app can connect to wsHttpBinding. If we have one service how can we serve two types of clients.<service behaviorConfiguration="MathWCFServiceApplication.MathServiceBehavior"name="MathWCFServiceApplication.MathService"> <!--EndPoint is used for WPF client--> <endpoint name="wsHttpMath" address="ws" binding="wsHttpBinding"contract="MathWCFServiceApplication.IMathService"> <identity> <dns value="localhost"/> </identity> </endpoint> <!--EndPoint is used for SilverLight client--> <endpoint name="basicHttpMath" address="basic" binding="basicHttpBinding"contract="MathWCFServiceApplication.IMathService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/></service>
  53. 53. WCF returns JSONJSON short for JavaScript Object Notation, is a lightweight computer data interchangeformat. It is a text-based, human-readable format for representing simple data structuresand associative arrays (called objects).<services> <service name="Wcf2Ajax.Service1"behaviorConfiguration="Wcf2Ajax.Service1Behavior"> <endpoint address="" behaviorConfiguration="AjaxBehavior"binding="webHttpBinding" contract="Wcf2Ajax.IService1"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding"contract="IMetadataExchange"/> </service></services><behaviors> <endpointBehaviors> <behavior name="AjaxBehavior"> <enableWebScript/> </behavior> </endpointBehaviors>
  54. 54. Service Behaviors:Instance and Concurrency Management
  55. 55. Instance and Concurrent modes WCF can control concurrency by the following two behaviors: InstanceContextMode and ConcurrencyMode. 3 instance modes: – Per-Session instance mode – Per-Call instance mode – Singleton Instance Mode 3 concurrent modes: – Single - default setting. Instructs the runtime to allow access on one thread per instance of the service class. This setting is the safest one because service operations do not need to worry about thread safety. – Reentrant - Only one thread at a time can access the service class, but the thread can leave the class and come back later to continue. – Multiple - Multiple threads may access the service class simultaneously. This setting requires the class to be built in a thread-safe manner.
  56. 56. Per SessionOne service instance for one session
  57. 57. Per CallOne instance for each call, even a call from same client
  58. 58. Singleton Instance
  59. 59. Service Throttling maxConcurentInstances: controlling how many services can be created by service. With this setting we are defining the upper boundary of the number of instances resides in a memory. maxConcurentCalls: - controlling how many concurrent calls can be active. What we can manage here is actually the number of threads used in our service processing. maxConcurrentSessions: - used to control how many active sessions we have especially when using PerSession instance mode.
  60. 60. WCF Security Authentication Authorization Confidentiality Integrity Transport and Message Security Please look at http://wcfsecurityguide.codeplex.com/
  61. 61. Workflow Services Architecture Service.cs Workflow.cs or Workflow.xoml Service Runtime Service Runtime Service Instance WorkflowInstance WorkflowInstance Service Instance OperationInvoker OperationInvoker WorkflowOperationInvoker WorkflowOperationInvoker Operation 11 ReceiveActivity 11 Operation ReceiveActivityApp.config OperationSelector OperationSelector Operation 22 ReceiveActivity 22 Operation ReceiveActivity Workflow Workflow ServiceHost ServiceHost ServiceHost ServiceHost InstanceProvider InstanceProvider DurableInstanceProvider DurableInstanceProvider Workflow Runtime Workflow Runtime MessageInspector MessageInspector MessageContextInspector MessageContextInspector ServiceDescription ServiceDescription ContextChannel ContextChannel WF Persistence DB WF Persistence DB ServiceBehavior ServiceBehavior WorkflowServiceBehavior WorkflowServiceBehavior ListenerChannel ListenerChannel OperationBehavior OperationBehaviorWorkflowOperationBehaviorWorkflowOperationBehavior
  62. 62. StockTrader.net: a good WCF examplehttp://msdn.microsoft.com/en-us/netframework/bb499684.aspx
  63. 63. New features in WCF 4.0Windows Communication Foundation (WCF) in .NET 4 includes three newfeatures areas. 1. Simplified Configuration Simplifications to configuration make WCF easier to use. In WCF 4 we can create a service without any configuration at all 2. Service Discovery Service Discovery allows you to locate services on the same subnet using ad hoc discovery, or using a proxy to establish connections with servers regardless of where they are. 3. Service Routing The Routing Service is designed to act as a generic, configurable SOAP intermediary. It allows you to configure Content Based Routing, set up Protocol Bridging, and handle communication errors that you encounter. The Routing Service also makes it possible for you to update your Routing Configuration while the Routing Service is running without restarting the service.
  64. 64. Demo1. Simplified Configuration2. Service Discovery3. Service Routing
  65. 65. WCF Summary WCF is good for SOA, distributed computing It combines the best of all existing Microsoft distributed computing stacks It uses WS-* standards for interoperability and .NET value- add for performance and integration with existing solutions
  66. 66. Good References Book “Essential Windows Communication Foundation for .NET 3.5” PluralSight video training http://www.pluralsight.com/main/screencasts/default.aspx Channel 9 http://channel9.msdn.com/shows/Endpoint/
  67. 67. Q&A

×