Wednesday 30 December 2015

Please explain different modes of security in WCF? Or Explain the difference between Transport and Message Level Security.



In Windows Communication Foundation, we can configure to use security at different levels

  •  Transport Level security.
  •  Message Level Security


Transport Level security.:-

Transport Level security means providing security at the transport layer itself. When dealing with security at Transport level, we are concerned about integrity, privacy and authentication of message as it travels along the physical wire. It depends on the binding being used that how WCF makes it secure because most of the bindings have built-in security.


  <netTcpBinding>
         <binding name=”netTcpTransportBinding”>
                    <security mode=”Transport”>
                          <Transport clientCredentialType=”Windows” />
                    </security>
          </binding>
  </netTcpBinding>


Message Level Security.:-

For Tranport level security, we actually ensure the transport that is being used should be secured but in message level security, we actually secure the message. We encrypt the message before transporting it.

   <wsHttpBinding>

            <binding name=”wsHttpMessageBinding”>
                          <security mode=”Message”>
                                     <Message clientCredentialType=”UserName” />
                          </security>
             </binding>
     </wsHttpBinding>



It totally depends upon the requirements but we can use a mixed security mode also as follows:

  <basicHttpBinding>
             <binding name=”basicHttp”>
                          <security mode=”TransportWithMessageCredential”>
                               <Transport />
                               <Message clientCredentialType=”UserName” />
                          </security>
              </binding>
       </basicHttpBinding>




In this above post I explained  how to use security at different levels in WCF service. I hpe you enjoyed it so please send your feedback and queries. Thnak You.

Tuesday 29 December 2015

What is transaction in WCF?

What is transaction and committed transaction in WCF?

A transaction is a collection or group of one or more units of operation executed as a whole. It provides way to logically group multiple pieces of single work and execute them as a single unit. In addition, WCF allows client applications to create transactions and to propagate transactions across service boundaries.

A transaction that executes successfully and manages to transfer the system from the consistent state A to the consistent state B is called a committed transaction.


What is Two-phase commit protocol in WCF? Why is it needed?

Consider for example client calling multiple service or service itself calling another service, this type of system are called as Distributed Service-oriented application. Now the questions arise that which service will begin the transaction? Which service will take responsibility of committing the transaction? How would one service know what the rest of the service feels about the transaction? Service could also be deployed in different machine and site. Any network failure or machine crash also increases the complexity for managing the transaction. This problem is resolved by using two phase protocol.

All the transactions in WCF complete using two phase commit protocol. It is the protocol which enables transactions in a distributed environment. This protocol mainly consist of two phases:

Prepare phase: In this phase the client application performs the operations of a WCF service. WCF service determines whether the requested operation will be successful or not and notify the client about the same.
Commit Phase: In the commit phase the client checks for the responses it got from the prepare phase and if all the responses are indicating that the operation can be carried out successfully the transaction is committed. If the response from any one of the operations indicates failure then the transaction will be rolled back. The actual operation on the service end will happen in the commit phase.
WCF service will have to send the notification of whether the operation will succeed or fail to the client application. It means that the One way operations can never support transactions. The operations that support transactions have to follow the Request-Response MEP. Also the applied binding should support WS-Atomic Transaction protocol like wsHttpBinding.

What is Transaction Propagation in WCF? Explain with example.

Suppose that there are two services CreditService and DebitService. CreditService has operation Credit(int accountId, double amount) and DebitService has operation Debit(int accountId, double amount). If you want to transfer amount from one account to another account, you need to call both the services. You also need to ensure that both the services should either succeed or fail together. You can achieve this by propagating the transaction of first service call to the second service call. Transaction Propagation is supported by WCF. You can propagate transaction across the service boundaries. It enables multiple services to participate in same transaction.

You can enable/disable transaction propagation using configuration as below:


<bindings>
   <netTcpBinding>
     <binding transactionFlow="true"></binding>
   </netTcpBinding>
</bindings>

Above configuration ensures that transaction can be propagated. However it does not force the transaction propagation until you specify for particular operation. You need to enable transaction flow for the operations whom you want to be part of transaction as below:


[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Credit(int accountId, double amount);
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);

Note: You can have single operation as which can do credit and debit. However I have separated as two for illustrating about transaction.

transactionFlow and TransactionFlowOption together enables the transaction flow for particular operation. If you enable only one of these two, transaction flow can not be enabled.

There are 3 possible values for TransactionFlowOption:

1. TransactionFlowOption.Mandatory: specifies that this function can only be called within a transaction.
2. TransactionFlowOption.Allowed: specifies that this operation can be called within a transaction but its not mandatory.
3. TransactionFlowOption.NotAllowed: specifies that this operation can not be called within a transaction.


How to create WCF transaction?

There are some steps you need to follow to enable transaction for a WCF service as below:

Step 1: Decorate the operation contract with TransactionFlow attribute for enabling the transaction.


<code>[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);

Step 2: Create the service class which implements the service contract and set the operation behavior with TransactionScopeRequired = true. This attribute is used to enable the service transaction when the client transaction is not available.


<code>[OperationBehavior(TransactionScopeRequired = true)]
public bool Debit(int accountId, double amount)
{
  // Debit logic goes here
}


Step 3: Enable transaction flow in configuration file.

<bindings>
      <wsHttpBinding>
        <binding name="myTransactionBinding" transactionFlow="true" ></binding>
      </wsHttpBinding>
    </bindings>





In this above post I explained What is transaction  in WCF. I hpe you enjoyed it so please send your feedback and queries. Thnak You.

Monday 28 December 2015

What is MEP (Message Exchange Pattern) in WCF?


MEP describes the way in which Client and Server communicates. It describes how client and server would be exchanging messages to each other. There are three types of message exchange patterns:


  1. Request- Replay (default): When client makes a request to the WCF service, it waits to get response from service till receiveTimeout expires. If client does not get any response from the service before receiveTimeout expires, TimeoutException is thrown.
  2. One-Way: When client makes a request to the WCF service, it does not wait for reply from the service. Service does not send any response to the sender, even if any error occurs in the communication. It does not support out or ref parameters. It does not return value to an operation. One way operation do not return values or exceptions. But while dispatching the one-way operation any error because of communication problems like host not available or address missmatch will through an exception on client side, again this depends on service instance mode and trasport session
  3. Duplex/Callback: Client and service can sends messages to each other by using One-way or request-reply messaging. This MEP is supported by only bidirectional-capable bindings like as WS Dual, TCP and IPC bindings.To make a duplex contract, you must also define a callback contract and assign the typeof that callback contract to the CallbackContract property of your service contract’s ServiceContract attribute.



public interface IMyDuplexServiceCallback
{
[OperationContract(IsOneWay = true)]
void Progress(string status);
}

[ServiceContract(CallbackContract = typeof(IMyDuplexServiceCallback))]
public interface IMyDuplexService
{
[OperationContract(IsOneWay = true)] //One-Way
void SaveData();

[OperationContract] //Request-Reply.
string GetData();
}

For Duplex MEP, you need to specify the one of the binding which supports bi-directional like wsDualHttpBinding as in below example:


<services>
  <service name="MyWCFServices.DuplexService">
    <endpoint address ="" binding="wsDualHttpBinding" con-tract="MyWCFServices.IDuplexService">
    </endpoint>

You can configure MEP using IsOneWay property of OperationContract attribute as below:

[OperationContract(IsOneWay = true)]





In this above post I explained Message Exchange Pattern in WCF service. I hpe you enjoyed it so please send your feedback and queries. Thnak You.

Difference between DataContract and MessageContract in WCF

Data Contract in WCF is an agreement between a service and a client that describes what type of data will be exchanged between them? I other words, Message Contract describes the structure of SOAP message that is passed between  service and client. Using Data Contract, we actually control the contents ( message body) of a SOAP message while Message Contract provides complete control over structure of SOAP message.

In Windows Communication Foundation, there are two types of Contracts:

  1. Behavioral Contracts
  2. Structural Contracts

Both DataContract and MessageContract are structural contracts that compliment each other serving different purposes. Lets now understand the difference between DataContract and MessageContract with the help of an example.



DataContract Example:
Consider a WCF Service having an operation as follows:


[ServiceContract()]
public interface IStudentService
{
    [OperationContract()]
    StudentInfo GetStudentById(int studentId);
}

Here the return type is StudentInfo which is basically a CLR type defined below as a DataContract.


[DataContract(Namespace="http://www.something.com/students/")]
public class StudentInfo
{
       [DataMember(Name="StudentId", Order=1)]
       public int ID;

       [DataMember(Name="FirstName", Order=2)]
       public string FName;

       [DataMember(Name="LastName", Order=3)]
       public string LName;
}



When the service method will be called, this StudentInfo type will be returned as part of the SOAP response message body.
If we look into this "StudentInfo" Data Contract, we are providing different details about data being transferred back to consumer. For example,
Order = 1,2,3 defines the order of the data member in response message body.
Name = "some name" dictates the name of particular data member as part of response message body.
But through all these attributes, we are actually controlling the contents of the SOAP message body only. And in most of the cases, developers are concerned with controlling the body part of the message instead of whole SOAP message.

MessageContract Example:

As we have seen in above example that DataContract has limited control over the SOAP message and all that control is related to contents inside body of the SOAP message. But there are scenarios, when we need more control over SOAP message. So, MessageContract is the answer in such cases.

Now consider a business scenario, an authentication code is required to access our service i.e. IStudentService. In this case functionality provided by our service will remain the same but authentication code validity is additional pre-requisite now. So in such cases, SOAP message header is the most reasonable place to store the authentication code while calling the service method.

Look into the below implementation of this scenario:

[MessageContract(IsWrapped = false)]
public class StudentInfoRequestMessage
{
       [MessageHeader()]
       public string AuthCode;

      [MessageBodyMember()]
      public int StudentId;
}

[MessageContract(IsWrapped = false)]
public class StudentInfoResponseMessage
{
      [MessageBodyMember()]
      public StudentInfo MyStudentInfo;
}

[ServiceContract]
public interface IStudentService
{
        [OperationContract]
        StudentInfoResponseMessage GetStudentById(StudentInfoRequestMessage stdInfoMessage);
}

public class StudentService : IStudentService
{
  public StudentInfoResponseMessage GetStudentById(StudentInfoRequestMessage stdInfoMessage)
     {
         private const string AuthCode = "ali123salman";

               //Validation Check
               if (stdInfoMessage.AuthCode != AuthCode)
               {
                       //fault response
               }    
              //routine code
     }
}



In this above post I explained Difference DataContract and MessageContract in WCF and how to choose one of them. I hope its helpful to reader so please comments your feedback and queries.

What are session modes in WCF? How can you make a service as sessionful?



ServiceContract attribute offers the property SessionMode which is used to specify the session mode. There are three session modes supported by WCF:


  • Session.Allowed(default): Transport sessions are allowed, but not enforced. Service will behave as a per-session service only if the binding used maintains a transport-level session.
  • Session.Required: Mandates the use of a transport-level session, but not necessarily an application-level session.
  • Session.NotAllowed: Disallows the use of a transport-level session, which precludes an application-level session. Regardless of the service configuration, the service will always behave as a per-call service.




[ServiceContract(SessionMode = SessionMode.NotAllowed)]
interface IMyContract
{.................}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract
{.................}








In this above post I explained you can limit how many instances or sessions are created at the application level

Can you limit how many instances or sessions are created at the application level?


Yes, you can limit how many instances or sessions are created at the application level. For this, you need to configure throttling behavior for the service in its configuration file. Some of these important properties are:



  • maxConcurrentCalls limits the total number of calls that can currently be in progress across all service instances. The default is 16.
  • maxConcurrentInstances limits the number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue.
  • maxConcurrentSessions limits the number of sessions a ServiceHost object can accept. It is a positive integer that is 10 by default.






<behaviors>
 <serviceBehaviors>
   <behavior name="ServiceBehavior">
     <serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances ="100" maxConcurrentSessions ="200"/>
   </behavior>





In this above post I explained you can limit how many instances or sessions are created at the application level

Can you control when the service instance is recycled?


Yes, we can control when the service instance is recycled using the ReleaseInstanceMode property of the OperationBehavior attribute. You can control the lifespan of your WCF service. You can set the value of ReleaseInstanceMode property as one of the following:

  • RealeaseInstanceMode.None: No recycling behavior.
  • RealeaseInstanceMode.BeforeCall: Recycle a service object before an operation is called.
  • RealeaseInstanceMode.AfterCall: Recycle a service object after an operation is called.
  • RealeaseInstanceMode.BeforeAndAfterCall: Recycle a service object both before and after an operation is called.


In this post I explained how to control when the service instance is recycled. I hope it is very helpful for you. Please comments your feedback and quries. Thank You.

How is the service instance created? How can you manage or control WCF service instance creation?


Service Instance

Client request can be served by using single service instance for all users, one service instance for one client, or one instance for one client request. You can control this behavior by using the technique called Instance Management in WCF.

There are three instance modes supported by WCF:


  • Per-Call: Service instance is created for each client request. This Service instance is disposed after response is sent back to client.
  • Per-Session (default): Service instance is created for each client. Same instance is used to serve all the requests from that client for a session. When a client creates a proxy to particular service, a service instance is created at server for that client only. When session starts, context is created and when it closes, context is terminated. This dedicated service instance will be used to serve all requests from that client for a session. This service instance is disposed when the session ends.
  • Singleton: All client requests are served by the same single instance. When the service is hosted, it creates a service instance. This service instance is disposed when host shuts down.



You can configure instance mode using [ServiceBehavior] attribute as below:

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]

public class MyService:IGreetingService



In this post I explained what are the Instance mode of supported by WCF. I hope you enjoyed this post please comments your feed back and quires. Thank You.

Fault Contract - Handling Errors in WCF service

What is FaultContract?


How do you handle errors in ASP.NET? It's very simple - just by adding the simple Try & Catch blocks. But when you come to WCF Service, if any unexpected error occurred (like SQL server down/Unavailability of data/Divide By Zero) in service, then error/Exception details can be passed to Client by using Fault Contract.

False Assumption

Most people think that we can't throw FaultException in catch block. It should be only based on some condition (if condition). But it is a false assumption. The main objective is, any type of exceptions(Predicted or Unpredicted) from service to be passed to Client (WCF Service consumer).

Using code:-



    [DataContract()]
    public class CustomError
    {
        [DataMember()]
        public string ErrorCode;
        [DataMember()]
        public string Title;
        [DataMember()]
        public string ErrorDetail;
    }

    [ServiceContract()]
    public interface IGreetingService
    {
        [OperationContract()]
        [FaultContract(typeof(CustomError))]
        string Greet(string userName);
    }

    public class GreetingService : IGreetingService
    {
        public string Greet(string userName)
        {
            // predicted Errors
            if (string.IsNullOrWhiteSpace(userName))
            {
                var exception = new CustomError()
                {
                    ErrorCode = "401",
                    Title = "Null or empty",
                    ErrorDetail = "Null or empty user name has been                                          provided"
                };
                throw new FaultException<CustomError>(exception, "Reason :                                                       Input error");
            }


            // Unpredictable Errors...
            try
            {
              SqlConnection con = new SqlConnection(StrConnectionString);
                con.Open();
                // some database operation code..
                con.Close();

            }
            catch (SqlException sqlEx)
            {
               var exception = new CustomError()
               {
                   ErrorCode = "402",
                   Title = "Null or empty",
                   ErrorDetail = "Connection can not open this " +
                                 "time either connection string is wrong                                     or Sever is down. Try later"
               };
               throw new FaultException<CustomError>(exception, "Reason :                                                       Server down");
            }
            catch (Exception ex)
            {
                var exception = new CustomError()
                {
                    ErrorCode = "403",
                    Title = "Null or empty",
                    ErrorDetail = "unforeseen error occurred. Please try                                      later."
                };
                throw new FaultException<CustomError>(exception, "Reason :                                                        Unforeseen Error");
              
            }


           // If there is no Error...
            return string.Format("Welcome {0}", userName);
        }
    }




In this post I explained how to handle exception at service side in WCF. I hope you enjoyed this post please comments your feed back and quires. Thank You.

Friday 4 December 2015

Serialization of .NET classes into JSON object in C#.Net ?

What is Serialization  ?

Serialization is a programming technique that converts an object in memory to a sequence of bytes. The serialized data is suitable for storage in files and databases, and can be sent to other computer systems across network protocols.

you will see how to use features built-in to the .NET framework to serialize objects to JavaScript object notation (JSON). JSON stores objects and collections of objects in a human-readable, structured text format, and is commonly used in client/server architectures because of its high level of compatibility across a wide range of client programming languages.

.NET Framework Classes

In version 3.5 (and in later versions) of the .NET framework, classes for serializing and deserializing to JSON are included in the framework. The main classes you will use are in System.Runtime.Serialization and System.Runtime.Serialization.Json.

The general process for serializing and deserializing JSON from C# is:


  • Add a reference to the System.Runtime.Serialization library.
  • Add using directives for System.Runtime.Serialization and System.Runtime.Serialization.Json.
  • Define classes for the objects represented using DataContract and DataMember attributes.
  • Create an instance of DataContractJsonSerializer.
  • Use WriteObject() to serialize an object to a stream.
  • Use ReadObject() to deserialize an object from a JSON stream.



Classes and Service Contracts

DataContracts are agreements between clients and servers that describe the information that is to be exchanged between them. Windows Communication Foundation (WCF) uses these extensively, however, you only need a small familiarity with them to use the DataContractJsonSerializer.


The DataContract attribute is used to mark a class as suitable for serialization/deserialization by the DataContractJsonSerializer. The example below defines a class with the minimum attributes needed to work with the serializer.



The attribute DataMember can also be used to control certain elements in the serialization and deserialization process. It has five properties:


Property Name


  1. EmitDefaultValue:- Sets whether or not to serialize the default values for the fields and properties being serialized.
  2. IsRequired:-  Whether the member must be present in the JSON code when deserializing.
  3. Name :- The name of the member when serialized.
  4. Order:- The order of the serialization or  deserialization.
  5. TypeId :-  With derived classes, TypeId is a unique  identifier for this attribute.
Attribute properties are included in the DataMember attribute by specifying the property name and value in parenthesis as shown in this modified version of the UserReg class.




[DataContract]
    class UserReg
    {
        [DataMember(IsRequired = true)]
        public String FirstName;

        [DataMember]
        public String LastName;

        [DataMember(IsRequired = true)]
        public String Gender;

        [DataMember(Name = "EmailAddress", IsRequired = true)]
        public String EmailID;

        [DataMember(IsRequired = true)]
        public String MobileNo;

        [DataMember]
        public String Country;

        [DataMember]
        public String State;

        [DataMember]
        public String City;

        [DataMember]
        public String Address;

        [DataMember]
        public int PinCode;
    }




The example above uses the name property to change how the member EmailID appears in the serialized output. It also marks all members, apart from icon, as required.

Specifying the attribute properties can be useful when building a contract to an existing service that uses names that cannot be used in your class. When serialized,


Serialization with the DataContractJsonSerializer

To serialize a .NET object to JSON, you must create an instance of DataContractJsonSerializer. The constructor for this class has one parameter: a reference to the type of .NET object that is to be serialized or deserialized.

Use the method WriteObject() to perform the serialization and send the output to the specified stream. It can work with most streams that are derived from System.IO.Stream – such as file streams, memory streams, and network streams.



class TestSerialization
    {
        static void Main(string[] args)
        {
            UserReg userReg = new UserReg()
            {
                FirstName = "Rampal",
                LastName = "Singh",
                Gender = "Male",
                EmailID = "rampal.singh0586@gmail.com",
                MobileNo = "8861447949",
                Country = "India",
                State = "Uttar Pradesh",
                City = "Moradbad",
                Address = "Prakash Nagar",
                PinCode = 244255
            };

            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserReg));
            MemoryStream ms = new MemoryStream();
            js.WriteObject(ms, userReg);

            Console.WriteLine("\r\nSerializing of .NET Class into JSON Object in C#\r\n");
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            Console.WriteLine(sr.ReadToEnd());
            sr.Close();
            ms.Close();
            Console.ReadKey();

        }
    }




The code above produces the following JSON output:
















Deserialization with the DataContractJsonSerializer

Deserialization takes JSON-formatted data and converts it into a .NET object in memory. As with serialization, this relies on using an instance of DataContractJsonSerializer. Generally speaking, you will be loading JSON data from a stream (most likely a network stream from communicating with a web server), however, in this example the JSON is hardcoded into a string and then accessed through a MemoryStream.

To deserialize JSON from a stream, use the method ReadObject(). This returns an Object type that you can cast to the desired class.


class TestSerialization
    {
        static void Main(string[] args)
        {

String userData = "{ \"FirstName\": \"Rampal\", \"LastName\": \"Singh\", \"Gender\": \"Male\", \"EmailAddress\": \"rampal.singh0586@gmail.com\", \"MobileNo\": \"8861447949\", \"Country\": \"India\", \"State\": \"Uttar Pradesh\" , \"City\": \"Moradabad\" , \"Address\": \"Prakash Nagar\", \"PinCode\": \"244255\"}";

            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserReg));
            MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(userData));

            UserReg userreg = (UserReg)js.ReadObject(ms);
            Console.WriteLine("\r\nDeserializing JSON object into .NET class Object in C#\r\n");
            Console.WriteLine("User Name: " + userreg.FirstName + "' '" + userreg.LastName);
            Console.WriteLine("Address: " + userreg.Address);
            ms.Close();

            Console.ReadKey();
       }
  }


Output Result:-
















In the above post I explain with example how to Serialization  the .NET classes into JSON objects and Deserialization back into .NET classes as objects. I hove this post very useful to you. I request you to please comments your feedback and questions here. Thamk Your