Cross machine communication between .Net Application using WCF

When service and client both are of .Net and resides on different machines then we choose preconfigured netTcpBinding to publsih WCF Service to the client.



netTcpBinding is best suited when both client and service are of .Net and communicating to each other either over Intranet or Internet.

Since both the service and client are in .Net, so performance of this binding is very much optimized for best. There is no overload of interoperability.

netTcpBinding uses TCP Protocol and Binary Encoding . Few deafult properties of netTcpBinding is listed in below digram.


Now let us create a WCF service using netTcpBinding . what we are going to do

1. Create a WCF Service

2. Host Service in Console Application

3. Configure EndPoint with netTcpBinding

4. Consume service at console client.

Create WCF Service

Open Visual Studio 2010 and create a new project by selecting WCF Service Aplication project template in WCF tab. If you are using Visual Studio 2008 then select WCF Service Application from Web Tab.

Now let us create a very simple Service Contract


using System.ServiceModel;
namespace WcfService10
 public interface IService1
 string GetDataUsingnetTcpBinding(int value);


Implement service as below,


namespace WcfService10

 public class Service1 : IService1
 public string GetDataUsingnetTcpBinding(int value)
 return string.Format("You are fetching: {0} using netTcpbinding", value);

Host Service in Console Application

To host WCF Service we are going to create console application. Just create a console application. Add below references in console application project,


Add the project reference of WCF Service application project we created in previous step. Right click on console application project and select Add Reference then click on Project tab and browse to WCF Service application project we created in previous step.


After adding all required references and of WCF Service project, we are going to write a code to host the application.


using System;
using System.ServiceModel;

namespace HostApplication
 class Program
 static void Main(string[] args)
 ServiceHost host = new ServiceHost(typeof(WcfService10.Service1));
 Console.WriteLine("Press a key to close the host");


In above code, we are creating instance of ServiceHost, opening the host and closing that.

Configure EndPoint with netTcpBinding

Now we need to configure EndPoint with netTcpBinding. Right click and add new item then choose Application Configuration file from General tab.


<?xml version="1.0" encoding="utf-8" ?>
 <service name="WcfService10.Service1" behaviorConfiguration ="netTcpServiceBehavior">
 <endpoint address =""
 binding ="netTcpBinding"
 contract ="WcfService10.IService1" />
 <endpoint address="mex"
 <baseAddresses >
 <add baseAddress ="net.tcp://localhost/SampleNetTCPService"/>
 <behavior name="netTcpServiceBehavior">
 <serviceMetadata httpGetEnabled="false" httpGetUrl=""/>
 <serviceDebug includeExceptionDetailInFaults="false"/>
 </serviceBehaviors >
 </behaviors >

In above configuration file

1. We are creating service behavior. In service behavior service, we are configuring metadata will not get enabled through over Http.



2. Attaching the service behavior with service



3. Creating base address. Client will able to consume the service on address net.tcp://localhost/sampleNetTCPService


4. Creating the EndPoints. First EndPoint is for service contract IService1 and other endpoint is for metadata.



Run the console application


Now service is up and running.

Consume service at console client

Since our service is up and running this is time to consume the service. Create a console application project right click and add service reference. In address you need to provide the same address we configured in App.Config file of host console application project.


Note: You need to make sure host console application project is running else you will get error while adding service reference.

After successfully adding the service reference we can call the service in normal way


using System;
namespace ConsoleApplication10
 class Program
 static void Main(string[] args)
 ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();
 string result = proxy.GetDataUsingnetTcpBinding(99999);



On running we will get the output as below ,


In this article we saw how we could use netTcpBinding for communication between two .Net Application residing on different machines.

Programmatically finding Binding Elements in WCF Binding

Binding is one of the important aspect of WCF Programming. It deals with, “How Service and client will talk to each other?” Binding is made up of different binding elements. When different binding elements are stacked together they form a Binding. Different binding types are made up of different binding elements.

Always a question arises that, “What are the different binding elements of a particular binding? “

And we can find solution of above question through code. What all we need to do

1. Create instance of Binding

2. Enumerate through Binding elements.

We are going to create console application to enumerate through all the binding elements in a binding.

Add below references in console application project,


We are going to write a function. This function will take object of a Binding as input parameter and prints all the binding elements.



Above function is very simple, just enumerating above all the binding elements.

We may call above function as below,


Full source code is as below,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels; 

namespace ConsoleApplication10
    class Program
        static void Main(string[] args)

            EnumerateBindingElements(new BasicHttpBinding());
            EnumerateBindingElements(new NetMsmqBinding());
            EnumerateBindingElements(new WSHttpBinding());


        static void EnumerateBindingElements(Binding binding)
            Console.WriteLine("Binding : " + binding.GetType().Name);
            BindingElementCollection bindingElements = binding.CreateBindingElements();
            foreach (BindingElement e in bindingElements)





Windows Azure For Developers Task 5: Configuring Virtual Machine sizes

What is specifying Virtual Machine Size?

We can specify the size of virtual machine on which Role will be deployed. Size of VM defines

1. CPU core

2. Memory capacity

3. Local file system

We can specify Virtual Machine size for the Role.

There are two way to specify the VM size

1. Through Service Definition file

2. If using Visual Studio then through property tab on the Role.

Through Service definition file

Open ServiceDefinition.csdef file and you can choose the size from provided dropdown.


Through Properties tab

Click on Web Role


And you can provide VM size by selecting Configuration tab and choosing VM size from the drop down.


There are 5 options available to choose from for the size of VM. Below table gives detail of all options available with different VM size


Windows Azure for developers Task4: Error Attaching the debugger in Windows Azure SDK 1.3

I installed Windows Azure SDL V 1.3 . I tried to create a Hello World Azure Application.

I pressed F5 and error I got as below ,


I tried Ctrl+F5 ; running without debugger and did not get above exception but got service unavailable error in the browser

On this particular exception a very good discussion I found here

Option 1

First suggestion was to check whether, there are two folders in C:\Windows\Microsoft.NET\Framework64 for V4.0 and rename one of the folders. I checked and I found I had only one folder for v4.0.30319 so this suggestion did not work for me.

Option 2

Second suggestion was the open the command prompt and run aspnet_regiis.exe –r. I tried and again I was not lucky.


Option 3

Third suggestion was to change the target framework from V4.0 to v3.5. I did that and was unlucky once again.

Option 4

Fourth suggestion was to change delete the Sites element from the ServiceDefinition.csdef file. I was unlucky once again.


Option 5

Fifth option was to test whether, a normal web Application with target framework 4.0 is getting published successfully in IIS or not? I tried that and I was able to publish. So my IIS was working fine.

I got frustrated and restarted and system and found everything working, I did not get that debugger exception. I have no idea what happened but this was my experience with this popular exception.

Editing applicationhost.config on 64 bit Windows 7 system

I had a very simple task to edit applicationhost.config file and it took my 2 hrs to get the solution.

I navigated to folder C:\Windows\System32\inetsrv\config and I found applicationHost.config file. And when I clicked on file to open in Visual Studio, I got the below error


Then I tried

1. Open visual studio in administrator mode

2. Clicked on open file

3. Navigated to folder C:\Windows\System32\inetsrv\config and found applicationHost.config was not available for selection.

This is because applicationHost.config is 64 bit file. And still VS dll is 32 bits.

So now question comes how to edit this file.

1. Open Notepad in elevated mode


2. Browse to C:\Windows\System32\inetsrv\config . Change file type to all and you would able to see applicationhost for selection. Select and open the file.


WCF Data Service with SQL Azure

In this article we will expose database from cloud or SQL Azure as WCF Data Service.

There two steps mainly involved in this

1. Creating local Database and migrating to SQL Azure

2. Exposing SQL Azure Database as WCF DATA Service

Step1: Creating local Database and migrating to SQL Azure

Creating Database

The first step is to create database. We are going to use School database. Script of sample School Database copy from here

Generate Database Script for SQL Azure

Right click on School Database and select Tasks. From Tasks select Generate Script.


From Pop up select Set Scripting option.


Give the file name by selecting Save to file option.

Now the main thing to be noticed here is we need to so some change in advanced setting. For that click on Advanced options.


And in types of data to script select Script and Data both option.


After that click next and Finish. You can see a SQL file is created and we will be using this script to migrate our in house school database to SQL Azure.

Create School Database in SQL Azure

Login SQL Azure portal with your live credential

Click on SQL Azure tab. You will get the project , you have created for yourself.


Click on the project. In my case project name is debugmode. After clicking on project, you will get listed the entire database created in your SQL Azure account.


Here in my account there are two database already created. They are master and student database. Master database is default database created by SQL Azure for you.

Click on Create Database


Give the name of your database. Select the edition as Web and specify the max size of database.


You can select other option also for the edition as business

After that click on Create you can see on Databases tab that Demo1 database has been created.


Run the Script in SQL Azure

Open SQL Server management studio


You will get Connect to server dialog box. Click cancel on that.


After cancelling the dialog box click on New Query from left top


On clicking New Query, you will get the connect to server dialog box again.


Now here you need to provide, Server name of SQL Azure and Login credential of SQL Azure.

To know what is database server name of SQL Azure portal, login to Windows Azure portal with your live credential and then click on SQL Azure tab


You will get the server name in form of

Where abc is name of your SQL Azure server. We need to provide this server name at local sql server management studio.


Make sure to select SQL Server Authentication and provide login user name and password of your SQL Azure database portal.

After that before clicking Connect click on Option


From Option select School database.


Run the Script

Now once you successfully got connected to School Database in SQL Azure. Copy the script and Run like below.


After successfully running of script, run the below command and all the tables name will get listed.


In this way you successfully migrated database to SQL AZURE.

Step2: Exposing SQL Azure Database as WCF DATA Service

Create a Web Application

Create a new project and select ASP.Net Web Application project template from Web tab. Give a meaning full name to the web application.


Create a Data Model

We can create a Data Model, which can be exposed as WCF Data Service in three ways

1. Using ADO.Net Entity model.

2. Using LINQ to SQL class.

3. Custom Data Model.

For our purpose, I am going to use ADO.Net Entity model to create the data model. So to create an entity model

1. Right click on web application and add a new item

2. Select ADO.Net Entity model from Data tab.


3. Since we have table in SQL Azure Dat aBase. So we are going to choose option, select from database.


4. Choose a new connection.


After clicking on New Connection, this is the more important step. We need to give extra care here.

So provide the information as below,


Click on Test Connection to test connection established successfully or not? After that you will get prompted as Connection string contains sensitive data, do you want to keep that in configuration file or mange through program. You can select as of your choice and need.


On providing your option click on Next button, you can see all the tables, Views, Stored Procedures’ are available to chosen as part of data model for WCF Data Service.


5. Select tables, views and stored procedure from data base you want to make as the part of your data model.

Creating WCF Data Service

1. Right click on Web Application project and add a new item.

2. Select WCF Data Service from Web tab. Give any meaningful name. I am leaving the default name here.


3. After adding the WCF Data Service, we can see a service file with extension .svc has been added to the solution explorer.

Very first we need to put data source name. To do so uncomment the first commented line and put the data source name. In our case name of the model, which we created in 2nd step is the data source. Our data model name is SchoolEntities


Now we need to set access rules for entity or entity set. Since we have only one table, so either we can give name of the table explicitly or if we want to set the same access rule for all the table in the data model or data source we could put *.



So we are setting the access rule that, on the entity in data source perform all the operations.

So finally svc file will look like


Run the WCF Data Service

Just press F5 to run the WCF Data Service. Data Service will be hosted in the default ASP.Net server.

On running you can see, all the table is listed there.


Append the URL with People and you will get all the records from People table


Note: If your browser is not showing the expected result, make sure Feed reading of browser is off. To do from menu of IE and select tool and then Internet Option then Content



So we have exposed data from cloud using WCF Data service. Now any OADTA client can consume the data from cloud by consuming WCF Data Service.

Thanks for reading , I hope this article was useful .

Windows Azure for Developers Task 3: Understanding Windows Azure Application

An application designed and developed to be as hosted service for windows azure consist of

1. Managed Code

2. XML file for configuration

Managed codes are mapped into different Roles

XML files are mapped into different configuration settings.

If we see the below diagram it explains all the components mainly involved in Windows Azure application.


Note: This image taken from Windows Azure SDK

We will examine each component of above diagram one by one.

The first thing is Roles

There are there types of Roles

1. Web Role

2. Worker Role

3. VM Role

Web Role

1. This is role customized for IIS.

2. If we choose this type of Role automatically IIS setup is configured for this.

3. This role mainly takes input.

4. This role is configured for HTTP request.

5. This contains web sites or other codes that is supported by IIS.

6. This mainly contains ASPX pages or it may contain WCF Services also. Any application supported by IIS can be used as Web Role.

7. Any application can be used as Web Role if it supports HTTP protocol.

8. When we use WCF Service for Web Role in Windows Azure we need to make sure that binding used in WCF service is basicHttpBinding. We cannot use another binding with WCF Service as Web Role.

Advancement in Web Role in Windows Azure SDK 1.3

1. It got full capability of IIS.

2. Web Applications and sites run fully under IIS.

3. Web Roles uses the application domain in the same way as of IIS.

Biggest advantage is that now we could have multiple sites or application is a single Web Role.

While creating Azure project we can select the type of Web Role we want for the application. Installed templates are

1. ASP.Net Web Role

2. ASP.Net MVC Web Role

3. WCF Service Web Role

4. CGI Web Role


On creation of Windows Azure project, you can see there are two types of configuration files created for you.


In ServiceConfiguration.cscfg file, we can give the number of Web Role instance


Worker Role

It is mainly useful for background work. The main point to be noticed here is that Worker Role does not support IIS. So it is very much capable to process any type of application including unmanaged code. Worker role does not directly interact with the user so it is very useful when it come for asynchronous long processing task.

Mainly Worker Roles are useful

1. Useful in the task where user has not to wait for.

2. Useful for asynchronous tasks.

3. Useful to run non HTTP service like TCP services.

4. To host the application does not require user input.


Difference between Worker Role and Web Role

Let us understand some differences between Web Role and Worker Role

1. Web Role is web application which gets HTTP Input from the user and it is supported by IIS. Worker Role has not supported IIS. This is the main difference between Web Role and Worker Role.

2. Web Role faces the user interface whereas Worker Role gets input from Web Role and mainly performs the batch operations asynchronously.

3. In Web Role Threading is managed by IIS whereas in Worker Role Threading is managed by developer or ourselves.

4. In Worker role we must need to provide Run method to start the process.

5. The security parameter is not same in between Web Role and Worker Role.

6. ACL [Access Control List] for certificates is supported by default for IIS and network services by default whereas in Worker Role developer has to manage it.

In csdef file Worker Role is defined like below , name of the worker role is WokerRole1 in the below configuration


Worker Role class mainly contains two methods


VM Role

Third type of role is VM Role. This is very special types of role and it mainly deals with operating system up gradation in virtual machines.

Web Role and Worker Role run on a virtual machine whereas VM Role is a virtual machine which gives full control of the operations on virtual machines.

Using VM Role we control the operating system and any up gradation in virtual machine operating system is instance of VM Role. This role is suited for migrating application to run as hosted service in Windows Azure.

A VM Role can be defined as below

<VirtualMachineRole name=”MachineRole” vmsize=”Medium”>


<Import moduleName=”RemoteAccess” />

<Import moduleName=”RemoteForwarder” />



Configuration files

Now since we have understood the three different types of Roles. Let us have a look on two types of configuration files involved in Windows Azure Application.



Configuration file can be updated without stopping the azure service. This file mainly contains information about

1. Number of Role instances

2. Value for the different types of setting.


1. Instance count says number of instance of the Web Role or Worker Role will be running.

2. In above configuration file we can see that application is using local development.


This file contains below information

1. Various ROLES used by the service

2. Information about Certificates used in the service.

3. Input and Internal End Points for the service

4. Local disk storage needed by the service

5. Configuration setting that would be used by different Roles .

This configuration file defines the Web Role or Worker Role. Let us understand each segment of this file one by one.


This segment contains the definitions for site and web applications. These sites and web applications are hosted in IIS 7.


There are two types of End Points in this configuration file, Input End Point and Internal End Point.

Input End Point contains the definition of endpoint that is used to contact hosted service.

Internal End Point contains the definition that is used by roles to communicate with each other.


This segment contains the certificate needed for a role.


This segment contains definition of imported rules.

Storage Service

The last segment of Azure Application is Azure Storage service. There are three types of azure services

1. For unstructured Data (BLOBS)

2. For structured Data ( TABLES)

3. For messages between application and services (QUEUES)

BLOBS are mainly for used for large storage of Data. There are two types of BLOG storage, Block BLOG and PAGE BLOB. Azure Tables are used to store structured data. CRUD operations can be performed using ODATA protocol or using the same syntax used for WCF Data Service. Each row in the Azure table uniquely identified by Row key and Partition Key.

SQL Azure

For storage purpose we can use SQL Azure also.


In this article we saw an introduction of Windows Azure application. This article was more of theoretical. In next article of this series we will explore Windows Azure application in a walkthrough way . Thanks for reading.

Windows Azure for Developers task 2: Adding Cloud Service project to existing ASP.Net Web Application

Adding Cloud Service project to existing ASP.Net Web Application

Imagine we are moving existing Web Application or ASP.Net MVC Web Application to cloud. In that case we need to add cloud service to existing Web Application or ASP.Net MVC Web Application.

We have a solution for Web Application is as below,


Now right click on the solution and add a new project in the same solution. Choose Windows Azure project from the installed template and then choose a ASP.Net Web Role.


In role selecting window do not select any role and click on Ok. See the image below,


Now you can see in solution explorer, Windows Azure project is being added.


After creating Windows Azure project we need to associate ASP.Net Web Application project to Window Azure. So to do so, Right click on Roles in Windows Azure Project and select add and then choose Web Role Project in solution option


Then you will get the project in the solution. Press ok


On clicking of Ok, Visual studio will update csdef and cscfg file for the Web Role.

Now add the references of required windows azure. For that click on web Application project and add references. Then add the below references.


In this way you have added cloud service project to existing Web application.

Windows Azure for Developers Task 1: Resolving Failed to initialize Windows Azure storage emulator Error

I thought to start learning Windows Azure. I installed Azure SDK and created a project by choosing Windows Azure project template from cloud tab and creating a Web Role.


I just put a label on aspx file and when tried running the project I got the below error


When I switched to Output Window, I got the Error message

Windows Azure Tools: Failed to initialize Windows Azure storage emulator. Unable to start Development Storage. Failed to start Development Storage: the SQL Server instance ‘localhost\SQLExpress’ could not be found. Please configure the SQL Server instance for Development Storage using the ‘DSInit’ utility in the Windows Azure SDK.


So to resolve this, Open command prompt in Administrator mode


Change Directory to C:\ProgramFiles\WindowsAzureSDK\v1.3\Bin\DevStore


Now type the command

C:\Program Files\Windows azure SDK\v1.3\bin\devstore DSINIT /SQLINSTANCE:SQLTest /Forcecreate

Only couple of point to notice in executing above command is

SQLTEST: It is name of the SQL Server instance. Make sure you are giving name of SQL Server instance name here rather than your PC name.

If you are not providing valid SQL Server instance name then you may get below exception.


On successfully execution of command , you will get below Dialog box for the success message.


Fetching Image from SharePoint 2007 picture library using object model

I thought this is an easy requirement to fetch Image form SharePoint 2007 picture library and bind to a System.Drwaing.Image object. But when I started doing that, I had to give my 3 to 4hrs. So here is the code snippet to fetch images from SharePoint 2007 Picture library.

Namespace Required


Function to return Image as MemoryStream

This function will return Image from Picture Library of SharePoint 2007 using WSS Object model. This function is taking siteUrl and filename to be fetched from the picture library. This function is returning MemoryStream

public static MemoryStream GetImageforCharts(string siteUrl, string fileName)
            Byte[] fileContentsArray=null; 
            MemoryStream imageStream = null; 

                using (SPSite site = new SPSite(siteUrl))
                // using (SPSite site = SPContext.Current.Site)
                    using (SPWeb web = site.OpenWeb())

                     SPPictureLibrary chartPictureLibrary = 
                        SPQuery query = new SPQuery();
                query.Query = @"<Where><Eq>
                                 <FieldRef Name ='Title'/>
                               <Value Type='Text'>" + fileName + "</Value></Eq></Where>";
                    SPListItemCollection lstImages = chartPictureLibrary.GetItems(query);
                        foreach (SPListItem r in lstImages)
                            SPFile file = r.File;
                            using (Stream fileContents = file.OpenBinaryStream())
                                long  length = fileContents.Length ;
                                fileContentsArray = new Byte[length]; 
                          fileContents.Read(fileContentsArray, 0,Convert.ToInt32(length));




                imageStream = new MemoryStream(fileContentsArray);
                return imageStream; 

            catch (Exception ex)
                return null; 

Using the Function

Now we can call the function as below, and save the Image in System.Drawing.Image object.