Data Contract Serialization Events in WCF

In WCF we use the DataContract to serialize and deserialize the custom data. Sometime you may come across a scenario do some work before or after the data gets serialized or deserialized. These are following four events provided on the DataContract.

image

You are free to give any method name provided method should return void and takes StreamingContext as input parameter. In a block diagram we can show events sequence as follows:

image

You can create these events inside the class decorated with DataContract. Now let us see some real time examples. Let us say you have a DataContract as follows:

 


[DataContract]
    public class Product
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public double Price { get; set; }
     }
}


We have a very simple ServiceContract defined as follows:

 


[ServiceContract]
    public interface IService1
    {

        [OperationContract]
        Product GetProduct(Product p);
      
    }


Service is implemented as follow which is basically echoing the data provided by the client.

 


public class Service1 : IService1
    {


        public Product GetProduct(Product p)
        {
            Product p1 = new Product { Name = p.Name, Price = p.Price };
            return p1; 
        }
    }


So far great now let is consume the service and examine the sequence of the serialization and deserialization events. Service is consumed as follows

 


Service1Client proxy = new Service1Client();
            Product p = new Product { Price = 300, Name = "Pen" };
            var result = proxy.GetProduct(p);
            Console.WriteLine(result.Name + result.Price);
            Console.ReadKey(true);


Now let us go ahead and modify the data contract class by adding the events. Modified class will look like as follows:

 


using System.Runtime.Serialization;

namespace DataContractEventsDemo
{
    [DataContract]
    public class Product
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public double Price { get; set; }

        [OnSerializing]
        void OnSerializing(StreamingContext context)
        {

        }
        [OnSerialized]
        void OnSerialized(StreamingContext context)
        {

        }
        [OnDeserializing]
        void OnDeserializing(StreamingContext context)
        {

        }
        [OnDeserialized]
        void OnDeserialized(StreamingContext context)
        {

        }
    }
}

To find out sequence in which events get executed put a break point on the events. You will find events get executed in following sequence

image

Now consider a real time scenario that if client is not passing price of the product then service should provide a default price value. You can do that in OnDeserialized event as follows:

 

[OnDeserialized]
        void OnDeserialized(StreamingContext context)
        {
            if(Price==0)
            {
                Price = 99; 
            }
           
        }

Now if modify the client and not provide price as shown below

 


  static void Main(string[] args)
        {

            Service1Client proxy = new Service1Client();
            Product p = new Product { Name = "Pen" };
            var result = proxy.GetProduct(p);
            Console.WriteLine(result.Name + result.Price);
            Console.ReadKey(true);
        }

You will get output with default price as follows

clip_image002These events are useful to provide default values, closing connections to data base etc.Hope you find the post useful. Happy Coding.

Multiple bindings in self-hosted WCF Service

Even though WCF is now, more than 5 years old but still I see developers struggling with the multiple bindings specially when hosted in a managed console application. In this post, step by step we will learn to create a WCF Service with multiple bindings and host the service in a managed console application. We will do the following tasks in this post,

  • Create a service with the netTCPBinding
  • Host the service in a console application
  • Add wsHttpBinding EndPoint in the service
  • Consume the service in a client

To start with create a project by choosing either WCF Service Application or WCF Service Library from the WCF tab. I am selecting WCF Service Library project template.

clip_image002

Let us create a very simple service contract as follows


using System.ServiceModel;

namespace MultipleBindingSelfHosted
{
   
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        
    }

}


Next let us implement the service as follows:


namespace MultipleBindingSelfHosted
{
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

       
    }
}


By this step we have created the service and implemented it. Compile the solution to make sure that everything is fine in the WCF project.

Now let us go ahead and add a console application in the project. This application will be the host application in which the service will be hosted. Let us follow the given steps:

  1. Create a console application in the project
  2. Add reference of System.ServiceModel
  3. Add reference of WCF project

Next in the App.config file of the console application we need to add service’s Endpoint configurations. Let us start with adding netTCPBinding Endpoint. To add the configuration follow the steps shown as follows:

  1. Add system.serviceModel
  2. Add services in the system.servicxeModel
  3. Add host base address in the host section
  4. Add Endpoint with netTcpBinding
  5. Add Metadata Endpoint for netTcpBinding

These steps can be done as shown below:

 

<system.serviceModel>

    <services>
      <service name="MultipleBindingSelfHosted.Service1" behaviorConfiguration="MultipleBindingSelfHostedBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:9002/MultipleBindingSelfHosted"/>
          </baseAddresses>
        </host>
        <endpoint address="net.tcp://localhost:9002/MultipleBindingSelfHosted"
                  binding="netTcpBinding" 
                  contract="MultipleBindingSelfHosted.IService1"/>
        <endpoint address="mex"
                  binding="mexTcpBinding" 
                  contract="IMetadataExchange"/>
      </service>
    </services>

  </system.serviceModel>


If you notice above we have added a service behaviour. So let us go ahead and configure the behaviour as follows:

 

<behaviors>
      <serviceBehaviors>
        <behavior name="MultipleBindingSelfHostedBehavior">
          <serviceMetadata httpGetEnabled="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

Great, by this step we have added Endpoint with the netTcpBinding. Next let us go ahead and create instance of the service host by passing service definition class in the constructor.


using System;
using System.ServiceModel; 

namespace MultipleBindingSelfHosted.Host
{
    class Program
    {
        static void Main(string[] args)
        {

            ServiceHost host = new ServiceHost(typeof(Service1));
            host.Open();
            Console.Write("Service is up and running");
            Console.WriteLine("To stop service press any key !!! ");
            Console.ReadKey();
            host.Close();

        }
    }
}


Press F5 to run the host application. You should see host application running as expected as follows:clip_image002[6]

Next we will go ahead and add an Endpoint for wsHttpBinding. To do this follows the steps as discussed follows:

  1. Add new base address
  2. Add new Endpoint with wsHttpBinding
  3. Give name to endpoints in case we may want to access separate Endpoint by providing Endpoint name the client

Add new base address as follows:

<add baseAddress="http://localhost:9001/MultipleBindingSelfHosted"/>

Add new Endpoint as follows. If you notice I have given name to the Endpoint as httpendpoint. You are free to give name of your choice.

<endpoint name="httpendpoint" address="http://localhost:9001/MultipleBindingSelfHosted" 
                  binding="wsHttpBinding" 
                  contract="MultipleBindingSelfHosted.IService1"/>


Also make sure that you have given a name to netTcpBinding Endpoint as well. Next let us go ahead and add metadata endpoint for http binding as well.

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

After configuring two Endpoints app.config of host application will look like as follows:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <system.serviceModel>

    <services>
      <service name="MultipleBindingSelfHosted.Service1" behaviorConfiguration="MultipleBindingSelfHostedBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:9002/MultipleBindingSelfHosted"/>
            <add baseAddress="http://localhost:9001/MultipleBindingSelfHosted"/>
          </baseAddresses>
        </host>
        <endpoint address="net.tcp://localhost:9002/MultipleBindingSelfHosted"
                  binding="netTcpBinding" 
                  contract="MultipleBindingSelfHosted.IService1"/>
        <endpoint address="mex"
                  binding="mexTcpBinding" 
                  contract="IMetadataExchange"/>
        <endpoint name="httpendpoint" address="http://localhost:9001/MultipleBindingSelfHosted" 
                  binding="wsHttpBinding" 
                  contract="MultipleBindingSelfHosted.IService1"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MultipleBindingSelfHostedBehavior">
          <serviceMetadata httpGetEnabled="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

  </system.serviceModel>
</configuration>


Once again go ahead and build and run the application. You should able to get host application running as follows:

image

We have successfully created a self-hosted service with multiple Endpoint. Now let us go ahead and create a client to consume the service. In console application, right click and add service reference. If client is in the same solution then use Discover option else copy paste base address from app.config file of the hosted application.

image

And then you can call the service for two Endpoints as follows

// calling service with TCP binding 
            Service1Client tcpproxy = new Service1Client("tcpendpoint");
            var result1 = tcpproxy.GetData(12);
            Console.WriteLine(result1);

            //calling service with HTTP binding 
            Service1Client httpproxy = new Service1Client("httpendpoint");
            var result2 = httpproxy.GetData(12);
            Console.WriteLine(result2);

            Console.ReadKey(true);


In this way you can create the self-hosted WCF service with multiple Endpoints. I hope this post is useful. Happy Coding!

An error was raised by libgit Category =Ssh error: solved git for Visual Studio

Have you come across the error as shown in below image?

clip_image002

You get the above shown error in Visual Studio while pulling changes from the git server. This error causes because you have local changes without the commit. In this scenario the visual Studio does not give very readable error message. Perhaps you may want to use git command for pull for more information on the error.

clip_image003

The git pull command clearly says that either commit the changes or stash them. If you are not sure about the local changes then better option is to stash them. Local changes can be stashed using the git stash command.

clip_image004

After stashing the local changes (you can commit also) run the git pull command to pull the remote changes from the git server. You should not get any error doing pulling the latest changes.

Hope it helps. Happy coding.

Property Initializers in C-Sharp 6.0

In the C-Sharp 3.0 a new feature Automatic property got introduced. It allows us to create a class as a bag of the setters and the getters. You can create a class as follows:


public class Product
    {
        public int Price { get; set; }
        public string Name  { get; set; }

    }

Each property is backed by a backing filed. When you set value of the property, setter gets executed to set the value of the backing field. Now catch is that to create a read only property you have to invoke the setter in the constructor of the class and make set as private

public class Product
    {
        public int Price { get; private set; }
        public string Name  { get; set; }

        public Product()
        {
            Price  = 10;
        }

    }

In the above class definition the Price property is read only and set to the default value 10 and you can set the value of the name property outside the class.

To create a read only property with the default value, we created a private setter and then set the default value in the constructor. In c-sharp 6.0, you can directly create a read only property with default value without invoking the setter. This feature of C# 6.0 is called Property Initializers

Property Initializer allows you to create a property with the default value without invoking the setter. It directly sets value if the backing field.

image

As you see in the above snippet we are setting the default value of Price property as 10. However after creating the instance of the class. Value of price property can be changed. If you wish you can create read only property by removing the setter.

image

Since setter is optional, it is easier to create immutable properties. For your reference source code harnessing Property Initializer is given below:


using System;
namespace demo1
{
    class Program
    {
        static void Main(string[] args)
        {
            Product p = new Product
            {
                
                Name = "Pen"

            };

            Console.WriteLine(p.Price);

            Console.ReadKey(true);
        }
    }

    public class Product
    {
        public int Price { get;} = 10; 
        public string Name  { get; set; }
    }
}


We can summarize this post discussing purpose of the auto property initializer. It allows us to create immutable property with the user defined default value. Now to create properties with default values, you don’t have to invoke setter.

Happy coding.

Exception Filters in C-Sharp 6.0

So far we deal with the Exceptions as below. As you see in the following code snippet, we are catching the exception and displaying the error message.


using System;
namespace demo1
{
    class Program
    {
        static void Main(string[] args)
        {

            int number = 24;
            try
            {

                int rem = number % 0;
                Console.WriteLine(rem);
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey(true);
        }
    }
}


Challenge in the above snippet is that you cannot apply filter to the exception. Of course you can have if-else statement inside the try catch block but it will cause a particular catch block to get executed and then filter would get applied.

In C# 6.0 a new feature got introduced to apply filter at the catch block. This feature is known as Exception filters. Now a particular catch block can be executed only of the filter is set to true.

image

In the above snippet we are filtering the exception on the various basis like if message contains a particular string then execute a particular catch block or on the basis of the exception source execute a particular catch block.

This feature may be useful in the scenarios in which, you need to perform various actions on if a condition is met in a particular exception type.

For your reference the source code is given below,

using System;
namespace demo1
{
    class Program
    {
        static void Main(string[] args)
        {

            int number = 24;
            try
            {

                int rem = number % 0;
                Console.WriteLine(rem);
            }
            catch (DivideByZeroException ex) if (ex.Message.Contains("dj"))
            {
                Console.WriteLine(ex.Message);
            }
            catch(DivideByZeroException ex) if (ex.Source == "demo1")
            {
                Console.WriteLine(ex.Source);
            }

            Console.ReadKey(true);
        }
    }
}


Exception message does not contain any string dj hence the first catch block will not get executed. However second catch block will be executed since source of the exception is demo1. You will get the expected output as below:

image

I hope concept of Exception filter is clear to you now and you will harness C# 6.0 feature in your project.

Happy coding

Child Actions in ASP.NET MVC

Read full post on falafel blog

Child Actions are the action methods which can be invoked within the view. This is used to work with the data in the view, which are not related to the main action method. For example, if you want to create a data driven widget in the view using data that is not related to the main action method, you will need to use the child action method.
In ASP.NET MVC any action can be used as a child action. However, to use an action only as a child action and attribute it with the ChildActionOnly. It will make sure the action is not called by any user request and will only be used in the view. A child action can be created as shown below:

Read full post on falafel blog

Prototypical inheritance in JavaScript

Read full post on falafel blog

Before we can understand prototypical inheritance, let us start with a problem statement. You have a student for whom you need to:

  • Calculate their grade
  • Print the grade

In JavaScript this can be simply implemented as follows:


var studentMarks;
var studentGrade;

function FindGrade(studentMarks) {
    if (studentMarks >= 80) {
        studentGrade = "A";
    }
    else {
        studentGrade = "B";
    }
}

function PrintGrade() {
    console.log("Student Grade is " + studentGrade);
}

FindGrade(60);
PrintGrade();

There are some inherent problems in the above approach:

  • Variables are defined globally
  • Code maintenance is tough as the functionality grows
  • Code debugging is tough
  • Code testing is tough

The major problem in the above code is that neither the PrintGrade nor the FindGrade functions are reusable. Any future requirements in the find grade logic or in the print logic will require a change in the existing code, and that may introduce new bugs and require testing again. As a developer we may not want this.

Let us go ahead and refactor above code as follows:

Read full post on falafel blog