SlideShare a Scribd company logo
1 of 67
Yellow Pepper
     Mobile Financial Solutions




Window Communication Foundation
                August 2010
           Presenter: Mai Phi Long
Agenda
 – Overview
 – WCF Architecture
 – WCF Configuration and Hosting
 – End Point (ABC)
 – Contacts
 – Binding
 – Service Behaviors
 – New features in WCF 4.0
Overview
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
Unified Model


                                   Enterprise
  ASMX                              Services
                                      Fast
  Basic                              Secure
  Open                               Binary
 Interop                              Txns


                     Remotin
             WSE         g     MSMQ
           Secure      Fast    Queued
            Open      Secure    Txns
           Interop    Binary
Before WCF
 Remote Procedure Call
 COM+
 .NET Remoting
 ASP.net web service
 Hard code TCP Socket
 MSMQ
…
WCF .net 3.5
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
WCF Architecture
WCF Architecture
                       Application



                           …              Error           Metadata        Instance
Service 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
WCF Architecture: Messaging Runtime

                        Service        Contract
    Client                               and
                       Dispatcher      Behaviors

    Protocol(s)          Protocol(s)



                          Encoder
                                        Binding
     Encoder



     Transport           Transport
                                        Address
WCF Architecture: Composition & Behaviors

           Formatter   Transaction                     Security     TCP
           Behavior     Behavior                       Channel    Transport


Service
 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.
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)
Elements in WCF
WCF Configuration and Hosting
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
Implement WCF in code
 ServiceHost serviceHost = new ServiceHost(typeof(StockService),
                                          new
Uri("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> to
terminate.nn");
            Console.ReadLine();

            // Close the ServiceHostBase to shutdown the service.
            serviceHost.Close();
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>
Demo
 Self Hosting
 IIS Hosting
 Windows Service
End Point
Services and Clients
Endpoints


     Client                                         Service
                                                Endpoint

         Endpoint           Message             Endpoint



The service endpoint contains the information about the Address,
Binding, Contract, and Behavior required by a client to find and
interact with the service at this endpoint.
Address, Binding, Contract


   Client                                    Service
                                      A    B C

            C B   A     Message       A    B C




              Address   Binding   Contract

              (Where)    (How)    (What)
How client knows WCF service  mex
Metadata tells client how to connect & communicate to web service.
Design time, client sends request defined in WS-Metadata exchange standard and get
WSDL in return.
WSDL is then used to create proxy class and create config file at client
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 false
and remove the metadata endpoint above before deployment -->
        <serviceMetadata httpGetEnabled="true"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>
Some tools to debug, and test WCF


                            WCF Test Client




                            WCF Service
                            Configuration
                            Editor
Contracts
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.
Service Contract

using System.ServiceModel;

[ServiceContract]
public interface ICalculate
{
       [OperationContract]
       double Add( double a, double b);
       [OperationContract]
       double Subtract( double a, double b);
}
Synchronous vs Asynchronous Request Response
Main 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));
Service Contract: OneWay

[ OperationContract(IsOneWay = true)]
void DoBigAnalysisFast(string ticker);

[OperationContract]
void DoBigAnalysisSlow(string ticker);




The client just needs acknowledgement of successful delivery; it does
not need an actual response from the service
Duplex Communication

                       Use wsDualHttpBinding


                       Since two endpoints
                       are used, we can define
                       two different bindings,
                       protocol for each
                       channels
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);
}
Service Contract: Duplex Symmetric



[ServiceContract(Session=true,
          CallbackContract=typeof(IChat)]
public interface IChat
{
    [OperationContract(IsOneWay=true)]
    void Talk(string text);
}
Demo
 Request –Reply
 One Way
 One Service many EndPoints
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;
    }
}
Demo
 Basic data type data contract
 Class data type data contract
 Hierarchy data type data contract
 Collection data contract
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);
}
Message Contract
[MessageContract]
public class ComplexProblem
{
    [MessageHeader]
    public string operation;
    [MessageBody]
    public ComplexNumber n1;
    [MessageBody]
    public ComplexNumber n2;
    [MessageBody]
    public ComplexNumber solution;

    // Constructors…
}
Bindings
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
Standard Bindings in WCF.net 3.0
Binding                          Interop       Security     Session     TX        Duplex

BasicHttpBinding                 BP 1.1        N, T         N           N         n/a

WSHttpBinding                    WS            M, T, X      N, T, RS    N, Yes    n/a

WSDualHttpBinding                WS            M            RS          N, Yes    Yes

WSFederationBinding              Federation    M            N, RS       N, Yes    No

NetTcpBinding                    .NET          T, M         T ,RS       N, Yes    Yes

NetNamedPipeBinding              .NET          T            T, N        N, Yes    Yes

NetPeerTcpBinding                Peer          T            N           N         Yes

NetMsmqBinding                   .NET          T, M, X      N           N, Yes    No

MsmqIntegrationBinding           MSMQ          T            N           N, Yes    n/a

          N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions
New bindings in WCF.net 3.5
 ws2007HttpBinding
 ws2007FederationBinding
Supported Features of Each Binding
Choose a binding that suits your need
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
Bindings & Behaviors: Reliable Sessions
  Client                                              Service
                                          A   B   C

           C   B   A                      A   B   C

                                          A   B   C


                       Bindings provide
                         Session and
                         Guarantees


Reliable Messaging: in-order and exactly once (similar to
MSMQ and MQSeries guarantees).
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
                         AutoComplete

1- Multistep business process : Long running transaction WF integrates with
WCF
2- Short running transaction
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>
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>
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>
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>
WCF returns JSON
JSON short for JavaScript Object Notation, is a lightweight computer data interchange
format. It is a text-based, human-readable format for representing simple data structures
and 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>
Service Behaviors:
Instance and Concurrency
       Management
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.
Per Session




One service instance for one session
Per Call




One instance for each call, even a call from same client
Singleton Instance
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.
WCF Security
 Authentication
 Authorization
 Confidentiality
 Integrity
 Transport and Message Security
 Please look at
  http://wcfsecurityguide.codeplex.com/
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
                                                               ReceiveActivity
App.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
        OperationBehavior
WorkflowOperationBehavior
WorkflowOperationBehavior
StockTrader.net: a good WCF example
http://msdn.microsoft.com/en-us/netframework/bb499684.aspx
New features in WCF 4.0
Windows Communication Foundation (WCF) in .NET 4 includes three new
features 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.
Demo
1.   Simplified Configuration
2.   Service Discovery
3.   Service Routing
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
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/
Q&A

More Related Content

What's hot

10 Tricks and Tips for WCF
10 Tricks and Tips for WCF10 Tricks and Tips for WCF
10 Tricks and Tips for WCFBarry Dorrans
 
Introduction to WCF
Introduction to WCFIntroduction to WCF
Introduction to WCFybbest
 
Wcf architecture overview
Wcf architecture overviewWcf architecture overview
Wcf architecture overviewArbind Tiwari
 
REST, JSON and RSS with WCF 3.5
REST, JSON and RSS with WCF 3.5REST, JSON and RSS with WCF 3.5
REST, JSON and RSS with WCF 3.5Rob Windsor
 
WCF tutorial
WCF tutorialWCF tutorial
WCF tutorialAbhi Arya
 
Building RESTful Services with WCF 4.0
Building RESTful Services with WCF 4.0Building RESTful Services with WCF 4.0
Building RESTful Services with WCF 4.0Saltmarch Media
 
introduction to Windows Comunication Foundation
introduction to Windows Comunication Foundationintroduction to Windows Comunication Foundation
introduction to Windows Comunication Foundationredaxe12
 
Beginning with wcf service
Beginning with wcf serviceBeginning with wcf service
Beginning with wcf serviceBinu Bhasuran
 
1. WCF Services - Exam 70-487
1. WCF Services - Exam 70-4871. WCF Services - Exam 70-487
1. WCF Services - Exam 70-487Bat Programmer
 
Session 1: The SOAP Story
Session 1: The SOAP StorySession 1: The SOAP Story
Session 1: The SOAP Storyukdpe
 
Web services, WCF services and Multi Threading with Windows Forms
Web services, WCF services and Multi Threading with Windows FormsWeb services, WCF services and Multi Threading with Windows Forms
Web services, WCF services and Multi Threading with Windows FormsPeter Gfader
 
Advancio, Inc. Academy: Web Sevices, WCF & SOAPUI
Advancio, Inc. Academy: Web Sevices, WCF & SOAPUIAdvancio, Inc. Academy: Web Sevices, WCF & SOAPUI
Advancio, Inc. Academy: Web Sevices, WCF & SOAPUIAdvancio
 
Session 1 Shanon Richards-Exposing Data Using WCF
Session 1 Shanon Richards-Exposing Data Using WCFSession 1 Shanon Richards-Exposing Data Using WCF
Session 1 Shanon Richards-Exposing Data Using WCFCode Mastery
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIKevin Hazzard
 
Service Oriented Development With Windows Communication Foundation 2003
Service Oriented Development With Windows Communication Foundation 2003Service Oriented Development With Windows Communication Foundation 2003
Service Oriented Development With Windows Communication Foundation 2003Jason Townsend, MBA
 

What's hot (20)

WCF Fundamentals
WCF Fundamentals WCF Fundamentals
WCF Fundamentals
 
Wcf development
Wcf developmentWcf development
Wcf development
 
10 Tricks and Tips for WCF
10 Tricks and Tips for WCF10 Tricks and Tips for WCF
10 Tricks and Tips for WCF
 
Introduction to WCF
Introduction to WCFIntroduction to WCF
Introduction to WCF
 
Windows Communication Foundation (WCF) Best Practices
Windows Communication Foundation (WCF) Best PracticesWindows Communication Foundation (WCF) Best Practices
Windows Communication Foundation (WCF) Best Practices
 
WCF And ASMX Web Services
WCF And ASMX Web ServicesWCF And ASMX Web Services
WCF And ASMX Web Services
 
Wcf architecture overview
Wcf architecture overviewWcf architecture overview
Wcf architecture overview
 
REST, JSON and RSS with WCF 3.5
REST, JSON and RSS with WCF 3.5REST, JSON and RSS with WCF 3.5
REST, JSON and RSS with WCF 3.5
 
WCF tutorial
WCF tutorialWCF tutorial
WCF tutorial
 
WCF for begineers
WCF  for begineersWCF  for begineers
WCF for begineers
 
Building RESTful Services with WCF 4.0
Building RESTful Services with WCF 4.0Building RESTful Services with WCF 4.0
Building RESTful Services with WCF 4.0
 
introduction to Windows Comunication Foundation
introduction to Windows Comunication Foundationintroduction to Windows Comunication Foundation
introduction to Windows Comunication Foundation
 
Beginning with wcf service
Beginning with wcf serviceBeginning with wcf service
Beginning with wcf service
 
1. WCF Services - Exam 70-487
1. WCF Services - Exam 70-4871. WCF Services - Exam 70-487
1. WCF Services - Exam 70-487
 
Session 1: The SOAP Story
Session 1: The SOAP StorySession 1: The SOAP Story
Session 1: The SOAP Story
 
Web services, WCF services and Multi Threading with Windows Forms
Web services, WCF services and Multi Threading with Windows FormsWeb services, WCF services and Multi Threading with Windows Forms
Web services, WCF services and Multi Threading with Windows Forms
 
Advancio, Inc. Academy: Web Sevices, WCF & SOAPUI
Advancio, Inc. Academy: Web Sevices, WCF & SOAPUIAdvancio, Inc. Academy: Web Sevices, WCF & SOAPUI
Advancio, Inc. Academy: Web Sevices, WCF & SOAPUI
 
Session 1 Shanon Richards-Exposing Data Using WCF
Session 1 Shanon Richards-Exposing Data Using WCFSession 1 Shanon Richards-Exposing Data Using WCF
Session 1 Shanon Richards-Exposing Data Using WCF
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
 
Service Oriented Development With Windows Communication Foundation 2003
Service Oriented Development With Windows Communication Foundation 2003Service Oriented Development With Windows Communication Foundation 2003
Service Oriented Development With Windows Communication Foundation 2003
 

Viewers also liked

Twitter Bootstrap Presentation
Twitter Bootstrap PresentationTwitter Bootstrap Presentation
Twitter Bootstrap PresentationDuy Do Phan
 
BlackBerry Basic
BlackBerry BasicBlackBerry Basic
BlackBerry BasicDuy Do Phan
 
1. PCI Compliance Overview
1. PCI Compliance Overview1. PCI Compliance Overview
1. PCI Compliance Overviewokrantz
 
Introduction to PCI DSS
Introduction to PCI DSSIntroduction to PCI DSS
Introduction to PCI DSSSaumya Vishnoi
 
PCI DSS Simplified: What You Need to Know
PCI DSS Simplified: What You Need to KnowPCI DSS Simplified: What You Need to Know
PCI DSS Simplified: What You Need to KnowAlienVault
 
Work life balance
Work life balanceWork life balance
Work life balanceDuy Do Phan
 
Work life balance issues- How to deal with it.
Work life balance issues- How to deal with it.Work life balance issues- How to deal with it.
Work life balance issues- How to deal with it.Sandipan Samaddar
 

Viewers also liked (11)

Twitter Bootstrap Presentation
Twitter Bootstrap PresentationTwitter Bootstrap Presentation
Twitter Bootstrap Presentation
 
PCI DSS
PCI DSSPCI DSS
PCI DSS
 
BlackBerry Basic
BlackBerry BasicBlackBerry Basic
BlackBerry Basic
 
SSL
SSLSSL
SSL
 
1. PCI Compliance Overview
1. PCI Compliance Overview1. PCI Compliance Overview
1. PCI Compliance Overview
 
Introduction to PCI DSS
Introduction to PCI DSSIntroduction to PCI DSS
Introduction to PCI DSS
 
PCI DSS Simplified: What You Need to Know
PCI DSS Simplified: What You Need to KnowPCI DSS Simplified: What You Need to Know
PCI DSS Simplified: What You Need to Know
 
Requirement of PCI-DSS in India.
Requirement of PCI-DSS in India.Requirement of PCI-DSS in India.
Requirement of PCI-DSS in India.
 
PCI DSS 3.2
PCI DSS 3.2PCI DSS 3.2
PCI DSS 3.2
 
Work life balance
Work life balanceWork life balance
Work life balance
 
Work life balance issues- How to deal with it.
Work life balance issues- How to deal with it.Work life balance issues- How to deal with it.
Work life balance issues- How to deal with it.
 

Similar to WCF

Complete Architecture and Development Guide To Windows Communication Foundati...
Complete Architecture and Development Guide To Windows Communication Foundati...Complete Architecture and Development Guide To Windows Communication Foundati...
Complete Architecture and Development Guide To Windows Communication Foundati...Abdul Khan
 
Tulsa Tech Fest2008 Service Oriented Development With Windows Communication F...
Tulsa Tech Fest2008 Service Oriented Development With Windows Communication F...Tulsa Tech Fest2008 Service Oriented Development With Windows Communication F...
Tulsa Tech Fest2008 Service Oriented Development With Windows Communication F...Jason Townsend, MBA
 
Service Oriented Development With Windows Communication Foundation Tulsa Dnug
Service Oriented Development With Windows Communication Foundation   Tulsa DnugService Oriented Development With Windows Communication Foundation   Tulsa Dnug
Service Oriented Development With Windows Communication Foundation Tulsa DnugJason Townsend, MBA
 
Dot Net Training Wcf Dot Net35
Dot Net Training Wcf Dot Net35Dot Net Training Wcf Dot Net35
Dot Net Training Wcf Dot Net35Subodh Pushpak
 
Understanding Web Services by software outsourcing company india
Understanding Web Services by software outsourcing company indiaUnderstanding Web Services by software outsourcing company india
Understanding Web Services by software outsourcing company indiaJignesh Aakoliya
 
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)Jorgen Thelin
 
A presentation on WCF & REST
A presentation on WCF & RESTA presentation on WCF & REST
A presentation on WCF & RESTSanthu Rao
 
Basics of WCF and its Security
Basics of WCF and its SecurityBasics of WCF and its Security
Basics of WCF and its SecurityMindfire Solutions
 
Top wcf interview questions
Top wcf interview questionsTop wcf interview questions
Top wcf interview questionstongdang
 
WCF and WF in Framework 3.5
WCF and WF in Framework 3.5WCF and WF in Framework 3.5
WCF and WF in Framework 3.5ukdpe
 
Windows communication foundation ii
Windows communication foundation iiWindows communication foundation ii
Windows communication foundation iiSwamy Gowtham
 
Web services
Web servicesWeb services
Web servicesaspnet123
 
Windows Communication Foundation
Windows Communication FoundationWindows Communication Foundation
Windows Communication FoundationMahmoud Tolba
 
WINDOWS COMMUNICATION FOUNDATION
WINDOWS COMMUNICATION FOUNDATIONWINDOWS COMMUNICATION FOUNDATION
WINDOWS COMMUNICATION FOUNDATIONDeepika Chaudhary
 
Service mesh in action with onap
Service mesh in action with onapService mesh in action with onap
Service mesh in action with onapHuabing Zhao
 

Similar to WCF (20)

Complete Architecture and Development Guide To Windows Communication Foundati...
Complete Architecture and Development Guide To Windows Communication Foundati...Complete Architecture and Development Guide To Windows Communication Foundati...
Complete Architecture and Development Guide To Windows Communication Foundati...
 
Tulsa Tech Fest2008 Service Oriented Development With Windows Communication F...
Tulsa Tech Fest2008 Service Oriented Development With Windows Communication F...Tulsa Tech Fest2008 Service Oriented Development With Windows Communication F...
Tulsa Tech Fest2008 Service Oriented Development With Windows Communication F...
 
Service Oriented Development With Windows Communication Foundation Tulsa Dnug
Service Oriented Development With Windows Communication Foundation   Tulsa DnugService Oriented Development With Windows Communication Foundation   Tulsa Dnug
Service Oriented Development With Windows Communication Foundation Tulsa Dnug
 
Windows Communication Foundation
Windows Communication FoundationWindows Communication Foundation
Windows Communication Foundation
 
Dot Net Training Wcf Dot Net35
Dot Net Training Wcf Dot Net35Dot Net Training Wcf Dot Net35
Dot Net Training Wcf Dot Net35
 
Understanding Web Services by software outsourcing company india
Understanding Web Services by software outsourcing company indiaUnderstanding Web Services by software outsourcing company india
Understanding Web Services by software outsourcing company india
 
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
Overview of Windows Vista Devices and Windows Communication Foundation (WCF)
 
Net Services
Net ServicesNet Services
Net Services
 
A presentation on WCF & REST
A presentation on WCF & RESTA presentation on WCF & REST
A presentation on WCF & REST
 
07 advanced topics
07 advanced topics07 advanced topics
07 advanced topics
 
Basics of WCF and its Security
Basics of WCF and its SecurityBasics of WCF and its Security
Basics of WCF and its Security
 
Top wcf interview questions
Top wcf interview questionsTop wcf interview questions
Top wcf interview questions
 
WCF and WF in Framework 3.5
WCF and WF in Framework 3.5WCF and WF in Framework 3.5
WCF and WF in Framework 3.5
 
Windows communication foundation ii
Windows communication foundation iiWindows communication foundation ii
Windows communication foundation ii
 
Wcf faq
Wcf faqWcf faq
Wcf faq
 
Web services
Web servicesWeb services
Web services
 
Windows Communication Foundation
Windows Communication FoundationWindows Communication Foundation
Windows Communication Foundation
 
WINDOWS COMMUNICATION FOUNDATION
WINDOWS COMMUNICATION FOUNDATIONWINDOWS COMMUNICATION FOUNDATION
WINDOWS COMMUNICATION FOUNDATION
 
Service mesh in action with onap
Service mesh in action with onapService mesh in action with onap
Service mesh in action with onap
 
WCF 4 Overview
WCF 4 OverviewWCF 4 Overview
WCF 4 Overview
 

More from Duy Do Phan

Location based AR & how it works
Location based AR & how it worksLocation based AR & how it works
Location based AR & how it worksDuy Do Phan
 
Linux Introduction
Linux IntroductionLinux Introduction
Linux IntroductionDuy Do Phan
 
Cryptography Fundamentals
Cryptography FundamentalsCryptography Fundamentals
Cryptography FundamentalsDuy Do Phan
 
Android Programming Basic
Android Programming BasicAndroid Programming Basic
Android Programming BasicDuy Do Phan
 
SMS-SMPP-Concepts
SMS-SMPP-ConceptsSMS-SMPP-Concepts
SMS-SMPP-ConceptsDuy Do Phan
 
One minute manager
One minute managerOne minute manager
One minute managerDuy Do Phan
 

More from Duy Do Phan (8)

Location based AR & how it works
Location based AR & how it worksLocation based AR & how it works
Location based AR & how it works
 
Linux Introduction
Linux IntroductionLinux Introduction
Linux Introduction
 
Iso8583
Iso8583Iso8583
Iso8583
 
Cryptography Fundamentals
Cryptography FundamentalsCryptography Fundamentals
Cryptography Fundamentals
 
Android Programming Basic
Android Programming BasicAndroid Programming Basic
Android Programming Basic
 
iOS Basic
iOS BasiciOS Basic
iOS Basic
 
SMS-SMPP-Concepts
SMS-SMPP-ConceptsSMS-SMPP-Concepts
SMS-SMPP-Concepts
 
One minute manager
One minute managerOne minute manager
One minute manager
 

WCF

  • 1. Yellow Pepper Mobile Financial Solutions Window Communication Foundation August 2010 Presenter: Mai Phi Long
  • 2. Agenda – Overview – WCF Architecture – WCF Configuration and Hosting – End Point (ABC) – Contacts – Binding – Service Behaviors – New features in WCF 4.0
  • 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. 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. Before WCF  Remote Procedure Call  COM+  .NET Remoting  ASP.net web service  Hard code TCP Socket  MSMQ …
  • 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
  • 10. WCF Architecture Application … Error Metadata Instance Service 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. WCF Architecture: Messaging Runtime Service Contract Client and Dispatcher Behaviors Protocol(s) Protocol(s) Encoder Binding Encoder Transport Transport Address
  • 12. WCF Architecture: Composition & Behaviors Formatter Transaction Security TCP Behavior Behavior Channel Transport Service 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. 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)
  • 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. Implement WCF in code ServiceHost serviceHost = new ServiceHost(typeof(StockService), new Uri("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> to terminate.nn"); Console.ReadLine(); // Close the ServiceHostBase to shutdown the service. serviceHost.Close();
  • 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. Demo  Self Hosting  IIS Hosting  Windows Service
  • 22. Endpoints Client Service Endpoint Endpoint Message Endpoint The service endpoint contains the information about the Address, Binding, Contract, and Behavior required by a client to find and interact with the service at this endpoint.
  • 23. Address, Binding, Contract Client Service A B C C B A Message A B C Address Binding Contract (Where) (How) (What)
  • 24. How client knows WCF service  mex Metadata tells client how to connect & communicate to web service. Design time, client sends request defined in WS-Metadata exchange standard and get WSDL in return. WSDL is then used to create proxy class and create config file at client
  • 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 false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
  • 26. Some tools to debug, and test WCF WCF Test Client WCF Service Configuration Editor
  • 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. Service Contract using System.ServiceModel; [ServiceContract] public interface ICalculate { [OperationContract] double Add( double a, double b); [OperationContract] double Subtract( double a, double b); }
  • 30. Synchronous vs Asynchronous Request Response Main 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. Service Contract: OneWay [ OperationContract(IsOneWay = true)] void DoBigAnalysisFast(string ticker); [OperationContract] void DoBigAnalysisSlow(string ticker); The client just needs acknowledgement of successful delivery; it does not need an actual response from the service
  • 32. Duplex Communication Use wsDualHttpBinding Since two endpoints are used, we can define two different bindings, protocol for each channels
  • 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. Service Contract: Duplex Symmetric [ServiceContract(Session=true, CallbackContract=typeof(IChat)] public interface IChat { [OperationContract(IsOneWay=true)] void Talk(string text); }
  • 35. Demo  Request –Reply  One Way  One Service many EndPoints
  • 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. Demo  Basic data type data contract  Class data type data contract  Hierarchy data type data contract  Collection data contract
  • 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. Message Contract [MessageContract] public class ComplexProblem { [MessageHeader] public string operation; [MessageBody] public ComplexNumber n1; [MessageBody] public ComplexNumber n2; [MessageBody] public ComplexNumber solution; // Constructors… }
  • 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. Standard Bindings in WCF.net 3.0 Binding Interop Security Session TX Duplex BasicHttpBinding BP 1.1 N, T N N n/a WSHttpBinding WS M, T, X N, T, RS N, Yes n/a WSDualHttpBinding WS M RS N, Yes Yes WSFederationBinding Federation M N, RS N, Yes No NetTcpBinding .NET T, M T ,RS N, Yes Yes NetNamedPipeBinding .NET T T, N N, Yes Yes NetPeerTcpBinding Peer T N N Yes NetMsmqBinding .NET T, M, X N N, Yes No MsmqIntegrationBinding MSMQ T N N, Yes n/a N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions
  • 43. New bindings in WCF.net 3.5  ws2007HttpBinding  ws2007FederationBinding
  • 44. Supported Features of Each Binding
  • 45. Choose a binding that suits your need
  • 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. Bindings & Behaviors: Reliable Sessions Client Service A B C C B A A B C A B C Bindings provide Session and Guarantees Reliable Messaging: in-order and exactly once (similar to MSMQ and MQSeries guarantees).
  • 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 AutoComplete 1- Multistep business process : Long running transaction WF integrates with WCF 2- Short running transaction
  • 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. 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. 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. 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. WCF returns JSON JSON short for JavaScript Object Notation, is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and 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. Service Behaviors: Instance and Concurrency Management
  • 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. Per Session One service instance for one session
  • 57. Per Call One instance for each call, even a call from same client
  • 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. WCF Security  Authentication  Authorization  Confidentiality  Integrity  Transport and Message Security  Please look at http://wcfsecurityguide.codeplex.com/
  • 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 ReceiveActivity App.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 OperationBehavior WorkflowOperationBehavior WorkflowOperationBehavior
  • 62. StockTrader.net: a good WCF example http://msdn.microsoft.com/en-us/netframework/bb499684.aspx
  • 63. New features in WCF 4.0 Windows Communication Foundation (WCF) in .NET 4 includes three new features 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. Demo 1. Simplified Configuration 2. Service Discovery 3. Service Routing
  • 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. 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. Q&A

Editor's Notes

  1. Speaker Notes These are what we refer to as the three pillars of WCF . They are the three design goals of WCF that really sum up what that technology is all about. They ’re what we’ll be drilling into for the remainder of this presentation. The first design goal is unification . When we talk about unification, we ’re talking about bringing together the various technologies available today for building distributed applications (COM+ and .NET Enterprise services, MSMQ, .NET Remoting, ASP.NET Web Services, Web Services Enhancements (WSE)) into a single, unified programming model. Why is this important? First, it reduces complexity by allowing us to focus on a single programming model rather than learn multiple programming models. Second, it allows us to compose/combine the functionality of today ’s technologies in ways that we can’t today. Finally, it allows us to use a single programming model for building distributed applications that communicate with one another on a single machine, across multiple machines, and across the Internet. The second design goal is interoperability and integration . We talk about interoperability and integration on two different pivots. First, WCF enables you to build services that speak advanced Web services protocols (WS-*), enabling your application to communicate with other WS-* compliant services running on other platforms. Second, we built WCF to provide a smooth upgrade and interop story for your distributed applications built on today ’s technologies (WSE, ASMX, .NET Enterprise Services, System.Messaging, .NET Remoting). Why are Interop and Integration important? First, the ability to communicate with applications running on other platforms provides you with the flexibility you need when working in a heterogeneous environment. Second, the ability to communicate with existing applications protects your investments and provides you with an optional, incremental upgrade path to WCF. The third design goal is all about productivity and service orientation . WCF provides developers with a highly productive programming model for building service-oriented applications. By using WCF ’s attribute-based programming to define your services, you can dramatically reduce the amount of code you write to build secure, reliable services. WCF also facilitates the development of applications that adhere to the “four tenets of service-orientation” that we’ll drill into later in the presentation. These tenets help ensure that your services are extremely flexible and resilient to change, thereby reducing long-term maintenance costs. Transition to next slide: We ’ll spend the rest of this presentation drilling into these 3 concepts, but before doing so, let’s quickly discuss some of the basics of WCF… 4 Tenets of service oriented: Boundaries Are Explicit Services Are Autonomous Services Share Schema and Contract, Not Class Service Compatibility Is Based Upon Policy
  2. Consistency and Write less code when using multiple technologies: using System.ServiceModel for all distributed technologies in .NET 3.5 WCF, in .NET 2.0 using System.Runtime.Remoting for .net remoting, using System.Web.Service for web service …
  3. Speaker Notes Here&apos;s a roll-up of everything we&apos;ve been talking about. At the bottom of the WCF architecture, we have the hosting environments and service activation (How to spin up WCF services within a process) Above that we have the Messaging layer for moving messages around on the wire. One aspect of the Messaging layer that we didn ’t previously discuss is the message encoders. There are two types of Encoders for messages being sent from WCF services - Text/XML and Binary. If you use the HTTP protocol in conjunction with the Text/XML encoder, you get interoperability with other platforms. This is the default encoding/protocol combination. Of course, there are also optimizations that WCF services intelligently implement. For example, if an WCF service realizes that it’s communicating with another WCF service, it will use the Binary encoder to shrink packet size before sending it across the wire. The Service Model provides the API. Transition to next slide: Now that we ’ve discussed the first pillar of WCF (Unification of the architecture), let’s discuss the second – Interoperability and Integration…
  4. Speaker Notes Let ’s take a closer look at how WCF services work using both the messaging layer and the Service Model. In this example, we ’ll see how incoming messages to an WCF service get processed before they reach our user code and then how outgoing messages get processed before being sent across the wire. We ’ll begin with the Messaging layer. The Messaging layer basically works by Taking messages in from the wire, Adding transfer semantics (called Channels ) Passing the messages on for additional processing. This flexible architecture allows you to chain multiple channels together. For example, if we want to send and receive our messages using the TCP transport, we have a channel called the TCP transport channel that allows you to do this. Once the TCP transport channel processes an inbound message, it simply hands off the message to next level in the processing chain. This “next level” could either be your application code or another channel . So if you want end-to-end interoperable SOAP-based security, you ’d simply stack a Security channel on top. This secures outbound messages before handing off to TCP and validates incoming messages before handing back to your application. From there we get to the Service Model layer. This layer bridges the gap between the messaging layer and our user code that implement the WCF service. Just as the messaging layer has the stackable concept of Channels, the Service model layer has a stackable concept called Behaviors. For example, there is a CLR Type Integration behavior. This takes an incoming message and figures out what method to call in order to dispatch it. In other words, this behavior takes an incoming XML Infoset - looks for &quot;action=foo&quot;, &quot;parameter=bar&quot; and figures out what method to call. Of course, if you want, you can also just pass the message through to your code directly if you want to manipulate the XML yourself. The Transaction Behavior pulls the transaction out of the message and enlists in the transaction for you so when your code is called you are in the right transaction context. The Instancing Behavior allows you to choose if you want a new instance of your service with every call, or if you ’d like to use a singleton, as well as options that keep the same instance per session. Transition to next slide: There&apos;s a whole bunch of behaviors and channels. Let&apos;s look at them in action…
  5. Demo: WCF\\SomeWebServices\\SimpleService\\Config\\Service
  6. Demo: WCF\\SomeWebServices\\SimpleService\\Config\\Service
  7. Note that boundaries are explicit. WCF will only publish methods that are decorated as part of the service. Note that this can be declared inline on a class instance as well. This does not require that the end user declare the service contract via an interface.
  8. Demo: WCF\\03_OneWay
  9. The operations of the contracts shown in the previous code examples accept only simple types as parameters and the return values are also simple types. If you are dealing with parameter lists of that sort, it is likely that you will—for the most part—ignore the fact that the data you are exchanging between services is serialized from its in-memory object representation into an XML information set and subsequently encoded for the wire transfer (and vice versa, of course). If you are dealing with predefined WSDL documents or if you want to use complex types as arguments, you need to give a little more consideration to the &quot;data contract&quot;, however. While a service contract defines the shape and rules for interfaces (portTypes), along with their associated messages and operations, the data contract defines the shape and rules for the data that is exchanged through operation&apos;s input and output messages. The split between the data contract and the service contract is important. Service contracts typically define a logically and semantically related set of operations grouped on an interface and are about how a service behaves. The data contract defined information items that you flow across service boundaries and that are handled with additional logic on the provider and consumer side. If you were looking at it from a (English language) grammar perspective, you could consider operations to be the predicates and the data that flows are the objects , while the caller is the subject . Subjects can do a lot with objects. Every &quot;do&quot; is an operation.
  10. Demo: WCF\\Contracts\\HRService
  11. SO principles mean that designers should plan to exchange messages rather than procedure calls. The two styles of developing using WCF are RPC style where messages are generated using traditional procedure calls, but another mode of operation is available to users where they are cognizant of the messages being generated and want to control the SOAP encapsulation of the content that is being generated. Defining a message contract on a service means that the end user
  12. Speaker Notes When we talk about reliable messaging (RM), we ’re talking about a guarantee that a message actually gets from one service to another (retrying on failed attempts until success). WCF supports two RM guarantees: in-order and exactly once (similar to MSMQ and MQSeries guarantees). “In order” guarantees ensure that messages received are done so in the order in which they are sent. Exactly once guarantees ensure that each message is received only once. There are also two modes for doing RM: an express lightweight mode in which messages are not stored to disk before sending; and a transacted mode in which messages are durably stored to disk before sending. In the case of machine failure, express mode services would lose any messages in the buffer at the time of failure. When you truly need classic, atomic two-phase commit across two services, WCF also supports transactions. This provides the ability to flow a transaction across service boundaries, for and all participants to enlist in the transaction, vote on the outcome, and succeed or fail together atomically. It ’s also important to point out that security, RM, and transaction support are all configured by default to communicate using Web Services specification-compliant protocols (WS-Security, WS-ReliableMessaging, WS-AtomicTransaction, etc). This provides a new level of integration between services built on our platform and built on other vendor&apos;s platforms (WebSphere, etc). Transition to next slide: Now that we ’ve discussed a broad range of WCF-supported features, let’s look at how WCF services are hosted and activated…
  13. Demo: WCF\\GadgetDemo_WCFReturnJSON
  14. Very good article http://mkdot.net/blogs/dejan/archive/2008/04/29/wcf-service-behaviors-instance-and-concurrency-management.aspx