30 March 2014

Design Patterns


Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects..
The 23 Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioural
To give you a head start, the C# source code for each pattern is provided in 2 forms: structural and real-world. Structural code uses type names as defined in the pattern definition and UML diagrams. Real-world code provides real-world programming situations where you may use these patterns.

A third form, .NET optimized, demonstrates design patterns that exploit built-in .NET 4.5 features, such as, generics, attributes, delegates, reflection, and more.
Creational Patterns:
Abstract Factory :Creates an instance of several families of classes
BuilderSeparates object construction from its representation
Factory Method :Creates an instance of several derived classes
PrototypeA fully initialized instance to be copied or cloned
SingletonA class of which only a single instance can exist
Structural Patterns
Adapter Match interfaces of different classes
BridgeSeparates an object’s interface from its implementation
CompositeA tree structure of simple and composite objects
DecoratorAdd responsibilities to objects dynamically
Facade A single class that represents an entire subsystem
Flyweight:  A fine-grained instance used for efficient sharing
ProxyAn object representing another object.
Behavioural Patterns

Chain of Resp.: A way of passing a request between a chain of objects

Command :Encapsulate a command request as an object

Interpreter   A way to include language elements in a program

IteratorSequentially access the elements of a collection

MediatorDefines simplified communication between classes

MementoCapture and restore an object's internal state

ObserverA way of notifying change to a number of classes

StateAlter an object's behavior when its state changes

StrategyEncapsulates an algorithm inside a class

Template MethodDefer the exact steps of an algorithm to a subclass

VisitorDefines a new operation to a class without change

Internationalized Domain Names support

Internationalized domain name is a domain name that contains non-ASCII characters.

   Ability to host WCF with IDN name
   Client can call the service by using IDN name

Fig 1: Display the config settings


Uri has two properties Host and DnsSafeHost. These properties contain Unicode or Punycode values depending upon the IDN configuration settings
  • "None" - no conversions are performed by Uri.Host or Uri.DnsSafeHos
  • "AllExceptIntranet" - uri.Host remains Unicode and uri.DnsSafeHost is converted to Punycode
  • "All" - uri.DnsSafeHost is converted to Punycode for internet addresses, and remains Unicode for intranet addresses

Support for UDP Endpoint


   WCF 4.5 allows to use the UDP protocol for communication, so that developer can create the oneway operation message(fire and forget). In certain scenario UDP is much faster than TCP protocol, because TCP add extra validation to check message are delivered in order. But in case of UDP data deliver is not guaranteed

Configuration settings
    <service name="TestService" behaviorConfiguration="MyServiceBehaviour">
         <endpoint address="" binding="udpBinding"
         Binding Configuration ="MyBindingSetting" contract="iservice">
          <Identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
      </service>

Multiple Authentication Support

When you develop an ASP.Net application, multiple authentication modes are enabled by changing the “Authentication” setting on virtual directory

Similarly WCF4.5 provides multiple authentications for single endpoint when using the HTTP transport and transport security. In old version WCF, multiple authentications for single service can be provided by creating different endpoint. But in case of WCF4.5 multiple authentications can be configured using single endpoint.

Steps to enable Multiple Authentication in WCF


Step 1: Create WCF service in host in IIS, Set the authentication as mention below


Step 2: Set the security mode to Transport or TransportCredentialOnly and clientCredentialType to "InheritedFromHost"

    <security mode="TransportCredentialOnly">
        <transport clientCredentialType="InheritedFromHost"/>
    </security>

Compress the Binary Encoder message


Begging from WCF 4.5 onward, WCF binary message encoder supports message compression. Type of compression can be mention in the binding settings

Points to remember:

Both the client and the service must configure the CompressionFormat property, if service is configured with compression and client is not configured then system will throw exception.
Compression will work for HTTP, HTTPS and TCP protocol

You need to create the custom binding to use this feature

Compression is mostly useful if network bandwidth is a bottleneck. In the case where the CPU is the bottleneck, compression will decrease throughput.

    <custom Binding>
        <binding name="BinaryCompressionBinding">
          <binaryMessageEncoding compression Format ="GZip"/>
           <http Transport />
         </binding>
      </custom Binding>

Channel Factor Caching

In some client application Channel Factory is used to create a communication between Client and Service. Creating ChannelFactor will increase the overhead by following operation.

Constructing the Contract Description tree

Reflecting all of the required CLR types

Constructing the channel stack

Disposing of resources

In order to avoid this overhead, WCF 4.5 introduced the caching mechanism for ChannelFactor.
Caching will take three types of values

CacheSetting.AlwaysOn - All instances of Client Base within the app-domain can participate in caching

CacheSetting.AlwaysOff - Caching is turned off for all instances of Client Base

CacheSetting.Default - Only instances of Client Base created from endpoints defined in configuration files participate in caching within the app-domain

    Client Base < IService>.CacheSetting = CacheSetting.AlwaysOn;
            Foreach (string id in lstEmpIds)
            {
                Using (Test Client proxy = new Test Client(new BasicHttpBinding(),
                                                     new Endpoint Address(address)))
                {
                    // ...
                    proxy.GetEmployeeDetails (id);
                    // ...
                }
            }

Simple to expose HTTPS with IIS

WCF 4.0

WCF 4.0 has one of new feature called default endpoint, when ever new service is created default endpoint created with ‘basicHttpBinding’. But if you need to expose the service in ‘HTTPS’ binding then you need to Explicitly create the endpoint and provide all information.

WCF 4.5

In WCF 4.5, default endpoint can be created with HTTPS binding, by simply specifying the SSL and enabling ‘https’ in IIS setting

To Create a End Point:

Step 1:Create the WCF service and browse the WSDL, you will find only basicHttpBinding as shown below


Step 2: Host the WCF service in IIS and set the ‘https’ binding for the website
Step 3: Browse the wsdl file from IIS, you can see the https enabled by default. It is so simple WCF 4.5


Configuring WCF Services in Code

In general, WCF provides option to configure the service using config file or through code.
In older version of WCF (4.0 or older), if you want to configure the web hosted service, then you need to create a Service Host Factory that created the Service Host and performed any needed configuration.

But in case of WCF 4.5 it is very simple, you need to define a public static method called Configure with the following signature in your service implementation class. This method will be called before service host is opened.

Note: If static Configuration () method is specified, setting mention in app.config or web.config file will be ignored.

Code sample:
public class Service : IService
{
    public static void Configure(ServiceConfiguration config)
    {
       Service Endpoint se = new Service Endpoint(new Contract Description("IService1"),
       new BasicHttpBinding(), new Endpoint Address("basic"));
       se.Behaviors.Add (new MyEndpointBehavior ());
       config.AddServiceEndpoint (se); 
       config.Description.Behaviors.Add(new ServiceMetadataBehavior { 
                                                HttpGetEnabled = true});
        config.Description.Behaviors.Add (new ServiceDebug Behavior {
                                     IncludeExceptionDetailInFaults = true});
    }
Public string Get Data (int value)
{
                        Return string.Format ("You entered: {0}", value);
}
}

Streaming Improvements


WCF 4.5 support for true asynchronous streaming. Let see what is mean by true asynchronous streaming
  • In previous version, When WCF service is sending streamed messages to multiple clients. Service will be block its thread to transfer to next client till the slow client is received the message.
  • But in case of WCF4.5, service does not block one thread per client anymore and will free up the thread to service another client
Enabling asynchronous streaming
In previous versions of WCF when receiving a message for an IIS-hosted service that used streaming message transfer, ASP.NET would buffer the entire message before sending it to WCF. This would cause large memory consumption.

  • This buffering has been removed in .NET 4.5 and now IIS-hosted WCF services can start processing the incoming stream before the entire message has been received, thereby enabling true streaming.

Generating a Single WSDL Document

In WCF 4.0 and lower version, generated WSDL file does not contain all metadata information in single file. WSDL file will refer the other document using ‘import’ statement as shown below. So when third party try to consume the service using WSDL has to explicitly add these references.
In WCF 4.5, service provide two option to create the WSDL , we can create WSDL information in single file


Web Socket Support

Web Socket is a web technology providing dbi directional communications channels over a single TCP connection.
Web Socket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The Web Socket Protocol is an independent TCP-based protocol.
Two new bindings are added in WCF4.5 to support communication over Web Socket. NetHttpBinding NetHttpsBinding

Default - ASP.NET Compatibility Mode


In general WCF service hosting AppDomain can run in two different mode
  • Mixed Transports Mode(Default): In this mode does not participate in ASP.NET HTTP pipeline and it behaves consistently independent of hosting environment and transport.
  • ASP.Net Compatibility Mode: In this mode, service will participate in ASP.Net HTTP pipeline and it is similar to old web service (.asmx). ASP.NET features such as File Authorization, UrlAuthorization, and HTTP Session State are applicable to services running in this mode

In WCF 4.5 default aspNetCompatibilityEnabled attribute to true in web.config

WCF 4.5 Configuration Settings 


WCF 4.0 Configuration file


Configuration tool tips

In WCF 4.5, tooltips are provided for configuration file, this makes the developers job simple



XmlDictionaryReaderQuotas

XmlDictionaryReaderQuotas contains configurable quota values for XML dictionary readers which limit the amount of memory utilized by an encoder while creating a message. While these quotas are configurable, the default values have changed to lessen the possibility that a developer will need to set them explicitly

MaxArrayLength
Int32.MaxValue
MaxBytesPerRead
Int32.MaxValue
MaxDepth
128 nodes deep
MaxNameTableCharCount
Int32.MaxValue
MaxStringContentLength
Int32.MaxValue



Simplified Generated Configuration Files


 In old version WCF, configuration files generated at the client side will have all default setting and it looks complex. But in WCF 4.5, when you generate the configuration file using SvcUtil.exe tool or Service Reference only non-default value will be available in the configuration file.

 Configuration file generated in WCF 4.0
  
   

Configuration file generated in WCF 4.5




Contract-First Development


In WCF4.5, Using "SvcUtil.exe" you can generate only the contract files, in old version this feature is not available. If you create the proxy using "SvcUtil.exe", system will generate the contract, service client operation and data contract in single "service.cs" file. If you want to generate only contract you can use this simple command "/serviceContract".


Task-based Async Support


WCF Configuration Validation

In old version of WCF, configuration files are not validated while building the project. But in WCF 4.5 while compiling the project, validation errors will be displayed as warning message in visual studio.


Task-based Async Support

In WCF4.5, by default Task based async service operations methods are generated while Adding Service Reference. This is done for both synchronous and asynchronous method. This allows the client application to call the service operation using Task based programming model.

In WCF 4.5, if you select the “Generate asynchronous operations” while adding service reference. Old form of async operations methods are created in the proxy class




Service Client proxy generated using WCF 3.5


      
Service Client proxy generated using WCF 4.5

  





New Concepts in WCF 4.5


 This article explains about the new features introduced in WCF 4.5. Microsoft has brought new features in WCF 4.5 to reduce the developer’s job and maintain the code



All new features of WCF 4.5 is explained in different parts


Introdution to WCF 4.0

This article explains about the new features introduced in WCF 4.0.

.Net framework comes with new features and improved areas of WCF. It was mainly focused on simplifying the developer experience, enabling more communication scenario and providing rich integration with WWF.
The following items specifies the new features of WCF 4.0

Simplified configuration

This new feature shows simplification of WCF configuration section by providing default endpoint, binding and behavior configuration. It is not mandatory to provide endpoint while hosting service. Service will automatically create new endpoint if it does find any endpoint while hosting service. These changes make it possible to host configuration-free services.

Discovery service

There are certain scenario in which endpoint address of the service will be keep on changing. In that kind of scenario, client who consume this service also need to change the endpoint address dynamically to identify the service. This can be achieved using WS-Discovery protocol.

Routing service

This new feature introduces routing service between client and actual business service. This intermediated service Act as broker or gateways to the actual business services and provides features for content based routing, protocol bridging and error handling

REST Service
    There are few features helps while developing RESTful service.
    Automatic help page that describes REST services to consumer
    Support for declarative HTTP catching

Workflow service

  Improves development experience
  Entire service definition can be define in XAML
  Hosting workflow service can be done from .xamlx file, without using .svc file
  Introduce new “Context” bindings like BasicHttpContextBinding, WSHttpContextBinding, or NetTcpContextBinding
   In .Net4.0, WorkflowServiceHost class for hosting workflow services was redesigned and it is available in System.ServiceModel.Activities assembly.
   In .Net3.5, WorkflowServiceHost class is available in System.WorkflowServices assembly
   New messaging activities Send Reply and Receive Reply are added in .Net4.0