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 .

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.

clip_image001

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

clip_image002

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

clip_image003

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

clip_image005

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.

clip_image006

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

clip_image007

Worker Role class mainly contains two methods

clip_image009

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

<Imports>

<Import moduleName=”RemoteAccess” />

<Import moduleName=”RemoteForwarder” />

</Imports>

</VirtualMachineRole>

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.

clip_image011

ServiceConfiguratiobn.cscfg

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.

clip_image013

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.

ServiceDefinition.csdef

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.

clip_image015

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

clip_image017

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.

clip_image018

This segment contains the certificate needed for a role.

clip_image019

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.

Conclusion

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,

clip_image001

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.

clip_image003

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

clip_image004

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

clip_image005

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

clip_image007

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

clip_image008

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.

clip_image010

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.

clip_image002clip_image003

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

clip_image004

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.

clip_image006

So to resolve this, Open command prompt in Administrator mode

clip_image007

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

clip_image009

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.

clip_image010

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

clip_image011