Saturday, August 22, 2015

Fault Exception in WCF

WCF provides FaultException class that can be used to send exception details to client.

1. Through Exception class object from service 
<serviceDebug includeExceptionDetailInFaults="false"/>









2. Using default FaultException
Through Default FaultException class object from service
throw new FaultException(ex.Message);
OR
Enable includeExceptionDetailInFaults in config
<serviceDebug includeExceptionDetailInFaults="true"/>








3. Through Custom class object (Fault contract) using FaultException class











Service Code:
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [FaultContract(typeof(ClsCustomException))]
        int CalculateCost(string itemCount);
    }

    [DataContract]
    public class ClsCustomException
    {
        [DataMember]
        public string Message { get; set; }
        [DataMember]
        public string Description { get; set; }
        [DataMember]
        public string StackTrace { get; set; }
    }
    public int CalculateCost(string itemCount)
    {
        try
        {
            return int.Parse(itemCount) * 120;
        }
        catch (Exception ex)
        {
            //Without fault exception
            //throw ex;

            //Simple fault exception sending message only to client side
            //throw new FaultException(ex.Message);

            //Fault contract (using our custom class to send details of exception to client)
            ClsCustomException objMyException = new ClsCustomException();
            objMyException.Message = ex.Message;
            objMyException.Description = "Error in itemCount conversion to int";
            objMyException.StackTrace = ex.StackTrace;
            throw new FaultException<ClsCustomException>(objMyException);
        }

    }



Client Code:

        static void Main(string[] args)
        {
            ServiceReference1.Service1Client _client = new ServiceReference1.Service1Client();
            try
            {
                Console.WriteLine("Enter number...");
                Console.WriteLine( _client.CalculateCost(Console.ReadLine()));
                Console.ReadLine();
            }
            catch (FaultException<ServiceReference1.ClsCustomException> ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.Detail.Description);
                Console.WriteLine(ex.Detail.StackTrace);
                Console.ReadLine();
            }
        }

Tuesday, August 18, 2015

RESTful WCF Services

We will understand steps with an example of maintaining players list

Steps to create Wcf REST service 
  1. It requires webHttpBinding.
  2. It requires <webHttp />  tag inside behavior tag.
  3. Create wcf service application
  4. Create methods for add, update, delete, get player
            Player GetPlayer(string id);
            void AddPlayer(string name);
            void UpdatePlayer(string id, string name);
            void DeletePlayer(string id);
            List<Player> GetPlayers();
  5. Mark created methods with below given methods
                 1. WebGet
                 2. WebInvoke

  6. Assign values of parameters in WebGet and WebInvoke as required
    • UriTemplate : Set url format to access the method
      • GetPlayer/{id}
      • UpdatePlayer/{id}/{name}
    • Method
      • POST : To submit data to process
      • PUT : To update resource
      • DELETE : To delete resource
    • RequestFormat
      • RequestFormat= WebMessageFormat.Xml
      • RequestFormat= WebMessageFormat.Json
    • ResponseFormat
      • ResponseFormat= WebMessageFormat.Xml
      • ResponseFormat= WebMessageFormat.Json
    • BodyStyle
      • Bare
      • Wrapped
      • WrappedRequest
      • WrappedRespons






   
5. Service config settings
Note : In below given config settings 4th & 5th points are not compulsory.






Sunday, August 16, 2015

REST Services

REST is an architectural style of making web app/services uses http with its methods and apply certain principals on it to accomplish REST app/services.
REST stand for Representational State Transfer.

Rest service is useful when you required to access service in client script like Javascript, REST services can return data in Json format that can be used in scripting languages.

Principals used to implement RESTful services 
  1. Frame every thing like it is a resource
    Ex. User, Order
  2. Every resource should be represent with a unique url
    Ex. http://gstomar.blogspot.com/users/10
  3. Every request/response should be done with a representation
    Every call should present some view
  4. Interfaces should be simple & uniform
  5. Every request/response should be stateless
    Every request/response should be independent from each other

Methods used to accomplish RESTful services
S.No.
Method
Description
1
GET
Request a specific representation of a resource
2
PUT
Create or Update a resource with supplied representation
3
POST
Submits data to be processed by a resource
4
DELETE
Delete a resource
5
HEAD
Same like GET but accesses only header information
6
OPTIONS
Requests list of supported methods by resource

Saturday, August 15, 2015

WCF Duplex(Two way) contracts

Duplex contract is two way contract, two channels establishes between service & client, client to service & service to client.

Requirement: Whenever we have big service operation that we want to execute one way (Asynchronously), but we want to get notified also when service operation get completed.

Benefit: This way without getting halted for service method completion client get notified when operation completed also can get some return value from service.

Supported bindings : wsDualHttpBinding, netNamedPiepeBinding, netTCPBinding
Only these bindings are able to establish two transport channels.

Steps to implement Two way binding:

Service Side-
  1. Create new callback interface, with one method that will execute on completion of main method
    public interface IClientCallBack
    {
        [OperationContract(IsOneWay=true)]
        void OperationCompleted(string message);
    }
  2. Assign type of new created callback interface to attribute CallbackContract in ServiceContract of main interface
    [ServiceContract(CallbackContract= typeof(IClientCallBack))]
    public interface IService1
    {   
        [OperationContract(IsOneWay=true)]
        void SetData(int value);
    }

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>

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...