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.

 

clip_image002

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.

clip_image004

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

IService1.cs


using System.ServiceModel;
namespace WcfService10
{
 [ServiceContract]
 public interface IService1
 {
 [OperationContract]
 string GetDataUsingnetTcpBinding(int value);

 }
}

Implement service as below,

Service1.svc.cs

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,

clip_image006

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.

clip_image008

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

Program.cs


using System;
using System.ServiceModel;

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

}
 }
}

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.

App.Config


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

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.

 

clip_image010

2. Attaching the service behavior with service

 

clip_image012

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

clip_image014

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

 

clip_image015

Run the console application

clip_image017

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.

clip_image018

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

Program.cs


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

}

 }
}

On running we will get the output as below ,

clip_image020

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,

clip_image001

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

 

clip_image003

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

We may call above function as below,

clip_image004

Full source code is as below,

Program.cs



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());
            Console.ReadKey(true);

        }

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

        }
    }
}


 

Output

clip_image006

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.

clip_image002

Through Properties tab

Click on Web Role

clip_image003

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

clip_image005

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

clip_image007

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 ,

clip_image001

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.

clip_image003

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.

clip_image005

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

clip_image001

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

clip_image002

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.

clip_image003

Microsoft Sql Server, Error : 10061

I tried to connect SQLTEST instance of SQL Server and got below error

clip_image001

This is very common error and can be caused due to many reasons. The way I solved it

1. Go to Start

2. Type Run

3. Type Services.msc

4. Then locate for SQL Server instance you are trying to connect. In my case this is SQL TEST. Right click and select Properties

clip_image003

5. In Properties Dialog box go to Log On tab

clip_image004

Now if you have recently changed the login pass word of the system. Make sure for that particular account you have changed password here also. Better option would be make Log on as Local System account

6. Navigate to General tab and change the Startup type to Automatic and Start the service

clip_image005

7. Now try to connect SQL Server for that particular instance. You should successfully able to connect.

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.

clip_image001

From Pop up select Set Scripting option.

clip_image003

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.

clip_image004

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

clip_image005

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

https://sql.azure.com/

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

clip_image007

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.

clip_image009

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

clip_image011

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

clip_image012

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.

clip_image014

Run the Script in SQL Azure

Open SQL Server management studio

clip_image015

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

clip_image016

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

clip_image017

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

clip_image018

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

clip_image020

You will get the server name in form of

abc.database.windows.net

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

clip_image021

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

clip_image022

From Option select School database.

clip_image023

Run the Script

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

clip_image025

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

clip_image026

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.

clip_image028

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.

clip_image030

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

clip_image031

4. Choose a new connection.

clip_image032

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

So provide the information as below,

clip_image033

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.

clip_image034

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.

clip_image035

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.

clip_image037

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

clip_image039

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

clip_image041

clip_image042

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

clip_image044

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.

clip_image046

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

clip_image048

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

clip_image049

clip_image050

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 .