Saturday, August 15, 2015

WCF Single (One way) contracts

Single Contract
Need to mark IsOneWay attribute true in operation contract to the service method that we want to execute in one way mode.
Its good practice to use one way for service methods returns void and methods having independent operations.
Benefit: Client code execution not halt (wait) till service method execution completes.

    [ServiceContract]
    public interface IService1
    {   
        [OperationContract(IsOneWay=true)]
        void SetData(int value);

    }
    public class Service1 : IService1
    {
        public void SetData(int value)
        {
            Thread.Sleep(value);
        }          
    }

Client Code:
    static void Main(string[] args)
    {
        SerDuplex.Service1Client _client = new SerDuplex.Service1Client();
        Console.WriteLine("Client execution started..." + DateTime.Now.ToString());
        _client.SetData(10000);
        Console.WriteLine("Client execution completed..." + DateTime.Now.ToString());
        Console.ReadLine();
    }
Results:











Monday, August 10, 2015

Concurrency in WCF Services

Concurrency in WCF refers controlling number of threads in a given session context. ConcurrencyMode can be used with ServiceBehavior attribute.

Concurrency Modes
  • Single: Only one thread allowed to run in a session context, multiple calls to service served one by one.
  • Multiple: Multiple threads allowed to run in a session context so multiple calls to the service could be served simultaneously, calls could be from same client or different clients.To use this mode service should be designed thread safe. Operations on object's states(operations changing state of objects) should be locked, so that other thread couldn't access those in between operations.
  • Reentrant:  This is modified mode of 'Single'. Only one thread is allowed to run, any other call to the service in queue may start to serve when current one calls some other wcf service.So when proceed thread calls some other wcf service the thread released locks and other queued call may start.

     [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData();
    }
    [ServiceBehavior(InstanceContextMode= InstanceContextMode.PerCall, ConcurrencyMode= ConcurrencyMode.Multiple)]
    public class Service1 : IService1
    {
        int instanceCount =0;
        object thislock = new object();
        public string GetData()
        {
            lock (thislock) //Loc is important when you using "Multiple" concurrency mode
            {
            Thread.Sleep(1000);
            return string.Format("Instance Count:{0}, Session Id:{1}, Thread Name: {2}, Time: {3}", ++instanceCount, OperationContext.Current.SessionId, Thread.CurrentThread.Name, DateTime.Now.ToString());
            }
        }    
    }

Sunday, August 9, 2015

Sessions with WCF Service

Sessions in WCF refers controlling correlation of messages between two end points.

Session Modes
  • Allowed: Clients can connect with or without establishing session 
  • Required: Client can connect only with establishing session 
  • NotAllowed: Client can connect only without session
    [ServiceContract(SessionMode= SessionMode.Required)]
    public interface IService1
    {
        [OperationContract]
        string GetData();
    }

Session is not supported by all bindings. Only WS-*, netTcpBinding & netNamedPipe are support wcf sessions.

If we use bindings other than mentioned above, service throws exception






Instance Context Modes
  • PerCall: Each request made to the service is served by a new instance of service
  • PerSession: All requests made to the service served by a single service instance for a particular single session
  • Single: All request made to the service served by a single service instance even from different clients
   [ServiceBehavior(InstanceContextMode= InstanceContextMode.PerSession)]
    public class Service1 : IService1
    {
       int counter = 0;
        public string GetData()
        {
            return string.Format("Counter : {0} , Session Id: {1}", counter++, OperationContext.Current.SessionId);
        }
    }

Below are the results of 9 scenarios

Session Mode : Allowed

1. InstanceContextMode.PerCall : Session maintained but new instance serving every method call









Wednesday, August 5, 2015

Wcf Transactions

Wcf provides transaction so operations(wcf methods) those are part of a single work unit can be called in a transaction. Operations could be from same or different wcf services.

If any one method out of all methods called in one transaction fails & thrown exception then all other method's operations also rolled back.
Three options are available of transaction flow:
  • Allowed: Marked service method can be called with in transaction or without transaction
  • NotAllowed: Marked service method can't be called in transaction
  • Mandatory: Marked service method must be called in transaction only

Steps to make Wcf service transaction enabled:
  • Create binding tag with attribute transactionFlow is true
    <bindings>
      <wsHttpBinding>
        <binding name ="TransBind" transactionFlow="true"></binding>
      </wsHttpBinding>
    </bindings>
  • Assign binding name to bindingConfiguration attribute of endpoint
    <services>
      <service name="WcfTranService1.Service1" behaviorConfiguration="serviceBehavior">
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
        <endpoint address="" binding="wsHttpBinding" contract ="WcfTranService1.IService1" bindingConfiguration="TransBind"></endpoint>
      </service>
    </services>
  • Mark method in interface with TransactionFlowOption.allowed in TransactionFlow 
        [OperationContract]      
        [TransactionFlow(TransactionFlowOption.Allowed)]
        void SetData(int value);

Sunday, August 2, 2015

Transport & Message Security in WCF

WCF provides inbuilt service security, need to configure only as per requirements.

Message Security: This is end to end security, encrypted & signed messages transported, security is in messages itself. Its recommended when some other mediator (service, external routers) exist between client and service. Our won (custom) algorithms can be used for encryption/decryption.
User and Password need to pass to service before calling service methods.

Modes of security to achieve transfer security
  • Transport
  • Message
  • TransportWithMessageCredential
Transport Security
This security achieved by by transport protocol https using SSL certificate. SSL (Secure Sockets Layer) certificate is supplied by Microsoft, its paid.
Transport security is available for all bindings except 'wsDualHttpBinding'.
Transport security is based on
  • Caller authentication
  • Message integrity
  • Message Confidentiality 
Scenarios to use:
  • Intranet (Client and service are in same network)
  • Client & server communicating directly, there is no other intermediate system
    (If there is some intermediate system that also should communicate on new SSL).
Advantages:
  • Caller need not to understand WS security specifications
  • Better performance
  • Hardware accelerators can be used for more better performance
Disadvantages:
  • Recommended scenarios are intranet, or point to point means there transport should not done through some other intermediate system
  • Provide limited set of credentials
Message Security 
In message security credentials are encapsulated with every message & messages are encrypted & signed. It uses WS-Security specifications for message security, WS-Security specifications specify enhancements on SOAP.
If we are using ClientCredentialType 'windows' then service uses windows credentials in token to secure messages. Other than windows authentication types are 'Certificate', 'UserName', 'IssuedToken' these all are required service certificate that is used to secure messages.
Service uses service certificate as authentication token.

Saturday, August 1, 2015

Tracing in WCF Service

Tracing in wcf service enabled developers to get logged information about events. Only config settings can enable tracing in wcf.

Below given are trace levels, combination of these trace levels can be used  for 'SwitchValue' attribute of Source element.
  • Critical 
  • Error  
  • Warning 
  • Information
  • Verbose
  • Activity Tracing
  • All
There are number of Trace sources, traces generated within an assembly are accessed by the listeners defined for that source.
Common listener file can be used for different configured traces sources.
Commonly used is System.ServiceModel
  • System.ServiceModel: Logs all stages of WCF processing, whenever configuration is read, a     message is processed in transport, security processing, a message is dispatched in user code, and so on.
  • System.ServiceModel.MessageLogging: Logs all messages that flow through the system.
  • System.IdentityModel
  • System.ServiceModel.Activation
  • System.IO.Log: Logging for the .NET Framework interface to the Common Log File System (CLFS).
  • System.Runtime.Serialization: Logs when objects are read or written.

Config Settings:
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior >
          <serviceMetadata httpGetEnabled="true" />         
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <diagnostics>
      <messageLogging logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
        logMalformedMessages="true" maxMessagesToLog="20000" maxSizeOfMessageToLog="10000">       
      </messageLogging>
    </diagnostics>
  </system.serviceModel>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"  switchValue="Error, Critical" >
        <listeners >
          <add name="log" initializeData="E:\TracedLog.svclog" type="System.Diagnostics.XmlWriterTraceListener"></add>
        </listeners>
      </source>
    </sources>
  </system.diagnostics>

Sunday, July 26, 2015

Self Hosting of WCF Service

WCF service can be hosted with IIS, Self hosting & WAS server.

Self Hosting : In self hosting of WCF service we can host the service in our own application domain.
Whole WCF service can consists in an assembly, as you run the application (assembly) service got started and can be accessed.

Port you are using for service should not be in use by other IIS site and this port should be open on server in order to access it publicly.



Source Code:


Self hosting class
namespace ConsoleApplication1
{
    public class clsSelfHosting
    {
        static void Main(string[] args)
        {
            ServiceHost host;
            Uri uri = new Uri("http://localhost:1300/MyWCFSelfHosting");

            host = new ServiceHost(typeof(ConsoleApplication1.Service1), uri);
            host.AddServiceEndpoint(typeof(IService1), new WSHttpBinding(), "");

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);
            host.Open();
            Console.WriteLine("Service Started...");
            Console.ReadLine();
        }       
    }
}

Sunday, July 12, 2015

Service Oriented Architecture (SOA)

Service oriented architecture is an architecture style provides a way of making business applications using loosely coupled architecture of services.

SOA stands on services and communication between services using standard messages.

Services: A services is self contained & self-explanatory business logic accessible across platforms.

Services should be –
  • Self contained business logic
  • Self-explanatory
  • Hosted to be discovered by any one in web world 
  • Accessible on any platform in web world 

Messages: Messages are standard format text that is readable across platforms to communicate among services.

Messages should be –
  • Standard
  • Understandable across platforms in web world
  • Able to explain services


Saturday, July 11, 2015

Memento Design Pattern

Memento pattern is a way to preserve internal state of an object without violating encapsulation.

It is a widely used behavioral pattern.

There are three section of this pattern

Originator:
This is the original object for that memento get created
Memento: This is the copy of original class to preserve the original state of originator object.
Care Taker: This object holds memento object to restore to originator at any point of time.


Requirement:
During changing of object state if something goes wrong, object can be reverted to original state.

Use:
Original state can be re-stored at any point of time during application running.

Problem Solved:
Generally when required people restore object to its original state from database. So by using this pattern no need to query database to restore object.


Sample Code:

    
/// <summary>
    /// Original class
    /// </summary>
    public class Origintor
    {
        private string name;
        private string mobile;
        private string eMail;

        public Origintor(string _name, string _mobile, string _email)
        {
            name = _name;
            mobile = _mobile;
            eMail = _email;
        }

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public string Mobile
        {
            get
            {
                return mobile;
            }
            set
            {
                mobile = value;
            }
        }

        public string Email
        {
            get
            {
                return eMail;
            }
            set
            {
                eMail = value;
            }
        }

        public Memento SaveMemento()
        {
            return new Memento(name, mobile, eMail);
        }

        public void RestoreMemento(Memento objMemento)
        {
            this.Name = objMemento.Name;
            this.Mobile = objMemento.Mobile;
            this.Email = objMemento.Email;
        }
    }

Builder Design Pattern

The intent of this pattern is to separate construction of an object from its representation, so the same construction process can create different representation.

Its a creational design pattern.
Separates presentation of an object from its construction process.

There are three sections of this pattern:
  • Builder: Builder is responsible for defining construction process of each individual part of product. Builder has these small construction processes in it. 
  • Director: Director calls concrete builder of product as per client requirement.
  • Product: Product is final product that have multiple forms depends on which builder created the product.

Requirement: Whenever we have to create same kind of products with something different representation, we need this pattern.

Use: We can create different products using same construction process.

Problem Solved:  For creating products having different representation, no need to create whole separate process for each.



Sample Code:


    public class ReportDirector
    {
        public ReportDirector()
        {
        }

        public Report CreateReport(ReportBuilder reportBuilder)
        {
            reportBuilder.SetReportType();
            reportBuilder.SetReportTitle();
            reportBuilder.SetReportHeader();
            reportBuilder.SetReportFooter();
            return reportBuilder.GetReport();       
        }

    }

Friday, July 10, 2015

Abstract Factory Pattern

Provides a way to encapsulate a group of individual factories those have common theme (related) without specifying their concrete classes.

  • Its an important creational pattern
  • Abstract factory is an extension on factory pattern


Requirement: If you have created many factories or looking to create, client code become complex and scattered to call many factories. In that case abstract factory provides a centralized & simple way to call different individual factories using abstract factory.
Client only knows about Abstract factory & calls only Abstract factory for all individual factories.

Use: Client is able to call different related concrete factories from a single point of contact.
Client doesn't know about concrete classes & concrete factories. Client is aware only with abstract factory & abstract products (Interfaces).

Problems Solved: New concrete factories with related theme can be added without updating client.







































Sample Code:


    public abstract class AbstractFactory
    {      
        /// <summary>
        /// Get Connection Factory
        /// </summary>
        /// <param name="connectionType">
        /// 1- Sql Connection
        /// 2- Oledb Connection
        /// </param>
        /// <returns></returns>
        public abstract Connection GetConnectionObject(int connectionType)
        {
           return (new ConnectionFactory()).GetConnectionObject(connectionType);
        }

        /// <summary>
        /// Get Command Factory
        /// </summary>
        /// <param name="commandType">
        /// 1- Sql Command
        /// 2- Oledb Command
        /// </param>
        /// <returns></returns>
        public abstract Command GetCommandObject(int commandType) 
        {
           return (new CommandFactory()).GetCommandObject(commandType);
        }
     }

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...