Search This Blog

2009-06-17

Create A Step by Step WCF Application

This is a getting started tutorial to Windows Communication Foundation(WCF) Service.The followinh application provide two services
-1.getName:Which will take two input string parameter first name and the last name and returns a string which is a concatination of both two input string
-2.getMessage:Which will take one input string parameter and returns the same string appending another string "Message :" as a prefix

I have used Microsoft Visual Web Developer 2008 Express Edition for creating service and Microsoft Visual C# 2008 Express Edition for creating a windows application to invoke that service.
So it is very Simple.Let's Start

Step 1.Create New WCF Service
Open Microsoft Visual Web Developer 2008 Express Edition to create a New Website
Go to File->New Web Site and you will see a template called WCF Service.Select this template and put "MyWCFService" as a File Name



Step 2.Define ServiceContract and OperationContract
Open the IService.cs under App_Code,Delete all lines of code except the namespace portion and copy the following code after namespace.
[ServiceContract]
public interface IMyService
{
[OperationContract]
string getName(string fName, string lName);
[OperationContract]
string getMessage(string Message);
}

Step 3.Implement the Service
Open Service.cs under App_Code ,similarly delete all lines of code except the namespace.Create a new class MyNameService and implement IMyService.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

public class MyNameService : IMyService
{
#region IMyService Members

public string getName(string fName, string lName)
{
return fName + " " + lName;
}

public string getMessage(string Message)
{
return "Message :" + Message;
}
#endregion
}

Step 4.Create Service Defination File(.SVC)
Open Service.svc change service to "MyNameService".
<%@ ServiceHost Language="C#" Debug="true" Service="MyNameService" CodeBehind="~/App_Code/Service.cs" %>

Step 5.Edit web.config file for service hosting
Go to web.config.Within system.serviceModel you have a services.Under services you will get service tag,
-Change the name to "MyNameService" which is a user defined class under Service.cs that impement IMyService.
-Change the behaviorConfiguration to MyNameServiceBehavior
Go to the end point tag within service tage,
-Change contract to IMyService which is the name of your interface.

Step 6.Enable metadata for client access
Within this web.config file go To serviceBehaviors under behaviors,Go To behavior tag
-Within the behavior tag change the name to MyNameServiceBehavior which you have mention in the behaviorConfiguration at step 5.
-Within serviceDebug tag set includeExceptionDetailInFaults=true

The system.serviceModel will look like as follows(Step 5 and Step 6)

<system.serviceModel>
<services>
<service name="MyNameService" behaviorConfiguration="MyNameServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="IMyService"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyNameServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Step 7.Build and Test the application
Select Service.svc and right click.Click on "Set As Start Page"
Now run your application by clicking F5.You can see the following page when you run it.


Step 8.Generate a configuration file and a code file that contains the client class


Go to command prompt (type cmd in Start menu->run)

To go to the folder which contain SvcUtil.exe,Type
cd C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

run the following command
svcutil.exe http://localhost:1805/MyWCFService/Service.svc?wsdl
You can get the url from the output window(web site) generated at step 7

After executing the command ,you will get following two files within the folder C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin or the folder which contain SvcUtil.exe

-1.MyNameService.cs
-2.output.config

Step 9.Create A client application which will invoke your WCF Service
Create a windows application "MyWCFClient" in different .NET IDE

Step 10.Add Service Reference
Right click on your solution and click on "Add Service Reference"



Put the URL generated at step 7.
Click on GO.
Type "MyServiceReference" in a Namespace textbox.


Now Click OK
Now it will generate/Modify two files
-MyServiceReference under Service References folder
-app.config

Step 11.Copy Configuratin and code file
Copy MyNameService.cs and output.config generated at Step 8. Paste it in the root folder of your windows application(MyWCFClient)

Step 12.Invoke the WCF Service
Call your WCF Service(MyService) in a button click event.Create an object of MyServiceClient and call two methods getName and getMessage that is declared in IMyService at step 2 and implemented in MyNameService at step 3

private void button1_Click(object sender, EventArgs e)
{
MyServiceClient msc = new MyServiceClient();
MessageBox.Show(msc.getName("Manab", "Basu"));
MessageBox.Show(msc.getMessage("Tested"));
}

Step 13.Modify the app.config
Open the app.config and go to the endpoint tage within client under system.serviceModel.
Modify contract="MyServiceReference.IMyService" to contract="IMyService"

The file will look like as follows
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IMyService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:1805/MyWCFService/Service.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMyService"
contract="MyServiceReference.IMyService" name="WSHttpBinding_IMyService">
<identity>
<userPrincipalName value="manuba@wipro.com" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>

Step 14.Run your client application
Run your windows application and clik on the button


So now you can see that the WCF is so simple :)

2009-06-16

Basics Of Windows Workflow Foundation

What is a Workflow?
A set of activities that coordinate people
and / or software.

What are Activities?
An activity is a step or unit that represents runtime logic in a workflow.is the basic building block.An activity can expose properties and events that can be programmed againist within a workflow. An activity can also contain methods that are invoked by the workflow designer or workflowRuntime.
Properties and events that are exposed to the outside world and can be programmed from the workflow.It Supports pre/post interception hooks into execution in user code.
Methods which implement the inner behavior and are called by the workflow runtime.

What are the different categories of Activity?
Activites fall under two broad categories:
- Basic or sometimes called Primitive activities, which are steps in a workflow that execute runtime logic.Basic activities are steps that “do work”
- composite – which manage a set of child activities.In fact, a workflow itself is an activity.One variant of composite activites is a root activity.Workflows are just a special kind of composite activity

What are the different Types Of Workflow?
There are two types of workflow:
1.Sequential
2.State Machine
A state-based workflow waits on external entities to perform some action before moving on to the next step. On the other hand, a sequential workflow is just a continuous flow of operations which might include branching, but steps in the sequential workflow don't wait for an external entity to perform the operation, and then continue.

Which workflow to choose ?

Sequential workflow follows the traditional style of thinking - i.e. as long as the process is simple and stays in the boundary then a sequential workflow will work.
On the other hand, state machine workflows deal with different states of the workflow. A process which involves several different iterations before getting into the final shape is a candidate for being a state machine workflow.

Why Workflows and WF?
One of the biggest reasons for creating a workflow is that you are actually creating a model. Most of the business processes have some sort of model associated with them, whether it is use-cases, UML diagrams or a simple flow chart. In a process you always have some flow and thus, there will always be some steps involved in its execution.
With WF, model and workflow are one and the same. You use pieces of a business process to make a workflow and you piece together the workflow, which makes a model. Before WF you would make couple of UML diagrams, drawing flow-charts, writing pseudo code, explaining in bulleted text how an operation should work and then finally you will get to writing the code, whereas with WF when you are modeling the business process you are also building the application!

What is the Host Process for WF?
A WF has no executable environment and requires a host process within which it can execute. They are not applications themselves, rather, they require an application where they can reside. This host process can be a Windows Application or an ASP.NET Web application.

What is Workflow RunTime Engine?
The WF runtime engine executes workflow made up of activities created with VS2005 Workflow Designer. The runtime engine includes three basic services:
-1.Scheduling (schedules the execution of activities within a workflow)
-2.State Management (allows the state of the workflow to be persisted instead of storing it in some other mechanism like database)
-3.Rules (executes policy activities i.e., add rules on the workflow against certain activities in order to control the flow)

2009-06-15

Advantages of WCF over Webservice

Following are the few key points which describes the advantages of WCF over Webservice
  • WCF has support for multiple protocols (TCP/IP, HTTP, PIPE, MSMQ etc.)
  • WCF can be hosted outside if IIS ie: can be hosted in managed windows applications, a windows service, and WAS (Windows Process Activation Service)
  • WCF provides customisation such as event hooks into service start / end / init / custom global error Handling etc. etc.

2009-06-12

C# 3.0 Tutorial -9:Linq To Entities

Most applications are currently written on top of relational databases. At some point, these applications will have to interact with the data represented in a relational form. Database schemas are not always ideal for building applications, and the conceptual models of applications differ from the logical models of databases. The Entity Data Model (EDM) is a conceptual data model that can be used to model the data of a particular domain so that applications can interact with data as entities or objects.The following diagram shows the relationship between LINQ to Entities(L2E) and the Entity Framework, ADO.NET 2.0, and the data source.



It is basically the replacement of L2S(Linq to SQL).
This guide should be a good starting point for anyone whether or not they are familiar with L2S, and a quick 'jumping guide' to L2S developers. Here's how to get started:

Step 1.Create a Database in your SQL Server
Open the Sql Server ,Right Click On the Database and click on the new Database.

In the "New Database" modal window ,put the name "MyDb" in "Database Name" textbox



Step 2.Create Tables in your Database

Expend your "MyDb" Database ,Right Click on Tables and click on "New Table..."

Create 2 feilds :
a)CustomerID- the datatype is int and it is an identity column and make it is as Primary Key
b)CustomerName-the data type is varchar(50)



Save the table is "Cust_Master"

Create another table Cust_Dtls(Contain CustomerID(int) and CustLocation(varchar(50)) as follows


Make a foreign Key relation between two table with CustomerID


Step 3.Create a new Website in Visual Studio

Open Visual Studio 2008 IDE-Click on File-Click on New Website
In your New Web Site Dialog box select ASP.NET Web Site nad Choose "Visual C#" in your Language Dropdown.
Type "L2EDemo" as your Web Site name and click OK.


Step 4.Create App_Code Folder within your solution

Right Click on your Solution in the solution Explorer choose "App_Code" under the "Add Asp.NET Folder"



Step 5.Make your Ado.NET Entity Data Model
Right Click on your App_Code folder and click on "Add New Item..."
Choose "ADO.NET Entity Data Model" and name it (I left the default Model.edmx for the example)
Click on Add.



Click on Generate From Database



Click Next.
In the Entity Data Model Wizard Click on "New Connection"



Choose Microsoft SQL Server in your "Choose Data Source" Dialog Box



Choose The server Name and select your MyDb Database


Click OK and then Click on "Next"

Choose Cust_Dtls and Cust_Master tables


Then Click on Finish

Now your Model.edmx will be looked like as follows


Step 6.Access Your edmx

Go to your Default.aspx.cs Page
Include the namespace MyDbModel

using MyDbModel;

you will get the namespace from your ModelBrowser when the Model.edmx is opened


Step 7.Code for Save the record using L2E
protected void SaveRecord()
{
MyDbEntities db = new MyDbEntities();
Cust_Master cust = new Cust_Master();
cust.CustomerName = "Manab";
db.AddToCust_Master(cust);
db.SaveChanges();
}

Step 8.Code for modify records using L2E
MyDbEntities db = new MyDbEntities();
db.Cust_Master.First(c => c.CustomerID == 1).CustomerName = "Ranjan";
db.SaveChanges();

Step 9.Code to Display Records

MyDbEntities db = new MyDbEntities();
foreach (Cust_Master c in (from _c in db.Cust_Master select _c))
{
Response.Write("Customer ID : " + c.CustomerID);
Response.Write("<br/>");
Response.Write("Customer Name : " + c.CustomerName);
}

Step 10.Code To Delete Records
MyDbEntities db = new MyDbEntities();
db.DeleteObject(db.Cust_Master.First(c => c.CustomerID == 1));
db.SaveChanges();

Complete Code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MyDbModel;

public partial class _Default : System.Web.UI.Page
{
MyDbEntities db;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SaveRecord()
{
db = new MyDbEntities();
Cust_Master cust = new Cust_Master();
cust.CustomerName = "Manab";
db.AddToCust_Master(cust);
db.SaveChanges();
}
protected void ModifyRecord()
{
db = new MyDbEntities();
db.Cust_Master.First(c => c.CustomerID == 1).CustomerName = "Ranjan";
db.SaveChanges();
}
protected void showRecords()
{
db = new MyDbEntities();
foreach (Cust_Master c in (from _c in db.Cust_Master select _c))
{
Response.Write("Customer ID : " + c.CustomerID);
Response.Write("<br/>");
Response.Write("Customer Name : " + c.CustomerName);
}
}
protected void deleteRecord()
{
db = new MyDbEntities();
db.DeleteObject(db.Cust_Master.First(c => c.CustomerID == 1));
db.SaveChanges();
}
}

Now that should get you started. Like I said, if you are familiar with L2S, this transition should be no problem, and if you are new to this whole Linq arena, this should be simple to pick up. This new ADO is getting more and more impressive the more MS works on it. I can't even imagine going back to the old methods...

Related Resource:

C# 3.0 Tutorial -1:Var Keyword
C# 3.0 Tutorial -2:Extension Methods
C# 3.0 Tutorial -3:Lambda ExpressionsC# 3.0 Tutorial -4:Object Initializers
C# 3.0 Tutorial -5:Anonymous Types
C# 3.0 Tutorial -6:Type Equivalence
C# 3.0 Tutorial -7:Projections
C# 3.0 Tutorial -8:Linq

tags:Linq to Entities tutorials ,step by step Linq to Entities(L2E)