SlideShare a Scribd company logo
#111
 Get More Refcardz! Visit refcardz.com



                                                                   CONTENTS INCLUDE:
                                                                        About WCF
                                                                                                                          Getting Started with
                                                                   n	


                                                                   n	
                                                                        Configuration Overview
                                                                        WCF Contracts
                                                                                                         Windows Communication Foundation 4.0
                                                                   n	


                                                                   n	
                                                                        Bindings
                                                                   n	
                                                                        Behaviors
                                                                        Hosted Services and more...
                                                                                                                                                                                                                             By Scott Seely
                                                                   n	




                                                                                                                                                                   diagnostics                  Diagnostic settings for WCF, including WMI, performance
                                                                            ABOUT WCF                                                                                                           counter, message filters, and other settings.

                                                                                                                                                                   extensions                   Defines configuration extensions for the bindings, behaviors,
                                                                   Since .NET 3.0, Windows Communication Foundation (WCF) is the                                                                bindingElement (for extending CustomBinding configuration),
                                                                                                                                                                                                and standardEndpoints.
                                                                   preferred messaging system in .NET applications. It provides an
                                                                   abstraction layer over transports. This abstraction allows developers                           machineSettings              Allows the user to log personally identifiable information
                                                                   to focus on the types of messages their applications need to send                                                            in traces and message logs via the XML attribute,
                                                                                                                                                                                                enableLoggingKnownPii. This section can only be edited in
                                                                   and receive. It removes the need for developers to have intimate                                                             machine.config, located in the framework directory.
                                                                   knowledge of how the messages themselves are sent and received.
                                                                                                                                                                   protocolMapping              Used to map a protocol to a binding for easier configuration.
                                                                   Instead, developers focus on a concept called an endpoint which                                 serviceHostingEnvironment    Used to configure services hosted in ASP.NET.
                                                                   listens for and receives messages. Endpoints are built using three
                                                                                                                                                                   services                     Defines which contracts a service instance will listen for
                                                                   items: Address, Binding, and Contract.                                                                                       messages on and any base addresses the service will use. A
                                                                                                                                                                                                service may also add metadata and discovery endpoints via this
                                                                   The address defines where a message is sent.                                                                                 mechanism.
                                                                   http://www.dzone.com/ is an address.
                                                                                                                                                                   standardEndpoints            Contains configuration for endpoints specified by the kind
                                                                                                                                                                                                attribute on any service endpoint configuration.
 www.dzone.com




                                                                   A binding describes how to send the message. The binding
                                                                   contains information such as the transport to use, how to encode                                routing                      Provides message routes that a routing service uses to move
                                                                                                                                                                                                messages closer to its final destination.
                                                                   messages, and security requirements.
                                                                                                                                                                   tracking                     Defines tracking settings for a workflow service.
                                                                   A contract defines how a message is structured. The contract
                                                                   defines the message exchange pattern (MEP) used for each
                                                                   exchange as well as which messages initiate a conversation or stop a                                WCF CONTRACTS
                                                                   conversation. All message exchanges fall into one of three message
                                                                   exchange patterns, or MEPs: one-way, request-response, and
                                                                   duplex. One-way messages can act as event notifications. Request-                              WCF developers create two types of contracts: service contracts
                                                                   response messages send some data and expect a response in a                                    and data contracts. Service contracts inform the WCF runtime how
                                                                   particular format. Duplex messages are a conversation. In duplex,                              to read, write, and dispatch received messages. Data contracts
                                                                   when one caller initiates a conversation, that caller promises to                              inform the serialization infrastructure how to translate CLR objects
                                                                   make a set of one-way and request-response messages available to                               to and from an XML Infoset representation.
                                                                   the callee. Typically, duplex MEPs make use of sessions as well.
                                                                                                                                                                  Service Contracts
       Getting Started with Windows Communication Foundation 4.0




                                                                                                                                                                  The WCF runtime creates the infrastructure to host services and
                                                                            CONFIGURATION OVERVIEW                                                                dispatch messages. Developers declare the pieces of infrastructure
                                                                                                                                                                  they need by marking up classes with attributes. The WCF runtime
                                                                   Configuration is a big feature in WCF. It permeates much of the                                then uses this information to allow for communication with callers
                                                                   messaging framework. This section provides a map of configuration.                             and the hosted classes. This information is also shared via Web
                                                                   The configuration section group, <system.configuration>,                                       Services Description Language (WSDL) that WCF services can
                                                                   contains all WCF configuration settings. Within this configuration                             generate. To declare a class or interface represents the contract for
                                                                   section group, 14 different configuration sections exist. Some                                 a WCF service, mark the class with [ServiceContract].
                                                                   of those sections have relationships with other sections. One,
                                                                   system.serviceModel/extensions, is a configuration section for
                                                                   configuration only!

                                                                        behaviors           Contains configuration for shared behaviors that can be applied
                                                                                                                                                                                               Get over 90 DZone Refcardz
                                                                        bindings
                                                                                            to endpoints and services.

                                                                                            Contains information for shared bindings used to create
                                                                                                                                                                                                  FREE from Refcardz.com!
                                                                                            message processing pipelines. A computer program that can
                                                                                            run independently and can propagate a complete working
                                                                                            version of itself onto other hosts on a network.

                                                                        client              Contains information for clients to communicate with services.
                                                                                            Lookups are performed using a two part key: the name of the
                                                                                            configuration and the name of the contract.

                                                                        comContracts        An integration point used between COM+ and WCF to
                                                                                            configure the name and namespace for any hosted services.
                                                                                            This mimics the functionality normally provided by the
                                                                                            [ServiceContract] attribute via the Name and Namespace
                                                                                            properties.

                                                                        commonBehaviors     Defines a collection of behaviors applied to all services and
                                                                                            endpoints. These behaviors add to any others already present
                                                                                            on a service.



                                                                                                                                               DZone, Inc.    |   www.dzone.com
2
                                                                                                                        Getting Started with Windows Communication Foundation 4.0




 [System.ServiceModel.ServiceContract]                                                                         The commonly set properties on [DataContract] are:
 public interface IMyService {
 }
                                                                                                                Namespace          Defines the URL used as the targetNamespace in the XSD describing the
                                                                                                                                   type and used when serializing the data contract as an XML Infoset.
Through [ServiceContract], you will normally set the following
                                                                                                                Name               Defines the name of the item when read and written to an XML Infoset.
properties about the collection of operations on the service:
                                                                                                               The commonly set properties on [DataMember] are:
 Namespace             Sets the default namespace for the XML Schema Documents (XSD) for the
                       request and response messages. Default is http://tempuri.org.
                                                                                                                Name                  Defines the name of the item when read and written to an XML Infoset.
 SessionMode           One of three values: Allowed, Required, NotAllowed. By default,
                                                                                                                IsRequired            Set to true if the field must be present when the type is deserialized.
                       SessionMode is Allowed. If your contract requires session semantics,
                       set this value to System.ServiceModel.SessionMode.Required. If your                                            Default value is false.
                       contract will fail with sessions, set it to System.ServiceModel.SessionMode.
                       NotAllowed.                                                                              EmitDefaultValue      Indicates whether or not to write the member when set to the default
                                                                                                                                      value. The default value of this member is true.

 CallbackContract      CallbackContract: If the contract implements a duplex MEP, set this to the               Order                 An integer used to alter the ordering of values when read or written.
                       interface representing the other side of the duplex conversation.                                              By default, values are read and written in alphabetic order. The default
                                                                                                                                      value of Order is 0. Members with the same Order value are serialized
To make methods visible to external callers, mark the methods with                                                                    alphabetically. Order is sorted ascending.

[OperationContract].

 [System.ServiceModel.ServiceContract(
   Namespace = “http://www.dzone.com/WCF”)]
                                                                                                                   BINDINGS
 public interface IMyService
 {
   [System.ServiceModel.OperationContract]                                                                     WCF supports messaging through a messaging pipeline. The
   string SayHi(string name);
 }                                                                                                             pipeline itself must have stages that represent the transport and
                                                                                                               the serialization mechanism. In WCF, the pipeline is created by a
The commonly set properties on [OperationContract] are:                                                        type derived from System.ServiceModel.Channels.Binding and the
                                                                                                               stages are created by types derived from System.ServiceModel.
 IsOneWay           Can only be set on methods that return void. Use this to indicate that the                 Channel.BindingElement. Besides the transport and serialization
                    method does not send a response. Default is false.
                                                                                                               mechanism, the BindingElement also adds stages for security,
 IsInitiating       Use this to state that a given method can be called to instantiate a new                   reliability, and transactions. When creating a Binding, the
                    service. Default value is true.
                                                                                                               developer of the Binding decides how to surface the underlying
 IsTerminating      Use this to state that when a given method is called, the current instance can             BindingElement properties. Some settings will be easily set, others
                    be disposed. Default value is false. If this value is set to true, you must also set
                    ServiceContractAttribute.SessionMode to SessionMode.Required.                              made private, and still others surfaced as different concepts.

Your code may also return exceptions to callers. In SOAP messaging,                                            Every binding has settings for timeouts: OpenTimeout,
errors are returned as Fault messages. A given operation may                                                   ReceiveTimeout, CloseTimeout. These set the amount of time the
return zero or more faults. One declares the types of faults being                                             user of the Binding will wait for the pipeline to Open, Receive a
returned through [FaultContract]. [FaultContract] has a constructor                                            message, or Close. A Binding also identifies its URL scheme, which
that accepts a type describing what the fault details will look like.                                          is the scheme used by its transport. WCF ships with Bindings
This description is used by the callers to read any faults your service                                        supporting the following schemes: http, https, net.msmq, net.pipe,
might return.                                                                                                  net.p2p, and net.tcp. WCF also supports soap.udp, but only in an
                                                                                                               internal class used to support WS-Discovery.
 [System.ServiceModel.ServiceContract(
   Namespace = “http://www.dzone.com/WCF”)]
 public interface IMyService
 {
                                                                                                               Each of the Bindings has a common set of properties
   [System.ServiceModel.OperationContract()]                                                                   not required by the base class, Binding:
   [FaultContract(typeof(FaultDetails))]
   string SayHi(string name);
 }
                                                                                                                EnvelopeVersion        Sets the version of any SOAP Envelope. Normally, this is set to None,
                                                                                                                                       Soap11, Soap12. Use None for REST or other non-SOAP messaging;
Data Contracts                                                                                                                         Soap11 to send a SOAP 1.1 envelope and related headers; Soap12 to
WCF reads and writes objects to and from different formats using                                                                       send a SOAP 1.2 envelope and related headers.
serialization (write) and deserialization (read). WCF supports
                                                                                                                MaxBufferPoolSize      Most messages are received into memory. The buffer pool is used to
serialization through several mechanisms: System.Xml.Serialization,
                                                                                                                                       allocate memory for receiving messages. By default, each buffer in the
System.ISerializable, [System.Serializable], and through System.                                                                       pool is 65536 bytes. Adjust this value to change the size of the individual
Runtime.Serialization. The first three mechanisms exist to support                                                                     buffers.
legacy code. When developing your own declarations, you will
                                                                                                                ReaderQuotas           This sets quotas on reading inbound messages. The type,
normally use System.Runtime.Serialization to describe your data                                                                        System.Xml.XmlDictionaryReaderQuotas is found in
contracts. In WCF 4.0, an unattributed type will automatically read                                                                    System.Runtime.Serialization. The quotas set limits which limit the
and write any public fields or properties using the name of the                                                                        damage a denial of service attack or poorly formed XML document
property in the generated format. To control what gets written, mark                                                                   can do. By default, arrays can be no longer that 16384 elements
the type with [DataContract] and any members to be written with                                                                        (MaxArrayLength), strings must be less than 8192 characters
                                                                                                                                       (MaxStringContentLength), and XML nodes must be no more than 32
[DataMember].
                                                                                                                                       levels deep (MaxDepth).

 [System.Runtime.Serialization.DataContract]                                                                    Scheme                 Identifies the scheme used by the underlying transport protocol.
 public class Name
 {
   [System.Runtime.Serialization.DataMember]
   public string FirstName { get; set; }                                                                       Depending on which protocol you want to use, you have different
                                                                                                               bindings available. Most of the bindings in WCF support HTTP.
     [System.Runtime.Serialization.DataMember]
     public string LastName { get; set; }                                                                      The rest of the supported protocols are represented by one
 }
                                                                                                               binding. The following table shows which bindings support
When you explicitly mark a member with [DataMember], that                                                      duplex communications, message level security, reliable
field will be read and written regardless if the member is private,                                            messaging, flowing transactions, and workflow context. Transport
protected, or public.                                                                                          level security is available through all bindings in WCF.

                                                                                          DZone, Inc.      |   www.dzone.com
3
                                                                                              Getting Started with Windows Communication Foundation 4.0




 Binding                       Duplex   Message level   Reliable   Transactions       [ServiceBehavior] contains several properties. The most commonly
                                        security                                      used are:
 BasicHttpBinding                             *
                                                                                       ConcurrencyMode                      Controls the internal threading model to enable support
 BasicHttpContextBinding                      *
                                                                                                                            for reentrant or multithreaded services. By default,
 MsmqIntegrationBinding                                                                                                     concurrency is single threaded per instance.

 NetMsmqBinding                                                                       InstanceContextMode                  Controls how instances are created for the service. By
 NetNamedPipeBinding                                                                                                     default, each session gets a new service instance. Set
                                                                                                                            this property to PerSCall to allow for a new instance for
 NetPeerTcpBinding                                                                                                        every method call. Set this property to Single if you need
                                                                                                                            singleton behavior for the service.
 NetTcpBinding                                                       

 NetTcpContextBinding                                                              IncludeExceptionDetailsInFaults      Returns exception details to clients when debugging
                                                                                                                            services. This property requires a request-response or
 WS2007FederationHttpBinding                                                                                             duplex capable binding.
 WS2007HttpBinding                                                    

 WSDualHttpBinding                                                                [DeliveryRequirements], a contract behavior, allows a contract to
                                                                                      specify information about reliable messaging requirements imposed
 WSFederationHttpBinding                                              
                                                                                      on the service delivery.
 WSHttpBinding                                                        

 WSHttpContextBinding                                                              [CallbackBehavior], an endpoint behavior, provides configuration
                                                                                      settings for the callback contract on a duplex service. The settings
* The BasicHttpBinding and BasicHttpContextBinding will sign the                      are the same as the [ServicBehavior] except for settings for
timestamp on the message, but not sign and encrypt the body. For                      instancing and transactions.
full message level signing and encryption, use WSHttpBinding and                      In configuration, you can declare information about security,
WSHttpContextBinding.                                                                 diagnostics, discovery, and throttling.

Bindings appear in configuration in the system.serviceModel/                          WCF contains many configuration elements. Here, we focus on
bindings section under configuration that matches a camelCased                        the commonly configured behaviors for services. The following
version of the binding name. For example, the collection                              behaviors allow you to configure your service behaviors as
of WSHttpBinding can be found in system.serviceModel/
                                                                                      part of configuration within system.serviceModel/behaviors/
bindings/wsHttpBinding. Each configured binding has a
                                                                                      serviceBehaviors/:
name. A binding without a name becomes the default set of
settings for that particular binding. For example, to create a
reliable WSHttpBinding, use the following configuration:                               serviceCredentials     Allows the service to pick how it authenticates itself using X.509,
                                                                                                              Windows, username/password, and other valid tokens.

<system.serviceModel>                                                                  serviceDebug           Allows you to set up the HttpHelp page and to include exception
    <bindings>                                                                                                details in faults.
      <wsHttpBinding>
        <binding name=”reliable”>                                                      serviceDiscovery       Enables the WS-Discovery endpoint.
          <reliableSession enabled=”true”/>
        </binding>                                                                     serviceMetadata        Enables the WS-MetadataExchange endpoint.
      </wsHttpBinding>
    </bindings>
 </system.serviceModel>
                                                                                      On an endpoint, you can configure other behaviors. The following
                                                                                      commonly used behaviors allow you to configure your endpoint
                                                                                      behaviors as part of configuration within system.serviceModel/
    BEHAVIORS                                                                         behaviors/endpointBehaviors/:

Behaviors influence the hosting environment for a service. They                        callbackDebug        Allows you to state if a callback contract should include exception details
are used to handle instancing, expose metadata, enhance                                                     in faults.
discoverability, and more. There are four types of behaviors: service,                 clientCredentials    Allows the client to pick how it authenticates itself using X.509, Windows,
contract, endpoint, and operation. All behaviors may be applied                                             username/password, and other valid tokens.
in code. Service and endpoint behaviors may also be applied by                         enableWebScript      Enables a Web Script endpoint on the service. This allows the service
configuration. (Note: There is no notion of contract configuration                                          to return JavaScript when the URL end in /js or /jsdebug. This behavior
anywhere in WCF.) Service and contract behaviors are normally                                               is automatically included if using the System.ServiceModel.Activation.
applied via attributes in code.                                                                             WebScriptServiceHostFactory on a .SVC.

                                                                                       webHttp              Allows the endpoint to dispatch messages based on URL. This behavior
A service behavior applies to a service instance and may alter                                              is automatically included if using the System.ServiceModel.Activation.
aspects of the service, all endpoints, and all contracts. A contract                                        WebScriptServiceHostFactory or System.ServiceModel.Activation.
behavior applies to a contract and all implementations of the                                               WebServiceHostFactory as the factory name on a .SVC.
contract. Endpoint behaviors apply to a specific endpoint instances.
Finally, operation behaviors apply to specific operations.
                                                                                           HOSTING SERVICES
Attribute-based Behaviors
There are two service behaviors:                                                      WCF services can listen for messages anywhere: Windows
[AspNetCompatibilityRequirements] and [ServiceBehavior].                              Services, desktop applications, and Internet Information Services
[AspNetCompatibilityRequirements] has a single property,                              (IIS). All environments use the same configuration elements. In
RequirementsMode, that allows a service to declare that ASP                           all cases, an instance of a ServiceHost will be used to reflect over
features such as identity impersonation are Required, Allowed, or                     a service implementation to determine service requirements.
NotAllowed (default). When set to Required, configuration must                        The ServiceHost then marries the code with any configuration
enable compatibility too:                                                             to produce an entity that can listen for, dispatch, and respond
                                                                                      to messages that arrive over the various transports.
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled=”true”/>
  </system.serviceModel>
                                                                                      To demonstrate hosting, we use the following contract:


                                                                   DZone, Inc.    |   www.dzone.com
4
                                                                                         Getting Started with Windows Communication Foundation 4.0




 namespace DZone.Contracts                                                            private ServiceHost _host;
 {
   [System.ServiceModel.ServiceContract(                                              protected override void OnStart(string[] args)
     Namespace = “http://www.dzone.com/WCF”)]                                         {
   public interface IMyService                                                          ThreadPool.QueueUserWorkItem(StartListening, this);
   {                                                                                  }
     [System.ServiceModel.OperationContract]
     string SayHi(string name);                                                       static void StartListening(object state)
   }                                                                                  {
 }                                                                                      var service = state as DemoService;
 Implemented by the following class:                                                    if (service != null)
 namespace DZone.Services                                                               {
 {                                                                                        service._host = new ServiceHost(typeof(MyService));
   public class MyService : DZone.Contracts.IMyService                                    service._host.Faulted +=
   {                                                                                        (s, e) =>
     public string SayHi(string name)                                                       {
     {                                                                                        service.StopListening();
       return string.Format(“Console: Hello, {0}”, name);                                     service._host = null;
     }                                                                                        StartListening(service);
   }                                                                                        };
 }                                                                                      }
                                                                                      }

and use the following configuration:                                                  protected override void OnStop()
                                                                                      {
                                                                                        StopListening();
                                                                                      }
 <configuration>
   <system.serviceModel>                                                              void StopListening()
     <behaviors>                                                                      {
        <serviceBehaviors>                                                              try
          <behavior name=”MyServiceBehavior”>                                           {
            <serviceMetadata httpGetEnabled=”true”/>                                      ((IDisposable)_host).Dispose();
          </behavior>                                                                   }
        </serviceBehaviors>                                                             catch (CommunicationObjectFaultedException ex)
     </behaviors>                                                                       {
     <services>                                                                           // TODO: add code to log
        <service name=”DZone.Services.MyService”                                        }
          behaviorConfiguration=”MyServiceBehavior”>                                  }
          <host>
            <baseAddresses>
              <add baseAddress=”http://localhost/Demo”/>
            </baseAddresses>
                                                                                  The preceding code executes the initialization logic on a
          </host>                                                                 separate thread via ThreadPool.QueueUserWorkItem. The
          <endpoint contract=”DZone.Contracts.IMyService”
            binding=”basicHttpBinding” address=”/MyService”/>                     ServiceHost will run for a long time. If the ServiceHost gets
          <endpoint kind=”mexEndpoint” address=”/mex”                             into a situation where it can no longer listen for messages by
            binding=”mexHttpBinding” />
        </service>                                                                entering the Faulted state, the code should start up a new
     </services>
   </system.serviceModel>
                                                                                  instance of the ServiceHost. When the service is done listening,
 </configuration>                                                                 a CommunicationObjectFaultedException may be thrown on
                                                                                  Dispose. Because this exception is expected, the code will log
The configuration declares that there is a serviceBehavior                        the exception. When the service stops, we call StopListening. If
named MyServiceBehavior which supports metadata exchange.                         you want to support Pause and Resume, add the following:
This behavior is attached to a service instance whose name is
DZone.Services.MyService and matches the name of the service                          protected override void OnPause()
implementation. The host has a base address of http://localhost/                      {
                                                                                        StopListening();
Demo. This base address is used for any bindings that support the                       base.OnPause();
http scheme. The service exposes two endpoints. One endpoint                          }

exposes an implementation of the DZone.Contracts.IMyService                           protected override void OnContinue()
                                                                                      {
contract listening off the http base address at /MyService. The other                   ThreadPool.QueueUserWorkItem(StartListening, this);
endpoint hosts metadata exchange using a predefined binding                             base.OnContinue();
                                                                                      }
named mexHttpBinding listening off the http base address at /Mex.
                                                                                  Hosting in IIS
Hosting in a Console/GUI application
                                                                                  To host a service in IIS, you create a .svc file which is
Using this configuration, we can host the service in a
                                                                                  hosted at a path of your choosing in your web application.
Console application with the following code:
                                                                                  That will give you a file that looks like this:

 var host = new ServiceHost(typeof(MyService))
                                                                                   <%@ ServiceHost Service=”DZone.Services.MyService” %>
   host.Open();
   Console.WriteLine(“Press [Enter] to exit”);
   Console.ReadLine();                                                            The config remains largely the same. IIS will automatically set
 try
                                                                                  the http base address for the host to be the address of the
 {                                                                                .svc file.
   ((IDisposable)host).Dispose();
 }
 catch (CommunicationObjectFaultedException ex)                                   In IIS 7 and later, you can also host services with NetTcpBinding and
 {
   // TODO: add code to log                                                       NetNamedPipeBinding. To do this, run the following commands:
 }

                                                                                  TCP Activation:
Once the using block exits, host.Dispose() is called. You
can do something similar in a WinForm/WPF application by                             1. Run the following command (on one line):
opening the service on window Load and explicitly calling
ServiceHost.Dispose() when the window is closed/unloaded.                          %windir%system32inetsrvappcmd.exe set site “Default Web Site” -+bindings.
                                                                                   [protocol=’net.tcp’,bindingInformation=’808:*’]
Hosting in a Windows Service
A Windows Service requires you to be able to respond to                              2.  un the following command to enable the http and net. pipe
                                                                                        R
Start and Resume events very quickly. In order to do this, you                          protocol on your site (on one line):
do not want to block in the start if at all possible. Creating a
single WCF ServiceHost does not normally take much time.                           %windir%system32inetsrvappcmd.exe set app
However, we should always be prepared for things to take a                         “Default Web Site/[your v-dir]” /enabledProtocols:http,net.tcp
while and have the services behave nicely. To host the same
WCF service in a Windows Service, write the following code:                       Named Pipe Activation


                                                                DZone, Inc.   |   www.dzone.com
5
                                                                                                         Getting Started with Windows Communication Foundation 4.0




   1. Run the following command (on one line):                                                     var client = new DZoneService.MyServiceClient(
                                                                                                   “BasicHttpBinding_IMyService”);
                                                                                                   try
                                                                                                   {
 %windir%system32inetsrvappcmd.exe set site “Default Web Site”
                                                                                                     Console.WriteLine(client.SayHi(“DZone”));
 -+bindings.[protocol=’net.pipe’,bindingInformation=’*’]
                                                                                                   }
                                                                                                   catch (TimeoutException timeoutException)
                                                                                                   {
   2.  un the following command to enable the http and net. pipe
      R                                                                                              client.Abort();
      protocol on your site (on one line):                                                         }
                                                                                                   catch (FaultExceptionKnownFaultType faultException)
                                                                                                   {
                                                                                                     client.Abort();
 %windir%system32inetsrvappcmd.exe set app                                                      }
 “Default Web Site/[your v-dir]” /enabledProtocols:http,net.pipe                                   catch (FaultException faultException)
                                                                                                   {
                                                                                                     client.Abort();
With Vista SP1 and Server 2008, you can also enable these protocols                                }
                                                                                                   catch (CommunicationException communicationException)
in the IIS Manager.                                                                                {
                                                                                                     client.Abort();
                                                                                                   }
For the demo application, remove the host base
addresses and add in these two endpoints:
                                                                                                      DIAGNOSTICS
 endpoint contract=”DZone.Contracts.IMyService” address=”/MyService”
   binding=”netTcpBinding” /
 endpoint contract=”DZone.Contracts.IMyService” address=”/MyService”
   binding=”netNamedPipeBinding” /                                                               WCF also comes with a rich set of diagnostics information.
                                                                                                  Unlike other aspects of WCF, diagnostics can only be set in
                                                                                                  configuration. The diagnostics allows for tracing, message
OperationContext
                                                                                                  logging, WMI inspection, and performance counters.
Every incoming message is associated with an OperationContext.
Think of OperationContext as WCF’s version of HttpContext.
OperationContext.Current yields the current operation context
                                                                                                  Tracing/WMI
                                                                                                  All production applications should be deployed with System.
with pointers to the following commonly used properties:
                                                                                                  ServiceModel tracing configured but turned off. WMI
                                                                                                  should be enabled so that an administrator can enable
 IncomingMessageHeaders      Headers on the incoming message.                                     tracing through WMI. The configuration looks like this:
 OutgoingMessageHeaders      Can use this to add more headers to the response.
                                                                                                     system.diagnostics
 IncomingMessageProperties   The message properties serve as a mechanism to send                       sources
                             information in between layers within the message processing                 source name=”System.ServiceModel”
                             pipeline about a specific message.                                            switchValue=”Off”
                                                                                                           propagateActivity=”true”
                                                                                                           listeners
 ServiceSecurityContext      Gain access to the identity of the currently logged in user.                    add name=”ServiceModelTraceListener” /
                             Also available through ServiceSecurityContext.Current.                        /listeners
                             Contains a property, AuthorizationContext, where you can                    /source
                                                                                                       /sources
                             investigate the ClaimSets for the current user.                           sharedListeners
                                                                                                         add initializeData=”.logsweb_tracelog.svclog”
                                                                                                           type=”System.Diagnostics.XmlWriterTraceListener, System,
The OperationContext also has two often used methods:                                              Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”
                                                                                                           name=”ServiceModelTraceListener”
 SetTransactionComplete()     Allows the service to complete a transaction in code instead                 traceOutputOptions=”Timestamp” /
                                                                                                       /sharedListeners
                              of automatically on exit.                                              /system.diagnostics
                                                                                                     system.serviceModel
 GetCallbackChannelT()      For duplex services, allows the service to send messages                 diagnostics wmiProviderEnabled=”true” /
                              back to the service.                                                   /system.serviceModel


                                                                                                  If, in production, something goes wrong, the administrator
                                                                                                  can run the following Powershell commands to update
    CONSUMING SERVICES                                                                            the switchValue, capture data, change the switchValue
                                                                                                  back to Off, and send the traces off to development:
When consuming services, you will typically create a proxy via
the Visual Studio ‘Add Service Reference’ tool. Enter the WSDL                                     $appDomain = Get-WmiObject -Namespace rootServiceModel
                                                                                                     AppDomainInfo
or MetadataExchange endpoint for the service, typically just the
address of the .svc file for IIS hosted services, and then pick out the                            $appDomain.TraceLevel = “Verbose, ActivityTracing”
service. Visual Studio will do the rest of the work, including adding                              $appDomain.put()
configuration. The developer may need to edit the application
configuration file (named [app name].exe.config if the client is                                  Note: the line to get the WMI object will change depending
an executable or web.config if the client is a web application) to                                on how many AppDomains hosting WCF endpoints are
enter in security credentials, but otherwise the work is done.                                    running on the computer. Each AppDomainInfo has a
                                                                                                  corresponding ProcessID and AppDomainId to help you pick
When consuming the previous service, write the following code,                                    the right instance. Once that is done, you can set the trace
catching the TimeoutException, CommunicationException,                                            level as above and call put() to save the data. Above turns on
and FaultException since any of these may be returned. For                                        ActivityTracing which allows WCF to assign IDs to related traces
both the CommunicationException and TimeoutException,                                             and show how one group of activity flows from another. Use
the code may want to have some retry logic built in to get a                                      SvcTraceViewer.exe (part of the Windows SDK and ships as a
new client instance and try again up to n times, logging the                                      part of Visual Studio) to view and interpret the traces. When the
exception each time. In all cases, the code should Abort the                                      administrator is done collecting data, turn tracing back off:
connection to release all resources on the client machine.
                                                                                                   $appDomain.TraceLevel = “Off”
When the configuration is generated for the client, the endpoints
will have names like binding_Contract. For IMyService, the                                         $appDomain.put()
client endpoint is named BasicHttpBinding_IMyService
in configuration. The endpoint can then be created by                                             Note that changes to the trace level do not get saved to the
instantiating the generated proxy using the configured name.                                      configuration file as this would cause the AppDomain to restart
A call to a IMyService implementation looks like this:                                            on IIS.

                                                                                DZone, Inc.   |   www.dzone.com
6
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 Getting Started with Windows Communication Foundation 4.0




                                                                                                                            With WMI on, you can also inspect all the running endpoints                                                                                                                                                                                                                                                                                      diagnostics
                                                                                                                            including binding data, behaviors, and many other items.                                                                                                                                                                                                                                                                                           messageLogging
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    logMessagesAtTransportLevel=”true”
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    logMessagesAtServiceLevel=”true” /
                                                                                                                            Message Logging                                                                                                                                                                                                                                                                                                                                  /diagnostics
                                                                                                                            Message logging is enabled in two places. First, create the message
                                                                                                                            logging trace source. If you are logging and tracing, you can get                                                                                                                                                                                                                                                                         Typically, you will log messages at the transport level to see an
                                                                                                                            all the traces into one file with the following configuration:                                                                                                                                                                                                                                                                            XML 1.0 text representation of what the ServiceModel saw including
                                                                                                                                                                                                                                                                                                                                                                                                                                                                      message headers added by the message pipeline. You log at the
                                                                                                                                       system.diagnostics                                                                                                                                                                                                                                                                                                           service level to see what the message looked like after the message
                                                                                                                                         sources
                                                                                                                                           source name=”System.ServiceModel”                                                                                                                                                                                                                                                                                         is decrypted.
                                                                                                                                             switchValue=”Off”
                                                                                                                                             propagateActivity=”true”
                                                                                                                                             listeners                                                                                                                                                                                                                                                                                                              Performance Counters
                                                                                                                                               add name=”ServiceModelTraceListener” /                                                                                                                                                                                                                                                                               To enable performance counters, viewed in tools like PerfMon,
                                                                                                                                             /listeners
                                                                                                                                           /source
                                                                                                                                                                                                                                                                                                                                                                                                                                                                      you add the following configuration to system.serviceModel:
                                                                                                                                           source name=”System.ServiceModel.MessageLogging”
                                                                                                                                             switchValue=”Off”
                                                                                                                                             propagateActivity=”true”                                                                                                                                                                                                                                                                                                diagnostics performanceCounters=”ServiceOnly” /
                                                                                                                                             listeners
                                                                                                                                               add name=”ServiceModelTraceListener” /
                                                                                                                                             /listeners                                                                                                                                                                                                                                                                                                             Performance Counters can have one of four values:
                                                                                                                                           /source
                                                                                                                                         /sources
                                                                                                                                         sharedListeners
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       Default                     WCF_Admin is created and SQM data is collected. The values
                                                                                                                                           add initializeData=”.logsweb_tracelog.svclog”
                                                                                                                                             type=”System.Diagnostics.XmlWriterTraceListener, System,                                                                                                                                                                                                                                                                                              are never updated.
                                                                                                                                     Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”
                                                                                                                                             name=”ServiceModelTraceListener”                                                                                                                                                                                                                                                                                          Off                         Performance counters are disabled.
                                                                                                                                             traceOutputOptions=”Timestamp” /
                                                                                                                                         /sharedListeners                                                                                                                                                                                                                                                                                                            ServiceOnly                 Only service level counters are enabled.
                                                                                                                                       /system.diagnostics
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       All                         Counters for the service, endpoints, and operations
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   are created.
                                                                                                                            In the ServiceModel configuration, you can set what you want to log:




                                                                                                     ABOUT THE AUTHOR                                                                                                                                                                                                                                                                                                                                                 RECOMMENDED BOOK
                                                                                                                        Scott Seely is the author of several books on Web Services                                                                                                                                                                                                                                                                                                                 Essential Windows Communication Foundation
                                                                                                                        and an instructor for Pluralsight. He is a Microsoft Regional                                                                                                                                                                                                                                                                                                              For .NET Framework 3.5
                                                                                                                        Director. Right now, he is working on Essential Windows                                                                                                                                                                                                                                                                                                                    Written by three experts at the Microsoft Technology
                                                                                                                        Communication Foundation, 2nd Edition for Addison Wesley.                                                                                                                                                                                                                                                                                                                  Center in Boston, this guide answers developers’
                                                                                                                        He helped found the Chicago Code Camp with several other                                                                                                                                                                                                                                                                                                                   questions about WCF. Throughout the book’s 13
                                                                                                                        local developers. He helps run the Lake County .NET Users’                                                                                                                                                                                                                                                                                                                 chapters, authors Steve Resnick, Richard Crane, and
                                                                                                                        Group with Tim Stall. Throughout the year, Scott can be found                                                                                                                                                                                                                                                                                                              Chris Bowen offer best practices, key advice, tips,
                                                                                                       speaking at the user groups throughout northern Illinois and Wisconsin. From                                                                                                                                                                                                                                                                                                                and problem-solving tricks. They solve developers’
                                                                                                       2000 through 2006, Scott worked for Microsoft. He spent his first two years as                                                                                                                                                                                                                                                                                                              problems with WCF through in-depth explanations
                                                                                                       a developer/writer for MSDN and then moved over to the Indigo/WCF team                                                                                                                                                                                                                                                                                                                      and an extensive amount of code samples.
                                                                                                       as a developer. Scott is also founder of Friseton, LLC. Friseton specializes in
                                                                                                       creating highly scalable parallelized systems, solving application performance                                                                                                                                                                                                                                                                                                                                     BUY NOW
                                                                                                       problems, and building distributed applications that utilize REST and WS-*.                                                                                                                                                                                                                                                                                                                  books.dzone.com/books/essential-wcf




                                                                                                                                          #82

                                                                                                                                                                                                                                                                                                                                                                                           Browse our collection of 100 Free Cheat Sheets
                                                                                                                                             Get More Refcardz! Visit refcardz.com




                                                                                                                                                                                        CONTENTS INCLUDE:
                                                                                                                                                                                        ■


                                                                                                                                                                                        ■
                                                                                                                                                                                            About Cloud Computing
                                                                                                                                                                                            Usage Scenarios                                                                          Getting Started with

                                                                                                                                                                                                              Aldon                                           Cloud 4Computing
                                                                                                                                                                                        ■
                                                                                                                                                                                            Underlying Concepts
                                                                                                                                                                                         Cost
                                                                                                                                                                                                     by...                                                         #6
                                                                                                                                                                                        ■




                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Upcoming Refcardz
                                                                                                                                                                                                                                    ®
                                                                                                                                                                                            t to you
                                                                                                                                                                                         Data Tier Technologies
                                                                                                                                                                                        ■

                                                                                                                                                                                                                                ply.
                                                                                                                                                                                     brough
                                                                                                                                                                                        ■
                                                                                                                                                                                         Platform Management and more... te. Com
                                                                                                                                                                                                                    bora
                                                                                                                                                                                                              Chan
                                                                                                                                                                                                                  ge. Colla                                                                                                                 By Daniel Rubio


                                                                                                                       on:
                                                                                                                                                                                                                                                                                         dz. com




                                                                                                              gratiterns
                                                                                                                                                                                                                                                                        also minimizes the need to make design changes to support
                                                                                                                                                                                                                                                                                              CON
                                                                                                                                                                                                ABOUT CLOUD COMPUTING                                                   one time events.           TEN TS
                                                                                                                                                                                                                                                                                                          INC



                                                                                                        s Inte nti-PatM. Duvall
                                                                                                                                                                                                                                                                                                                       ■
                                                                                                                                                                                                                                                                                                                           HTML                 LUD E:
                                                                                                                                                                                                                                                                                                                                  Basics
                                                                                                                                                                                                                                                                                        HTML
                                                                                                                                                                                                                                                                                       ref car




                                                                                                                                                                                                                                                                                                                   ■

                                                                                                                                                                                            Web applications have always been deployed on servers                       Automated growth  scalable technologies


                                                                                                 nuou
                                                                                                                                                                                                                                                                                             vs XHT
                                                                                                                                                                                                                                                                                                   ation
                                                                                                                                                                                                                                                                                                               ■
                                                                                                                                                                                                                                                                                                                   Valid                   ML
                                                                                                                                                                                            connected to what is now deemed the ‘cloud’.                                Having the capability to support one time events, cloud

                                                                                                             A
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Apache Ant
                                                                                                                                                                                                                                                                                             Useful



                                                                                             ontiPatterns and By Pa
                                                                                                                                                                                                                                                                                                           ■




#84
                                                                                                                                                                                                                                                                        computing platforms also facilitate the gradual growth curves
                                                                                                                                                                                                                                                                                                    Open
                                                                                                                    ul                                                                                                                                                                      Page         Source
                                                                                                                                                                                                                                                                                                       ■
                                                                                                                                                                                                                                                                                     Vis it




                                                                                                                                                                                            However, the demands and technology used on such servers                                              Stru


                                                                                            C
                                                                                                                                                                                                                                                                        faced by web applications. cture         Tools




                                                                                                                                                                                                                                                                                                                                                                                    Core
                                                                                                                                                                                                                                                                                            Key    ■
                                                                                                                                                                                                                                                                                                            Elem           Structur
                                          E:                                                                                                                                                has changed substantially in recent years, especially with                                                  al Elem ents
                                INC LUD gration                                                                                                                                             the entrance of service providers like Amazon, Google and                                                          ents and
                                                                                                                                                                                                                                                                        Large scale growth scenarios involving specialized equipment
                         NTS
                                                                                                                                                                                                                                                                                rdz !




                                    ous Inte Change



                                                                                                                                                                                                                                                                                                                                                                                         HTML
                 CO NTE                                                                                                                                                                     Microsoft.                                     es                                                                            more...
                                                                                                                                                                                                                                                                        (e.g. load balancers and clusters) are all but abstracted away by
                          Continu at Every                                                                                                                                                                                          e chang
  m




                  About                       ns                                                                                                                                                                                     to isolat
                                                                                                                                                                                                                                                                        relying on a cloud computing platform’s technology.
                          Software i-patter
                                                                                                                                                                                                                               space




                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Hadoop
  rdz .co




                  ■
                                                                                                                                                                                                  n
                                                                                                                                                                                                                                                                             Re fca




                                                                                                                                                                                                                        e Work
                   Build
                                                                                                                                                                                           riptio
                               and Ant                                                                                                                                         These companies have Privat deployed webmanage
                                                                                                                                                                                       Desc                    a
                                                                                                                                                                                                         are in long trol repos
                                                                                                                                                                                                                                      itory
                                                                                                                                                                                                                                                    applications                                                       HTM
                                                                                                                                                                                                                                                                                                                               L BAS
                      ■


                    Patterns Control                                                                                                                                                         lop softw                 n-con                     to
                          ■
                                                                                                                                                                               that adapt and scale to large user bases, making them
                                                                                                                                                                                        Deve
                                                                                                                                                                                                        les to
                                                                                                                                                                                                               a versio                ing and                                                                      ICS
                                                                                                                                                                                                                                                                        In addition, several cloud computing platforms support data
                                       ment                                                                                                                                                                                   ize merg
                                                                                                                                                                   rn
                     Version                   e...                                                                                                          Patte                              it all fi             to minim
                                                                                                                                                                                                         many aspects related tomultiple computing.
                                                                                                                                                                                                                                                                                            HTM
                             Manage s and mor                                                                                                                       e Work knowledgeable in a mainline                                            s cloud               tier technologies that L and the precedent set by Relational
                                                                                                                                                                                                                                                                                                    exceed
                              ■                                                                                                                                             space        Comm
      ref ca




                      Build                                                                                                                                                                                                                                                                               XHT
                                                                                                                                                                                                                                                                                re




                                                                                                                                                              Privat                           lop on                                that utilize                                           HTML
                                   tice                                                                                                                                                                                                                                                             is used ML are the
                                                                                                                                                                                                                                                                        Database Systems (RDBMS): Map Reduce, web service APIs,
                                  ■
                                                                                                                                                                                          Deve code lines
                            d Prac                                                                                                                                                                                         a system
                                                                                                                                                                     sitory                                                                            of work                             prog
                                                                                                                                                                                                                                                                                                  support as the grap foundation                                                                                                    By An
                                                                                                                                                                                                                                                                        Ge t Mo




                       Buil                                                                                                      Repo                                   active               are within
                                                                                                                                                  This Refcard will introduce to you to clouddcomputing, with an                       units
                                                                                                   RATION                                                                                                                                                               etc. Some platforms rams writ large scale RDBMS deployments.
                                      ■
                                                                                                                                                                                                                                                                                                                                                                                    The src
                                                                                                                                                                                                                                                                                                                                                                                                                                         dy Ha
                                                                                                                                                                                       softw                                 riente
                                                                                                                        e               ine                                    loping                                                                                                     and Java                           hical            of all
                                                                                       INTEG                                                                                                                                                                                                                ten                                                                              attribute
                                                                                                                                                                                                                      task-o
                                                                                                              softwar                             emphasis oncodelines providers, so by Commit better understand
                                                                                                                                   Mainl                                 Deve
                                                                                                                                                                            these                      chang Level can
                                                                                                                                                                                                              es you
                                                                                                                                                                                                                                                                                                      also recein JavaScri user interfac web develop                               and the                                                    rris
        Vis it




                                                                             S



                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Spring Security
                                                                                                                                                                                                                                                                                                                                                                                                        desc
                                                                       INUOU                           ding                                                                                                                                                                              as the
                                                                                                                                                                                             e code
                                                                                                                                             w ww.dzone.com




                                                                                                                                                                                                                                                                                                                  ive data pt. Server-s                                           the ima alt attribute ribes whe
                                                                                                                                                                                                          Task
                                                            NT                                 of buil           trol                             what it is a cloud computingaplatform can offer your web
                                                                                                                                           line Policy                           nize sourc es as                                                     ut                                          output                                           e in clien        ment.
                                                     T CO                               cess           ion con                      Code                                   Orga        it chang              e name                           e witho                                   likew
                                                                                                                                                                                                                                                                             CLOUD COMPUTING PLATFORMS AND ide languag t-side
                                                                                                                                                                                                                                                                                                           mechan            from                                                          ge is            describe re the ima
                                                                              the pro ject’s vers
                                                                                                                                                                                                                                       sourc
                                                                                                                                                  applications. and subm                                                                                                                       ise
                                            ABOU                      (CI) is
                                                                                                                                                            it                                  with uniqu                  are from
                                                                                                                                                                                                                                                                                        was onc use HTML              ism. The web pag                                           Nested
                                                                                                                                                                                                                                                                                                                                                                                                 unavaila             s alte          ge file
            rd z!




                                                                                   a pro                                                      evel Comm                             the build                        softw                                                                                                                                   es like                                       ble.              rnate
                                                            gration
                                                                                                                                                                                                             build                                        um
                                                                                                                                                                                                                                                                             UNDERLYING CONCEPTS                 and XHT         emergin es and use                                                                                           can be
                                                                           ed to                                     blem             Task-L                                 Label
                                                                                                                                                                                               activit
                                                                                                                                                                                                      ies to
                                                                                                                                                                                                                                       the bare
                                                                                                                                                                                                                                                   minim                                          e
                                                                                                                                                                                                                                                                                       standard a very loos                                 g Ajax
                                                                                                                                                                                                                                                                                                                                                                     PHP
                                                                                                                                                                                                                                                                                                                                                                                Tags        tags                                    text that           found,
                                                   ous Inte     committ                                  to a pro                                          USAGE SCENARIOS            ate all
                                                                                                                                                                               Autom configurat
                                                                                                                                                                                                     ion                       cies to                  t
                                                                                                                                                                                                                                                                                                  ization,        ely-defi
                                                                                                                                                                                                                                                                                                                            ML as
                                                                                                                                                                                                                                                                                                                                     thei            tech
                                                                                                                                                                                                                                                                                                                                                             HTML                     can                                                      is disp
                                          Continu ry change                                                                                                                                                                                                                                                                                                                    cannot be (and freq
                                                                                                                                                                                                                         nden                     ymen                                                                                                                                                                                                 layed
                                                                                                    tion                                                                                                                                                                                                                    ned lang r visual eng nologies
               Re fca




                                                                                                                  ive                           Build                                 al                         depe                      deplo      t                               need
                                                eve                                        , a solu , ineffect             )             Label                                  manu
                                                                                                                                                                                                  stalle
                                                                                                                                                                                                         d tool               the same          nmen                                         for           but as                                                                       overlap           uen                                                if
                                          with                                     s (i.e.       (i.e.               blem                         ated
                                                                                                                                                          Build
                                                                                                                                                                                       ce pre-in                       t, use target enviro                             Amazon EC2: ther stanstandard software and uage with
                                                                                                                                                                                                                                                                                      whe Industry dard              it has
                                                                                                                                                                                                                                                                                                                             become virtualization HTM
                                                                                                                                                                                                                                                                                                                                                        ine.                  b/               , so a tly are) nest
                                                                         pattern                           lar pro
                                                                                                                                                                                                               ymen
                                                                                         tterns                                                                                                                                                                                                             s has                                                                   a is
                                                    ory.                                                                                  Autom                                  Redu                d deploEAR) each
                                                                                                                                                  Pay only what you consume in                                                                                                                                       bec heavily based on very little L




                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Subversion
                                           reposit               ed via        anti-pa             particu tions that e                                        nden
                                                                                                                                                                    cies                     tagge
                                                                                                                                                                                  For each (e.g. WAR
                                                                                                                                                                                                            or
                                                                                                                                                                                                                                                          t                          the curr you cho platform isome
                                                                                                                                                                                                                                                                        Amazon’s cloud computing ose                                    more                                              fine.              b/
                                                                                                                                                                                                                                                                                                                                                                                                                 a/
                                                                                                                                                                                                                                                                                                                                                                                                                            ed insid
                                                         explain text) and to “fix” the are solu                                                                                                                             es                                                                                                 more            importa                                                                                e
                                                                                                                                                                                                                                                                                              ent stan                                                                                                                      not lega each othe
                                                                                                                                                                                                                                                                                                               to writ                                                                                                b is
                                                     be                                                                   duc                     Web application deployment untillibrari yearsenvironmen similar
                                                                                                                                                    al Depe                               ge                      t a few                  t ago was                                that will
                                                                                                                                                                                                                                                                        industry standard software and virtualization technology.      app               nt,
                                                                                                  ns             to pro                      Minim                                 packa                    nden                                                                                        dards           e HTM
                 Mo re




                                            CI can ticular con             used                                                                                                                  all depe                       all targe
                                                                                                                                                                                                                                                                                                                                 L or XHT arent. Reg the                         HTM                                                                 r. Tags
                                                                                        i-patter they tend es, but can                                                                                                                                                                                                                                                                                                                l, but
                                                                                                                                                             rity
                                                                 etimes         s. Ant                                                        Binar most phone services: plans with alloted resources, with an
                                                                                                                                                  toInteg
                                                                                                                                                    y                                      alize                late fi
                                                                                                                                                                                                                        le that
                                                                                                                                                                                                                                                                                   and XHT simplify all         will help
                                                                                                                                                                                                                                                                                                                                                          ardless                       L VS
                                                                                                                                                                                                                                                                                                                                                                                               XHTM                                          a
                                             in a par hes som                                     ,                                                                                 Centr                                                               ts                                                                                  ML,
                                                                                                                                                                                                                                                                                              ML physical r othe you prov to
                                                                                                                ctic                                                                                     temp                                                                                               you                                                                                                                                    b/
                                                                       proces , in the end bad pra                        enting
                                                                                                                                                                              nt                                                                 nmen
                                                                                                                                                                 Mana
                                                                                                                                                                       geme                  e a single based on
                                                                                                                                                  incurred cost whether such resources were consumedto thenot.                          t enviro            or          Virtualization allows aare actu piece of hardware idebe understand of
                                                                                                                                                                                                                                                                                  much                                                                                     HTML                         L
                                              approac ed with the cial, but                                    implem
                                                                                                                                                                                                                                  targe
                                                                                                                                                                                                                                                                                                            ally simp r web cod
                                                                                                                                                                                      Creat
                                                                                                rily                                                   nden
                                                                                                                                                              cy                              rties are                       nt                       es                                of the                                             a solid            ing                 has
                                                                                                                                                                                                                into differe
                                                                                     necessa pared to
                                                                                                                                                                                                                                                chang
                                                                    efi                                                                          Depe                                   prope                                             itting
                                                                                                                                                                                                                                                                                                                        ler than ing. Fort foundation
                                                                                                                                                                                                                                                                        utilized by multiple operating systems. This allows resources
                                                                                                                                                                                                                                                                                                  function                                                                job adm been arou
                                               associat to be ben
                                                                                                                                                                    er
                          Ge t




                                                                                                                                                                                                    te builds                                                                    commo
                                                                           are not                                                                       late Verifi                                                            e comm
                                                                                                                                                                                                                                                                                            memory, ality has allocated exclusively to
                                                                                                                                                                                                                                                                                                                                                                                                     nd for
                                                                                           n com                                                  Cloud computing asRun remo              it’s known etoday has changed this. etc.                                                                                                               unately                 expecte irably, that
                                                                                                                                                                                                                        befor
                                                                    They         lts whe
                                                                                                                                                 Temp                                                           Build                                   ually,          (e.g. bandwidth,n elem CPU) to be mov                      they                                                                     some
                                                appear effects.                                                                                                                                 rm a
                                                                                                                                                  The various resources consumed by webperiodically,
                                                                                                                                                                                                       Privat                                    contin
                                                                                                                                                                                                                                   applications (e.g.nt team                     Every                ent instances. ed to CSS
                                                                                                                                                                                                                                                                                                                                        used
                                                                                                                                                                                                                                                                                                                                                to be, HTML                        d. Earl        job              time.
                                                                       ed resu                                                   tion                                                     Perfo                                                             opme                       pag
                                                                                                                                                                                                                                                                        individual operating system s                                                   because         Brow                y HTM has expand              Whi
                                                 adverse unintend                                                       Integra
                                                                                                                                                            d Builds                             sitory
                                                                                                                                                  bandwidth, memory, CPU) areIntegration on from CI server basis
                                                                                                                                                                                                                           Build                   to devel                     common e (HTML                                            .                                   ser                                   ed far le it has don
                                                                                                                                                                                                                                                                                                                                                                        web dev manufacture L had very
                                                                                                                                                    Stage                                  Repo
                                                          e                                                                                                                                                  tallied              a per-unit                                                            or XHT
                                                  produc                                                     tinuous                                         e Build                               rm an                                                                       extensio .) All are                                                                                                                          more              e its
                                                                                                                                                                                                                                                               e.com




                                                                                                                             ard                                                                                                                                                                                ML shar                                                                                         limit
                                                           tern.
                                                                                                                                                                                                                            ack                                                                                                                                                   elopers          rs add                          than
                                                                                                        Con            Refc                       (starting from zero) by Perfomajor cloud computing platforms.
                                                                                                                                                     Privat
                                                                                                                                                                                             all                                                                                         n. HTM essentia                                                                                                  ed man ed layout
                                                                                                                                                                                                                    feedb                                               As a user of Amazon’s EC2 cloud computing platform, you are
                                                                                                                                                                                                                                                                   on                                                      es cert                                     result                                                            anybody
                                                                                            the term” cycle, this
                                                                                                                                                                                                             ated
                                                   the pat
                                                                                                                                                                                                                                       occur                                                                                                                                                came
                                                                             tion                                          h as                                                                      autom                   as they                         based            proc                              lly plai                                                      is
                                                                  Integra al use of                                 ts suc
                                                                                                                                                                      Build                   Send
                                                                                                                                                                                                               ors as
                                                                                                                                                                                                                       soon
                                                                                                                                                                                                                                            ion with
                                                                                                                                                                                                                                                     builds
                                                                                                                                                                                                                                                                                   an operating system in the same wayain on all hosting
                                                                                                                                                                                                                                                                        assigned essor             L files                n text      as elements                      The late a lack of stan up with clev y competi
                                                                                                                                                                                                                                                                                                                                                                                                                                 supp
                                                                                                                                                                                                                                                                                                                                                                                                                                        ort.
                                                                                            and test concep
                                                                                                                                                               ration                                                                                                                                     should
                                                         tinuous vention                                                                                                                                                                                                                                                                                                                                                       ng stan
                                                                                                                                                        Integ                                                                        entat
                                                                                                                                                                                                                                                                                                                                                     in                         st web           dar             er wor
                                                                                  “build include                                                                                                                                                                                                                     not be
                                                                                                                                                                                                                            docum
                                                    Con                                                                                                                                                                                                                                                                                                                                                                  kar            dar
                                                            the con s to the                                                                                                                                                                                                                                                                                                             standar
                                                                                                                                                                                                                     oper
                                                                                                                                                                                                        rate devel                                                                                                            cr
                                                     While                             CI to                                                                                                     Gene
                                                                  efer         ion of



                                                                                                                                                                                                                                                                                                                                                                                                                                                                  DZone, Inc.
                                                                                                                                              Cloud Computing




                                                                     the not
                                                               s on
                                                       expand




                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ISBN-13: 978-1-934238-75-2
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  140 Preston Executive Dr.                    ISBN-10: 1-934238-75-9
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Suite 100
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         50795
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Cary, NC 27513

                                                                                      DZone communities deliver over 6 million pages each month to                                                                                                                                                                                                                                                                                                                888.678.0399
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  919.678.0300
                                                                                      more than 3.3 million software developers, architects and decision
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Refcardz Feedback Welcome
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       $7.95




                                                                                      makers. DZone offers something for everyone, including news,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  refcardz@dzone.com
                                                                                      tutorials, cheatsheets, blogs, feature articles, source code and more.                                                                                                                                                                                                                                                                                                                                                9 781934 238752
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Sponsorship Opportunities
                                                                                      “DZone is a developer’s dream,” says PC Magazine.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  sales@dzone.com
                                                                                      Copyright © 2010 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical,                                                                                                                                                                                                                                                                     Version 1.0
                                                                                      photocopying, or otherwise, without prior written permission of the publisher.

More Related Content

PPTX
Network Management in System Center 2012 SP1 - VMM
PDF
Semantic Reasoning in Context-Aware Assistive Environments to Support Ageing ...
PDF
Cassandra & the Acunu Data Platform
PDF
Osi 7 layer
PDF
Cassandra on Castle
PDF
Castle: Reinventing Storage for Big Data
PDF
(Paper) P2P VIDEO BROADCAST BASED ON PER-PEER TRANSCODING AND ITS EVALUATION ...
PDF
Diameter and Diameter Roaming
Network Management in System Center 2012 SP1 - VMM
Semantic Reasoning in Context-Aware Assistive Environments to Support Ageing ...
Cassandra & the Acunu Data Platform
Osi 7 layer
Cassandra on Castle
Castle: Reinventing Storage for Big Data
(Paper) P2P VIDEO BROADCAST BASED ON PER-PEER TRANSCODING AND ITS EVALUATION ...
Diameter and Diameter Roaming

Viewers also liked (17)

PDF
Examiner tips for ol mathematics
PDF
開発合宿 Hello world
PPTX
Cloud Computing
PDF
Куда Выгоднее Вложить Деньги
PPTX
Ativ1 4 salete
PPT
PPTX
Slideshare työ
PPT
Sticks
PPTX
CONSERVATIVE MANAGEMENT OF OTITIS MEDIA final
PDF
Доверительное Управление Деньгами
PPT
Introducing
PDF
Доверительное Управление Деньгами
PPTX
The first home game
PPTX
High Definition Radio ppt
DOCX
Napkin folding(demonstration)
PPTX
Cefexta (Cefdinir) an extended spectrum antibiotic
PPTX
Conservative management of otitis media
Examiner tips for ol mathematics
開発合宿 Hello world
Cloud Computing
Куда Выгоднее Вложить Деньги
Ativ1 4 salete
Slideshare työ
Sticks
CONSERVATIVE MANAGEMENT OF OTITIS MEDIA final
Доверительное Управление Деньгами
Introducing
Доверительное Управление Деньгами
The first home game
High Definition Radio ppt
Napkin folding(demonstration)
Cefexta (Cefdinir) an extended spectrum antibiotic
Conservative management of otitis media
Ad

Similar to Rc111 010d-wcf (20)

PDF
Anish Karmakar S C A
PPTX
OpenStack Quantum Network Service
PDF
S-CUBE LP: Service Level Agreement based Service infrastructures in the conte...
PDF
The unified data center for cloud david yen
PPTX
Viestinnän seminaari 8.11.2012 / Exchange
DOCX
Top wcf interview questions
PDF
Ccnp Quick Reference Sheets Bundle Exams 642901 642812 642845 642825 Brent St...
PDF
Network Function Virtualisation
PDF
Sdn03
PDF
Viestintäaamupäivä exchange 2013
PDF
Communication server
PDF
Clean airdepguidde
PDF
S-CUBE LP: Service Level Agreement based Service infrastructures in the conte...
PPT
WCFPresentation.ppt WCFPresentation.ppt WCFPresentation.ppt
PDF
1ip Tunneling And Vpn Technologies 101220042129 Phpapp01
PDF
Configuration management benefits for everyone - Rudder @ FLOSSUK Spring Conf...
PDF
Energy efficient cluster-based service discovery in wireless sensor networks
PPTX
TFI2014 Session I - State of SDN - Scott Sneddon
PPT
it's learning MLG integration
 
Anish Karmakar S C A
OpenStack Quantum Network Service
S-CUBE LP: Service Level Agreement based Service infrastructures in the conte...
The unified data center for cloud david yen
Viestinnän seminaari 8.11.2012 / Exchange
Top wcf interview questions
Ccnp Quick Reference Sheets Bundle Exams 642901 642812 642845 642825 Brent St...
Network Function Virtualisation
Sdn03
Viestintäaamupäivä exchange 2013
Communication server
Clean airdepguidde
S-CUBE LP: Service Level Agreement based Service infrastructures in the conte...
WCFPresentation.ppt WCFPresentation.ppt WCFPresentation.ppt
1ip Tunneling And Vpn Technologies 101220042129 Phpapp01
Configuration management benefits for everyone - Rudder @ FLOSSUK Spring Conf...
Energy efficient cluster-based service discovery in wireless sensor networks
TFI2014 Session I - State of SDN - Scott Sneddon
it's learning MLG integration
 
Ad

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Getting Started with Data Integration: FME Form 101
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Mushroom cultivation and it's methods.pdf
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
Tartificialntelligence_presentation.pptx
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
1. Introduction to Computer Programming.pptx
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PPTX
cloud_computing_Infrastucture_as_cloud_p
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Encapsulation_ Review paper, used for researhc scholars
Getting Started with Data Integration: FME Form 101
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Heart disease approach using modified random forest and particle swarm optimi...
Mushroom cultivation and it's methods.pdf
Univ-Connecticut-ChatGPT-Presentaion.pdf
Tartificialntelligence_presentation.pptx
A novel scalable deep ensemble learning framework for big data classification...
Group 1 Presentation -Planning and Decision Making .pptx
1. Introduction to Computer Programming.pptx
DP Operators-handbook-extract for the Mautical Institute
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
MIND Revenue Release Quarter 2 2025 Press Release
SOPHOS-XG Firewall Administrator PPT.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
cloud_computing_Infrastucture_as_cloud_p
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...

Rc111 010d-wcf

  • 1. #111 Get More Refcardz! Visit refcardz.com CONTENTS INCLUDE: About WCF Getting Started with n n Configuration Overview WCF Contracts Windows Communication Foundation 4.0 n n Bindings n Behaviors Hosted Services and more... By Scott Seely n diagnostics Diagnostic settings for WCF, including WMI, performance ABOUT WCF counter, message filters, and other settings. extensions Defines configuration extensions for the bindings, behaviors, Since .NET 3.0, Windows Communication Foundation (WCF) is the bindingElement (for extending CustomBinding configuration), and standardEndpoints. preferred messaging system in .NET applications. It provides an abstraction layer over transports. This abstraction allows developers machineSettings Allows the user to log personally identifiable information to focus on the types of messages their applications need to send in traces and message logs via the XML attribute, enableLoggingKnownPii. This section can only be edited in and receive. It removes the need for developers to have intimate machine.config, located in the framework directory. knowledge of how the messages themselves are sent and received. protocolMapping Used to map a protocol to a binding for easier configuration. Instead, developers focus on a concept called an endpoint which serviceHostingEnvironment Used to configure services hosted in ASP.NET. listens for and receives messages. Endpoints are built using three services Defines which contracts a service instance will listen for items: Address, Binding, and Contract. messages on and any base addresses the service will use. A service may also add metadata and discovery endpoints via this The address defines where a message is sent. mechanism. http://www.dzone.com/ is an address. standardEndpoints Contains configuration for endpoints specified by the kind attribute on any service endpoint configuration. www.dzone.com A binding describes how to send the message. The binding contains information such as the transport to use, how to encode routing Provides message routes that a routing service uses to move messages closer to its final destination. messages, and security requirements. tracking Defines tracking settings for a workflow service. A contract defines how a message is structured. The contract defines the message exchange pattern (MEP) used for each exchange as well as which messages initiate a conversation or stop a WCF CONTRACTS conversation. All message exchanges fall into one of three message exchange patterns, or MEPs: one-way, request-response, and duplex. One-way messages can act as event notifications. Request- WCF developers create two types of contracts: service contracts response messages send some data and expect a response in a and data contracts. Service contracts inform the WCF runtime how particular format. Duplex messages are a conversation. In duplex, to read, write, and dispatch received messages. Data contracts when one caller initiates a conversation, that caller promises to inform the serialization infrastructure how to translate CLR objects make a set of one-way and request-response messages available to to and from an XML Infoset representation. the callee. Typically, duplex MEPs make use of sessions as well. Service Contracts Getting Started with Windows Communication Foundation 4.0 The WCF runtime creates the infrastructure to host services and CONFIGURATION OVERVIEW dispatch messages. Developers declare the pieces of infrastructure they need by marking up classes with attributes. The WCF runtime Configuration is a big feature in WCF. It permeates much of the then uses this information to allow for communication with callers messaging framework. This section provides a map of configuration. and the hosted classes. This information is also shared via Web The configuration section group, <system.configuration>, Services Description Language (WSDL) that WCF services can contains all WCF configuration settings. Within this configuration generate. To declare a class or interface represents the contract for section group, 14 different configuration sections exist. Some a WCF service, mark the class with [ServiceContract]. of those sections have relationships with other sections. One, system.serviceModel/extensions, is a configuration section for configuration only! behaviors Contains configuration for shared behaviors that can be applied Get over 90 DZone Refcardz bindings to endpoints and services. Contains information for shared bindings used to create FREE from Refcardz.com! message processing pipelines. A computer program that can run independently and can propagate a complete working version of itself onto other hosts on a network. client Contains information for clients to communicate with services. Lookups are performed using a two part key: the name of the configuration and the name of the contract. comContracts An integration point used between COM+ and WCF to configure the name and namespace for any hosted services. This mimics the functionality normally provided by the [ServiceContract] attribute via the Name and Namespace properties. commonBehaviors Defines a collection of behaviors applied to all services and endpoints. These behaviors add to any others already present on a service. DZone, Inc. | www.dzone.com
  • 2. 2 Getting Started with Windows Communication Foundation 4.0 [System.ServiceModel.ServiceContract] The commonly set properties on [DataContract] are: public interface IMyService { } Namespace Defines the URL used as the targetNamespace in the XSD describing the type and used when serializing the data contract as an XML Infoset. Through [ServiceContract], you will normally set the following Name Defines the name of the item when read and written to an XML Infoset. properties about the collection of operations on the service: The commonly set properties on [DataMember] are: Namespace Sets the default namespace for the XML Schema Documents (XSD) for the request and response messages. Default is http://tempuri.org. Name Defines the name of the item when read and written to an XML Infoset. SessionMode One of three values: Allowed, Required, NotAllowed. By default, IsRequired Set to true if the field must be present when the type is deserialized. SessionMode is Allowed. If your contract requires session semantics, set this value to System.ServiceModel.SessionMode.Required. If your Default value is false. contract will fail with sessions, set it to System.ServiceModel.SessionMode. NotAllowed. EmitDefaultValue Indicates whether or not to write the member when set to the default value. The default value of this member is true. CallbackContract CallbackContract: If the contract implements a duplex MEP, set this to the Order An integer used to alter the ordering of values when read or written. interface representing the other side of the duplex conversation. By default, values are read and written in alphabetic order. The default value of Order is 0. Members with the same Order value are serialized To make methods visible to external callers, mark the methods with alphabetically. Order is sorted ascending. [OperationContract]. [System.ServiceModel.ServiceContract( Namespace = “http://www.dzone.com/WCF”)] BINDINGS public interface IMyService { [System.ServiceModel.OperationContract] WCF supports messaging through a messaging pipeline. The string SayHi(string name); } pipeline itself must have stages that represent the transport and the serialization mechanism. In WCF, the pipeline is created by a The commonly set properties on [OperationContract] are: type derived from System.ServiceModel.Channels.Binding and the stages are created by types derived from System.ServiceModel. IsOneWay Can only be set on methods that return void. Use this to indicate that the Channel.BindingElement. Besides the transport and serialization method does not send a response. Default is false. mechanism, the BindingElement also adds stages for security, IsInitiating Use this to state that a given method can be called to instantiate a new reliability, and transactions. When creating a Binding, the service. Default value is true. developer of the Binding decides how to surface the underlying IsTerminating Use this to state that when a given method is called, the current instance can BindingElement properties. Some settings will be easily set, others be disposed. Default value is false. If this value is set to true, you must also set ServiceContractAttribute.SessionMode to SessionMode.Required. made private, and still others surfaced as different concepts. Your code may also return exceptions to callers. In SOAP messaging, Every binding has settings for timeouts: OpenTimeout, errors are returned as Fault messages. A given operation may ReceiveTimeout, CloseTimeout. These set the amount of time the return zero or more faults. One declares the types of faults being user of the Binding will wait for the pipeline to Open, Receive a returned through [FaultContract]. [FaultContract] has a constructor message, or Close. A Binding also identifies its URL scheme, which that accepts a type describing what the fault details will look like. is the scheme used by its transport. WCF ships with Bindings This description is used by the callers to read any faults your service supporting the following schemes: http, https, net.msmq, net.pipe, might return. net.p2p, and net.tcp. WCF also supports soap.udp, but only in an internal class used to support WS-Discovery. [System.ServiceModel.ServiceContract( Namespace = “http://www.dzone.com/WCF”)] public interface IMyService { Each of the Bindings has a common set of properties [System.ServiceModel.OperationContract()] not required by the base class, Binding: [FaultContract(typeof(FaultDetails))] string SayHi(string name); } EnvelopeVersion Sets the version of any SOAP Envelope. Normally, this is set to None, Soap11, Soap12. Use None for REST or other non-SOAP messaging; Data Contracts Soap11 to send a SOAP 1.1 envelope and related headers; Soap12 to WCF reads and writes objects to and from different formats using send a SOAP 1.2 envelope and related headers. serialization (write) and deserialization (read). WCF supports MaxBufferPoolSize Most messages are received into memory. The buffer pool is used to serialization through several mechanisms: System.Xml.Serialization, allocate memory for receiving messages. By default, each buffer in the System.ISerializable, [System.Serializable], and through System. pool is 65536 bytes. Adjust this value to change the size of the individual Runtime.Serialization. The first three mechanisms exist to support buffers. legacy code. When developing your own declarations, you will ReaderQuotas This sets quotas on reading inbound messages. The type, normally use System.Runtime.Serialization to describe your data System.Xml.XmlDictionaryReaderQuotas is found in contracts. In WCF 4.0, an unattributed type will automatically read System.Runtime.Serialization. The quotas set limits which limit the and write any public fields or properties using the name of the damage a denial of service attack or poorly formed XML document property in the generated format. To control what gets written, mark can do. By default, arrays can be no longer that 16384 elements the type with [DataContract] and any members to be written with (MaxArrayLength), strings must be less than 8192 characters (MaxStringContentLength), and XML nodes must be no more than 32 [DataMember]. levels deep (MaxDepth). [System.Runtime.Serialization.DataContract] Scheme Identifies the scheme used by the underlying transport protocol. public class Name { [System.Runtime.Serialization.DataMember] public string FirstName { get; set; } Depending on which protocol you want to use, you have different bindings available. Most of the bindings in WCF support HTTP. [System.Runtime.Serialization.DataMember] public string LastName { get; set; } The rest of the supported protocols are represented by one } binding. The following table shows which bindings support When you explicitly mark a member with [DataMember], that duplex communications, message level security, reliable field will be read and written regardless if the member is private, messaging, flowing transactions, and workflow context. Transport protected, or public. level security is available through all bindings in WCF. DZone, Inc. | www.dzone.com
  • 3. 3 Getting Started with Windows Communication Foundation 4.0 Binding Duplex Message level Reliable Transactions [ServiceBehavior] contains several properties. The most commonly security used are: BasicHttpBinding * ConcurrencyMode Controls the internal threading model to enable support BasicHttpContextBinding * for reentrant or multithreaded services. By default, MsmqIntegrationBinding concurrency is single threaded per instance. NetMsmqBinding  InstanceContextMode Controls how instances are created for the service. By NetNamedPipeBinding    default, each session gets a new service instance. Set this property to PerSCall to allow for a new instance for NetPeerTcpBinding   every method call. Set this property to Single if you need singleton behavior for the service. NetTcpBinding     NetTcpContextBinding     IncludeExceptionDetailsInFaults Returns exception details to clients when debugging services. This property requires a request-response or WS2007FederationHttpBinding    duplex capable binding. WS2007HttpBinding    WSDualHttpBinding     [DeliveryRequirements], a contract behavior, allows a contract to specify information about reliable messaging requirements imposed WSFederationHttpBinding    on the service delivery. WSHttpBinding    WSHttpContextBinding    [CallbackBehavior], an endpoint behavior, provides configuration settings for the callback contract on a duplex service. The settings * The BasicHttpBinding and BasicHttpContextBinding will sign the are the same as the [ServicBehavior] except for settings for timestamp on the message, but not sign and encrypt the body. For instancing and transactions. full message level signing and encryption, use WSHttpBinding and In configuration, you can declare information about security, WSHttpContextBinding. diagnostics, discovery, and throttling. Bindings appear in configuration in the system.serviceModel/ WCF contains many configuration elements. Here, we focus on bindings section under configuration that matches a camelCased the commonly configured behaviors for services. The following version of the binding name. For example, the collection behaviors allow you to configure your service behaviors as of WSHttpBinding can be found in system.serviceModel/ part of configuration within system.serviceModel/behaviors/ bindings/wsHttpBinding. Each configured binding has a serviceBehaviors/: name. A binding without a name becomes the default set of settings for that particular binding. For example, to create a reliable WSHttpBinding, use the following configuration: serviceCredentials Allows the service to pick how it authenticates itself using X.509, Windows, username/password, and other valid tokens. <system.serviceModel> serviceDebug Allows you to set up the HttpHelp page and to include exception <bindings> details in faults. <wsHttpBinding> <binding name=”reliable”> serviceDiscovery Enables the WS-Discovery endpoint. <reliableSession enabled=”true”/> </binding> serviceMetadata Enables the WS-MetadataExchange endpoint. </wsHttpBinding> </bindings> </system.serviceModel> On an endpoint, you can configure other behaviors. The following commonly used behaviors allow you to configure your endpoint behaviors as part of configuration within system.serviceModel/ BEHAVIORS behaviors/endpointBehaviors/: Behaviors influence the hosting environment for a service. They callbackDebug Allows you to state if a callback contract should include exception details are used to handle instancing, expose metadata, enhance in faults. discoverability, and more. There are four types of behaviors: service, clientCredentials Allows the client to pick how it authenticates itself using X.509, Windows, contract, endpoint, and operation. All behaviors may be applied username/password, and other valid tokens. in code. Service and endpoint behaviors may also be applied by enableWebScript Enables a Web Script endpoint on the service. This allows the service configuration. (Note: There is no notion of contract configuration to return JavaScript when the URL end in /js or /jsdebug. This behavior anywhere in WCF.) Service and contract behaviors are normally is automatically included if using the System.ServiceModel.Activation. applied via attributes in code. WebScriptServiceHostFactory on a .SVC. webHttp Allows the endpoint to dispatch messages based on URL. This behavior A service behavior applies to a service instance and may alter is automatically included if using the System.ServiceModel.Activation. aspects of the service, all endpoints, and all contracts. A contract WebScriptServiceHostFactory or System.ServiceModel.Activation. behavior applies to a contract and all implementations of the WebServiceHostFactory as the factory name on a .SVC. contract. Endpoint behaviors apply to a specific endpoint instances. Finally, operation behaviors apply to specific operations. HOSTING SERVICES Attribute-based Behaviors There are two service behaviors: WCF services can listen for messages anywhere: Windows [AspNetCompatibilityRequirements] and [ServiceBehavior]. Services, desktop applications, and Internet Information Services [AspNetCompatibilityRequirements] has a single property, (IIS). All environments use the same configuration elements. In RequirementsMode, that allows a service to declare that ASP all cases, an instance of a ServiceHost will be used to reflect over features such as identity impersonation are Required, Allowed, or a service implementation to determine service requirements. NotAllowed (default). When set to Required, configuration must The ServiceHost then marries the code with any configuration enable compatibility too: to produce an entity that can listen for, dispatch, and respond to messages that arrive over the various transports. <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled=”true”/> </system.serviceModel> To demonstrate hosting, we use the following contract: DZone, Inc. | www.dzone.com
  • 4. 4 Getting Started with Windows Communication Foundation 4.0 namespace DZone.Contracts private ServiceHost _host; { [System.ServiceModel.ServiceContract( protected override void OnStart(string[] args) Namespace = “http://www.dzone.com/WCF”)] { public interface IMyService ThreadPool.QueueUserWorkItem(StartListening, this); { } [System.ServiceModel.OperationContract] string SayHi(string name); static void StartListening(object state) } { } var service = state as DemoService; Implemented by the following class: if (service != null) namespace DZone.Services { { service._host = new ServiceHost(typeof(MyService)); public class MyService : DZone.Contracts.IMyService service._host.Faulted += { (s, e) => public string SayHi(string name) { { service.StopListening(); return string.Format(“Console: Hello, {0}”, name); service._host = null; } StartListening(service); } }; } } } and use the following configuration: protected override void OnStop() { StopListening(); } <configuration> <system.serviceModel> void StopListening() <behaviors> { <serviceBehaviors> try <behavior name=”MyServiceBehavior”> { <serviceMetadata httpGetEnabled=”true”/> ((IDisposable)_host).Dispose(); </behavior> } </serviceBehaviors> catch (CommunicationObjectFaultedException ex) </behaviors> { <services> // TODO: add code to log <service name=”DZone.Services.MyService” } behaviorConfiguration=”MyServiceBehavior”> } <host> <baseAddresses> <add baseAddress=”http://localhost/Demo”/> </baseAddresses> The preceding code executes the initialization logic on a </host> separate thread via ThreadPool.QueueUserWorkItem. The <endpoint contract=”DZone.Contracts.IMyService” binding=”basicHttpBinding” address=”/MyService”/> ServiceHost will run for a long time. If the ServiceHost gets <endpoint kind=”mexEndpoint” address=”/mex” into a situation where it can no longer listen for messages by binding=”mexHttpBinding” /> </service> entering the Faulted state, the code should start up a new </services> </system.serviceModel> instance of the ServiceHost. When the service is done listening, </configuration> a CommunicationObjectFaultedException may be thrown on Dispose. Because this exception is expected, the code will log The configuration declares that there is a serviceBehavior the exception. When the service stops, we call StopListening. If named MyServiceBehavior which supports metadata exchange. you want to support Pause and Resume, add the following: This behavior is attached to a service instance whose name is DZone.Services.MyService and matches the name of the service protected override void OnPause() implementation. The host has a base address of http://localhost/ { StopListening(); Demo. This base address is used for any bindings that support the base.OnPause(); http scheme. The service exposes two endpoints. One endpoint } exposes an implementation of the DZone.Contracts.IMyService protected override void OnContinue() { contract listening off the http base address at /MyService. The other ThreadPool.QueueUserWorkItem(StartListening, this); endpoint hosts metadata exchange using a predefined binding base.OnContinue(); } named mexHttpBinding listening off the http base address at /Mex. Hosting in IIS Hosting in a Console/GUI application To host a service in IIS, you create a .svc file which is Using this configuration, we can host the service in a hosted at a path of your choosing in your web application. Console application with the following code: That will give you a file that looks like this: var host = new ServiceHost(typeof(MyService)) <%@ ServiceHost Service=”DZone.Services.MyService” %> host.Open(); Console.WriteLine(“Press [Enter] to exit”); Console.ReadLine(); The config remains largely the same. IIS will automatically set try the http base address for the host to be the address of the { .svc file. ((IDisposable)host).Dispose(); } catch (CommunicationObjectFaultedException ex) In IIS 7 and later, you can also host services with NetTcpBinding and { // TODO: add code to log NetNamedPipeBinding. To do this, run the following commands: } TCP Activation: Once the using block exits, host.Dispose() is called. You can do something similar in a WinForm/WPF application by 1. Run the following command (on one line): opening the service on window Load and explicitly calling ServiceHost.Dispose() when the window is closed/unloaded. %windir%system32inetsrvappcmd.exe set site “Default Web Site” -+bindings. [protocol=’net.tcp’,bindingInformation=’808:*’] Hosting in a Windows Service A Windows Service requires you to be able to respond to 2. un the following command to enable the http and net. pipe R Start and Resume events very quickly. In order to do this, you protocol on your site (on one line): do not want to block in the start if at all possible. Creating a single WCF ServiceHost does not normally take much time. %windir%system32inetsrvappcmd.exe set app However, we should always be prepared for things to take a “Default Web Site/[your v-dir]” /enabledProtocols:http,net.tcp while and have the services behave nicely. To host the same WCF service in a Windows Service, write the following code: Named Pipe Activation DZone, Inc. | www.dzone.com
  • 5. 5 Getting Started with Windows Communication Foundation 4.0 1. Run the following command (on one line): var client = new DZoneService.MyServiceClient( “BasicHttpBinding_IMyService”); try { %windir%system32inetsrvappcmd.exe set site “Default Web Site” Console.WriteLine(client.SayHi(“DZone”)); -+bindings.[protocol=’net.pipe’,bindingInformation=’*’] } catch (TimeoutException timeoutException) { 2. un the following command to enable the http and net. pipe R client.Abort(); protocol on your site (on one line): } catch (FaultExceptionKnownFaultType faultException) { client.Abort(); %windir%system32inetsrvappcmd.exe set app } “Default Web Site/[your v-dir]” /enabledProtocols:http,net.pipe catch (FaultException faultException) { client.Abort(); With Vista SP1 and Server 2008, you can also enable these protocols } catch (CommunicationException communicationException) in the IIS Manager. { client.Abort(); } For the demo application, remove the host base addresses and add in these two endpoints: DIAGNOSTICS endpoint contract=”DZone.Contracts.IMyService” address=”/MyService” binding=”netTcpBinding” / endpoint contract=”DZone.Contracts.IMyService” address=”/MyService” binding=”netNamedPipeBinding” / WCF also comes with a rich set of diagnostics information. Unlike other aspects of WCF, diagnostics can only be set in configuration. The diagnostics allows for tracing, message OperationContext logging, WMI inspection, and performance counters. Every incoming message is associated with an OperationContext. Think of OperationContext as WCF’s version of HttpContext. OperationContext.Current yields the current operation context Tracing/WMI All production applications should be deployed with System. with pointers to the following commonly used properties: ServiceModel tracing configured but turned off. WMI should be enabled so that an administrator can enable IncomingMessageHeaders Headers on the incoming message. tracing through WMI. The configuration looks like this: OutgoingMessageHeaders Can use this to add more headers to the response. system.diagnostics IncomingMessageProperties The message properties serve as a mechanism to send sources information in between layers within the message processing source name=”System.ServiceModel” pipeline about a specific message. switchValue=”Off” propagateActivity=”true” listeners ServiceSecurityContext Gain access to the identity of the currently logged in user. add name=”ServiceModelTraceListener” / Also available through ServiceSecurityContext.Current. /listeners Contains a property, AuthorizationContext, where you can /source /sources investigate the ClaimSets for the current user. sharedListeners add initializeData=”.logsweb_tracelog.svclog” type=”System.Diagnostics.XmlWriterTraceListener, System, The OperationContext also has two often used methods: Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089” name=”ServiceModelTraceListener” SetTransactionComplete() Allows the service to complete a transaction in code instead traceOutputOptions=”Timestamp” / /sharedListeners of automatically on exit. /system.diagnostics system.serviceModel GetCallbackChannelT() For duplex services, allows the service to send messages diagnostics wmiProviderEnabled=”true” / back to the service. /system.serviceModel If, in production, something goes wrong, the administrator can run the following Powershell commands to update CONSUMING SERVICES the switchValue, capture data, change the switchValue back to Off, and send the traces off to development: When consuming services, you will typically create a proxy via the Visual Studio ‘Add Service Reference’ tool. Enter the WSDL $appDomain = Get-WmiObject -Namespace rootServiceModel AppDomainInfo or MetadataExchange endpoint for the service, typically just the address of the .svc file for IIS hosted services, and then pick out the $appDomain.TraceLevel = “Verbose, ActivityTracing” service. Visual Studio will do the rest of the work, including adding $appDomain.put() configuration. The developer may need to edit the application configuration file (named [app name].exe.config if the client is Note: the line to get the WMI object will change depending an executable or web.config if the client is a web application) to on how many AppDomains hosting WCF endpoints are enter in security credentials, but otherwise the work is done. running on the computer. Each AppDomainInfo has a corresponding ProcessID and AppDomainId to help you pick When consuming the previous service, write the following code, the right instance. Once that is done, you can set the trace catching the TimeoutException, CommunicationException, level as above and call put() to save the data. Above turns on and FaultException since any of these may be returned. For ActivityTracing which allows WCF to assign IDs to related traces both the CommunicationException and TimeoutException, and show how one group of activity flows from another. Use the code may want to have some retry logic built in to get a SvcTraceViewer.exe (part of the Windows SDK and ships as a new client instance and try again up to n times, logging the part of Visual Studio) to view and interpret the traces. When the exception each time. In all cases, the code should Abort the administrator is done collecting data, turn tracing back off: connection to release all resources on the client machine. $appDomain.TraceLevel = “Off” When the configuration is generated for the client, the endpoints will have names like binding_Contract. For IMyService, the $appDomain.put() client endpoint is named BasicHttpBinding_IMyService in configuration. The endpoint can then be created by Note that changes to the trace level do not get saved to the instantiating the generated proxy using the configured name. configuration file as this would cause the AppDomain to restart A call to a IMyService implementation looks like this: on IIS. DZone, Inc. | www.dzone.com
  • 6. 6 Getting Started with Windows Communication Foundation 4.0 With WMI on, you can also inspect all the running endpoints diagnostics including binding data, behaviors, and many other items. messageLogging logMessagesAtTransportLevel=”true” logMessagesAtServiceLevel=”true” / Message Logging /diagnostics Message logging is enabled in two places. First, create the message logging trace source. If you are logging and tracing, you can get Typically, you will log messages at the transport level to see an all the traces into one file with the following configuration: XML 1.0 text representation of what the ServiceModel saw including message headers added by the message pipeline. You log at the system.diagnostics service level to see what the message looked like after the message sources source name=”System.ServiceModel” is decrypted. switchValue=”Off” propagateActivity=”true” listeners Performance Counters add name=”ServiceModelTraceListener” / To enable performance counters, viewed in tools like PerfMon, /listeners /source you add the following configuration to system.serviceModel: source name=”System.ServiceModel.MessageLogging” switchValue=”Off” propagateActivity=”true” diagnostics performanceCounters=”ServiceOnly” / listeners add name=”ServiceModelTraceListener” / /listeners Performance Counters can have one of four values: /source /sources sharedListeners Default WCF_Admin is created and SQM data is collected. The values add initializeData=”.logsweb_tracelog.svclog” type=”System.Diagnostics.XmlWriterTraceListener, System, are never updated. Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089” name=”ServiceModelTraceListener” Off Performance counters are disabled. traceOutputOptions=”Timestamp” / /sharedListeners ServiceOnly Only service level counters are enabled. /system.diagnostics All Counters for the service, endpoints, and operations are created. In the ServiceModel configuration, you can set what you want to log: ABOUT THE AUTHOR RECOMMENDED BOOK Scott Seely is the author of several books on Web Services Essential Windows Communication Foundation and an instructor for Pluralsight. He is a Microsoft Regional For .NET Framework 3.5 Director. Right now, he is working on Essential Windows Written by three experts at the Microsoft Technology Communication Foundation, 2nd Edition for Addison Wesley. Center in Boston, this guide answers developers’ He helped found the Chicago Code Camp with several other questions about WCF. Throughout the book’s 13 local developers. He helps run the Lake County .NET Users’ chapters, authors Steve Resnick, Richard Crane, and Group with Tim Stall. Throughout the year, Scott can be found Chris Bowen offer best practices, key advice, tips, speaking at the user groups throughout northern Illinois and Wisconsin. From and problem-solving tricks. They solve developers’ 2000 through 2006, Scott worked for Microsoft. He spent his first two years as problems with WCF through in-depth explanations a developer/writer for MSDN and then moved over to the Indigo/WCF team and an extensive amount of code samples. as a developer. Scott is also founder of Friseton, LLC. Friseton specializes in creating highly scalable parallelized systems, solving application performance BUY NOW problems, and building distributed applications that utilize REST and WS-*. books.dzone.com/books/essential-wcf #82 Browse our collection of 100 Free Cheat Sheets Get More Refcardz! Visit refcardz.com CONTENTS INCLUDE: ■ ■ About Cloud Computing Usage Scenarios Getting Started with Aldon Cloud 4Computing ■ Underlying Concepts Cost by... #6 ■ Upcoming Refcardz ® t to you Data Tier Technologies ■ ply. brough ■ Platform Management and more... te. Com bora Chan ge. Colla By Daniel Rubio on: dz. com gratiterns also minimizes the need to make design changes to support CON ABOUT CLOUD COMPUTING one time events. TEN TS INC s Inte nti-PatM. Duvall ■ HTML LUD E: Basics HTML ref car ■ Web applications have always been deployed on servers Automated growth scalable technologies nuou vs XHT ation ■ Valid ML connected to what is now deemed the ‘cloud’. Having the capability to support one time events, cloud A Apache Ant Useful ontiPatterns and By Pa ■ #84 computing platforms also facilitate the gradual growth curves Open ul Page Source ■ Vis it However, the demands and technology used on such servers Stru C faced by web applications. cture Tools Core Key ■ Elem Structur E: has changed substantially in recent years, especially with al Elem ents INC LUD gration the entrance of service providers like Amazon, Google and ents and Large scale growth scenarios involving specialized equipment NTS rdz ! ous Inte Change HTML CO NTE Microsoft. es more... (e.g. load balancers and clusters) are all but abstracted away by Continu at Every e chang m About ns to isolat relying on a cloud computing platform’s technology. Software i-patter space Hadoop rdz .co ■ n Re fca e Work Build riptio and Ant These companies have Privat deployed webmanage Desc a are in long trol repos itory applications HTM L BAS ■ Patterns Control lop softw n-con to ■ that adapt and scale to large user bases, making them Deve les to a versio ing and ICS In addition, several cloud computing platforms support data ment ize merg rn Version e... Patte it all fi to minim many aspects related tomultiple computing. HTM Manage s and mor e Work knowledgeable in a mainline s cloud tier technologies that L and the precedent set by Relational exceed ■ space Comm ref ca Build XHT re Privat lop on that utilize HTML tice is used ML are the Database Systems (RDBMS): Map Reduce, web service APIs, ■ Deve code lines d Prac a system sitory of work prog support as the grap foundation By An Ge t Mo Buil Repo active are within This Refcard will introduce to you to clouddcomputing, with an units RATION etc. Some platforms rams writ large scale RDBMS deployments. ■ The src dy Ha softw riente e ine loping and Java hical of all INTEG ten attribute task-o softwar emphasis oncodelines providers, so by Commit better understand Mainl Deve these chang Level can es you also recein JavaScri user interfac web develop and the rris Vis it S Spring Security desc INUOU ding as the e code w ww.dzone.com ive data pt. Server-s the ima alt attribute ribes whe Task NT of buil trol what it is a cloud computingaplatform can offer your web line Policy nize sourc es as ut output e in clien ment. T CO cess ion con Code Orga it chang e name e witho likew CLOUD COMPUTING PLATFORMS AND ide languag t-side mechan from ge is describe re the ima the pro ject’s vers sourc applications. and subm ise ABOU (CI) is it with uniqu are from was onc use HTML ism. The web pag Nested unavaila s alte ge file rd z! a pro evel Comm the build softw es like ble. rnate gration build um UNDERLYING CONCEPTS and XHT emergin es and use can be ed to blem Task-L Label activit ies to the bare minim e standard a very loos g Ajax PHP Tags tags text that found, ous Inte committ to a pro USAGE SCENARIOS ate all Autom configurat ion cies to t ization, ely-defi ML as thei tech HTML can is disp Continu ry change cannot be (and freq nden ymen layed tion ned lang r visual eng nologies Re fca ive Build al depe deplo t need eve , a solu , ineffect ) Label manu stalle d tool the same nmen for but as overlap uen if with s (i.e. (i.e. blem ated Build ce pre-in t, use target enviro Amazon EC2: ther stanstandard software and uage with whe Industry dard it has become virtualization HTM ine. b/ , so a tly are) nest pattern lar pro ymen tterns s has a is ory. Autom Redu d deploEAR) each Pay only what you consume in bec heavily based on very little L Subversion reposit ed via anti-pa particu tions that e nden cies tagge For each (e.g. WAR or t the curr you cho platform isome Amazon’s cloud computing ose more fine. b/ a/ ed insid explain text) and to “fix” the are solu es more importa e ent stan not lega each othe to writ b is be duc Web application deployment untillibrari yearsenvironmen similar al Depe ge t a few t ago was that will industry standard software and virtualization technology. app nt, ns to pro Minim packa nden dards e HTM Mo re CI can ticular con used all depe all targe L or XHT arent. Reg the HTM r. Tags i-patter they tend es, but can l, but rity etimes s. Ant Binar most phone services: plans with alloted resources, with an toInteg y alize late fi le that and XHT simplify all will help ardless L VS XHTM a in a par hes som , Centr ts ML, ML physical r othe you prov to ctic temp you b/ proces , in the end bad pra enting nt nmen Mana geme e a single based on incurred cost whether such resources were consumedto thenot. t enviro or Virtualization allows aare actu piece of hardware idebe understand of much HTML L approac ed with the cial, but implem targe ally simp r web cod Creat rily nden cy rties are nt es of the a solid ing has into differe necessa pared to chang efi Depe prope itting ler than ing. Fort foundation utilized by multiple operating systems. This allows resources function job adm been arou associat to be ben er Ge t te builds commo are not late Verifi e comm memory, ality has allocated exclusively to nd for n com Cloud computing asRun remo it’s known etoday has changed this. etc. unately expecte irably, that befor They lts whe Temp Build ually, (e.g. bandwidth,n elem CPU) to be mov they some appear effects. rm a The various resources consumed by webperiodically, Privat contin applications (e.g.nt team Every ent instances. ed to CSS used to be, HTML d. Earl job time. ed resu tion Perfo opme pag individual operating system s because Brow y HTM has expand Whi adverse unintend Integra d Builds sitory bandwidth, memory, CPU) areIntegration on from CI server basis Build to devel common e (HTML . ser ed far le it has don web dev manufacture L had very Stage Repo e tallied a per-unit or XHT produc tinuous e Build rm an extensio .) All are more e its e.com ard ML shar limit tern. ack elopers rs add than Con Refc (starting from zero) by Perfomajor cloud computing platforms. Privat all n. HTM essentia ed man ed layout feedb As a user of Amazon’s EC2 cloud computing platform, you are on es cert result anybody the term” cycle, this ated the pat occur came tion h as autom as they based proc lly plai is Integra al use of ts suc Build Send ors as soon ion with builds an operating system in the same wayain on all hosting assigned essor L files n text as elements The late a lack of stan up with clev y competi supp ort. and test concep ration should tinuous vention ng stan Integ entat in st web dar er wor “build include not be docum Con kar dar the con s to the standar oper rate devel cr While CI to Gene efer ion of DZone, Inc. Cloud Computing the not s on expand ISBN-13: 978-1-934238-75-2 140 Preston Executive Dr. ISBN-10: 1-934238-75-9 Suite 100 50795 Cary, NC 27513 DZone communities deliver over 6 million pages each month to 888.678.0399 919.678.0300 more than 3.3 million software developers, architects and decision Refcardz Feedback Welcome $7.95 makers. DZone offers something for everyone, including news, refcardz@dzone.com tutorials, cheatsheets, blogs, feature articles, source code and more. 9 781934 238752 Sponsorship Opportunities “DZone is a developer’s dream,” says PC Magazine. sales@dzone.com Copyright © 2010 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, Version 1.0 photocopying, or otherwise, without prior written permission of the publisher.