Monday, February 8, 2010

Windows Workflow Foundation Custom Activity - Part 1


Introduction

Windows Workflow foundation gives many activities to use in workflow like code, delay, IfElse, Listen, Parallel etc. But in some scenario, those activities will not work as per our requirement. So we need to implement custom activity which will work as per our requirement.

To create a custom activity, we need to implement one class which is derived from “Activity” base class because every workflow activity is directly/indirectly derived from “Activity” class.

Example

Let’s take one example. We have to create one workflow for Employee management. For this workflow, we need one activity which has some properties like FirstName, LastName, Age etc… (For employee entity) and have one function which will insert employee data into database.

For the above scenario, we need to create our own activity which takes care of above functionality.

Here below I created one class “EmployeeActivity” which is derived from the “Activity” class.

public class EmployeeActivity : Activity

{

}

Now we need to add properties for Employee entities. Here I took only 3 properties for demo purpose.

public class EmployeeActivity : Activity

{

private string firstName;

public string FirstName

{

get { return firstName; }

set { firstName = value; }

}

private string lastName;

public string LastName

{

get { return lastName; }

set { lastName = value; }

}

private int age;

public int Age

{

get { return age; }

set { age = value; }

}

}

In above code, I have created three private variables and public properties for FirstName, LastName and Age. You can add any number of variables and properties which you need.

Now we need to override “Execute” method of “Activity” class. This method will take care of inserting employee data into database.

Let’s implement “Execute” method:

protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)

{

/// Code to insert employee data into database

return base.Execute(executionContext);

}

Now you can put your custom activity on workflow and set the property. Whenever this activity will execute, it will insert employee data into database.

Now think that user wants to do some pre authorization before data will store into database. Means you have to implement one event which will execute before employee information will store in employee database.

Let’s create one event and integrate it with EmployeeActvity:

public delegate void PreAuthorizationEventHandler(object sender, CustomActivityEventArgs e);

public event PreAuthorizationEventHandler PreAuthorizationEvent;

Here we created one delegate and one event. We create one class “CustomActivityEventArgs” which is derived from “EventArgs” base class.

[Serializable]

public class CustomActivityEventArgs : EventArgs

{

private string firstName;

public string FirstName

{

get { return firstName; }

set { firstName = value; }

}

private string lastName;

public string LastName

{

get { return lastName; }

set { lastName = value; }

}

private int age;

public int Age

{

get { return age; }

set { age = value; }

}

}

Now we need to change “Execute” method code to execute event. Updated code is look as below:

protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)

{

CustomActivityEventArgs customActivityEventArgs = new CustomActivityEventArgs();

customActivityEventArgs.FirstName = FirstName;

customActivityEventArgs.Age = Age;

customActivityEventArgs.LastName = lastName;

//Here we are executing event

if (PreAuthorizationEvent != null)

PreAuthorizationEvent(this, customActivityEventArgs);

/// Code to insert employee data into database

return base.Execute(executionContext);

}

When you will use this EmployeeActivity in you workflow, you will get one event “PreAuthorization” which will execute before employee data inserting in the database.


Friday, February 5, 2010

Basic of Entity Framework


Introduction

Microsoft has evolved new technology “Entity Framework” to work with Database. Before this, Microsoft has introduced LINQ to work with the objects which derived from the IEnumerable.

Entity framework is easy to use for developer to generate entity classes for tables/views. Entity framework also generates methods to execute stored procedure which you have created into database.

Entity Framework needs Visual Studio 2008 Service Pack2 installed on the machine.

Developer can easily drag and drop the entity object from server explorer to Entity Framework UI. You can easily generate Entity Framework classes from the existing database. Reverse engineering is not possible in Visual Studio 2008. We can expect this functionality from Visual Studio 2010.

Let’s start with Entity Framework

I have used following database structure to understand Entity framework in .Net application.

Table NameContact
Field NameData TypeConstraint
ContactIDIntPK, Auto Increment
FirstNameVarchar(100)Not Null
LastNameVarchar(100)Not Null
TitleVarchar(50)Not Null
AddDateDateTimeNot Null, Default Value = GetDate()
ModifiedDateDateTimeNot Null, Default Value = GetDate()
Table NameAddress
Field NameData TypeConstraint
AddressIDIntPK, Auto Increment
Street1Varchar(50)
Street2Varchar(50)
CityVarchar(50)
StateProvinceVarchar(50)
CountryRegionVarchar(50)
PostalCodeVarchar(50)
AddressTypeVarchar(50)
ModifiedDateDateTime
ContactIDIntFK


Here we took example of Contact and Address table. One contact person has many addresses like permanent address, office address, Farm-house address etc… So we took “ContactID” field as a foreign key in Address table.

Now let’s create Entity Framework project in .Net IDE.

First open Visual Studio 2008 and select File -> New -> Project option. It will open “New Project” dialog box. Select Project Type “Visual C#” -> “Windows”. Select “Windows Form Application” from Template options. Provide project name, project location and solution name as you want.

Note: You can also take console application or another type of project. But for demo purpose I have chosen windows form application.

After successfully loading project, Right click on project in solution explorer and add new item. In New Item Dialog box select “ADO.Net Entity Data Model” and give name ContactDataModel.edmx. Click on Add button. It will start Entity Framework wizard.
  • In entity framework wizard home page you will get two options “Generate from database” and “Entity model”. You can generate Entity Model using existing database or can use blank entity model to generate your classes manually. [Reverse engineering is not possible in Visual Studio 2008]. Select “Generate from Database” option and click next button
  • In next screen, it allows to create new connection or use existing connection which created before. You can create new connection using “New connection” option. After selecting the proper data connection, Connection string text box will display the connection string used to communicate with the database. You can save the connection string in App.config file. To save connection string in App.Config file just give proper name to “Save entity connection settings in App.config As” textbox. Give “TestEntityEntities” name as connection string name. Click on Next button.
  • In Next screen, you have option to choose which object you want to include in entity framework. You can select Tables, Views and Stored Procedures. Select Address and Contact Table. Click on Finish Button.
  • Entity Framework Wizard will create Entity Framework Model file in your project and option UI in Visual studio. You can see Contact and Address entities.


Entity Framework also generates classes in code behind file for Contact and Address entities. It will generate three classes:
  • Address: This class contains private variables and public properties for each field.
  • Contact: This class contains private variables and public properties for each field.
  • TestEntityEntities: This class is derived from ObjectContext class and has property for Address and Contact entities. This class has method to add new objects in Contact and Address classes.

Now let’s use it in our windows application:

Create new windows form in our windows form application and drag DataGridView control on windows form. Write following code to display all contact information in data grid view.


TestEntityEntities entities = new TestEntityEntities();
var query = from c in entities.Contact select c;
dataGridView1.DataSource = query;

In above code, we created object of the TestEntityEntities class which is generated by Entity Framework wizard in code-behind file. Just use LINQ syntax to get all the contact information from the TestEntityEntities object and display all the contact information in DataGridView object.

Add new record using Entity Framework:

Let go with the Contact Entity. The below code is useful to add new record in contact entity.


TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = new Contact();
contact.FirstName = "test1";
contact.LastName = "test2";
contact.Title = "Mr.";
testEntityEntities.AddToContact(contact);
testEntityEntities.SaveChanges();

First of all we create object of Entities class which is created by Entity Framework. Then after we create object of Contact and assign value to the required properties. After successfully assign value to contact entity, we will call “AddToContact” method of TestEntityEntities class. This method will store the data in Contact table but still the data is not committed. So commit the added data, we need to call “SaveChanges” method of TestEntityEntities class.

Edit existing record using Entity Framework:

To edit any existing record, we need to fetch that record and update it in memory and call SaveChanges method to save the changes. Below code is used to edit existing record.


TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = testEntityEntities.Contact.First(c => c.FirstName == "test1");
contact.FirstName = "test1_Changed";
testEntityEntities.SaveChanges();


First we create object of TestEntityEntities class. Then after we get contact entity record using TestEntityEntities class method. After getting the record, we just need to update the property values and call SaveChanges function.

Deleting existing record:

To delete the record, we need to load the record and delete it using Entity Framework. Below code is used to delete the record.


TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = testEntityEntities.Contact.First(c => c.FirstName == "test1");
testEntityEntities.DeleteObject(contact);
testEntityEntities.SaveChanges();

We just load the record and then call DeleteObject method. This method will not commit your changes to database. To commit the changes, we need to call SaveChanges method.

For more information on how to map stored procedure with Entity, click here.

Thursday, February 4, 2010

Data Warehousing Basic


What is Data Warehousing?

Data warehouse is mainly used to store bulk data and generate analysis report. These analysis reports are very important for taking business decision.

Following are constraint to develop analysis report from the relational database:
• Performance is very poor
• Difficult to develop
• Put very heavy load on database

If you will go with data warehousing then you can easily use SQL server analysis service to generate analysis report.

Generally Data ware housing use two type of database structure:

• Star schema
• Snow flake schema

Key Terms:

Dimension: Dimensions are the entity using it you want to analysis the data. For an example, Product is an entity; it is dimension which is used to analysis the sales report product wise.

Fact: Fact is the entity on which you are analysis the data. For an example sales data is a fact. Fact data must be numeric data so you can analysis the report. For an example, you can calculate minimum/maximum/average of the data. You can use many function on that numeric data.

Dimension tables are joined with fact table directly or in-directly.

Star Schema
If all the dimension tables are joined directly to fact table then that schema is called star schema. Here I took an example of Sales management system.




Snow Flake Schema
If any dimension table is not directly joined with fact table but it is joined through the other dimension tables then that schema is called snow flake schema.



In above diagram, you can see “DimState” and “DimCountry” are dimension tables and connected to Fact table “FactSales” through the DimCity dimension table.

Send HTTP Web Request using C# Application


In some application, we need to send HTTP web request to web application server. While sending http request to server our .Net code block the execution till the response come back to us. But in some scenario we need not wait for response on the same time because we need that output later on.


For the above problem, we can send asynchronous HTTP web request to web application server. When we send web request asynchronous then our application resume the execution and when we need the output of that web request then we can get is using IAsyncResult object.

Here I explained come sample to send asynchronous HTTP web request to web application.

Before starting it, we need to understand the web request types. Actually, any browser send HTTP request using two methods:

  • GET
  • POST
In GET method, Browser sends form data into query string, so user can easily view the data in address bar and also change the data.

In POST method, Browser sends form data with URL as an attachment. User can’t see the POST data in address bar so it is not possible to change the data from address bar.

First we go through asynchronous HTTP web request method using “GET”. Please check the code below:

///
/// Gets the response.
///

/// <param name="StrURL">The URL.
/// HTML source
public string GetResponse(string StrURL)
{
string strReturn = "";
HttpWebRequest objRequest = null;
IAsyncResult ar = null;
HttpWebResponse objResponse = null;
StreamReader objs = null;
try
{

objRequest = (HttpWebRequest)WebRequest.Create(StrURL);
ar = objRequest.BeginGetResponse(new AsyncCallback(GetScrapingResponse), objRequest);

//// Wait for request to complete
ar.AsyncWaitHandle.WaitOne(1000 * 60, true);
if (objRequest.HaveResponse == false)
{
throw new Exception("No Response!!!");
}

objResponse = (HttpWebResponse)objRequest.EndGetResponse(ar);
objs = new StreamReader(objResponse.GetResponseStream());
strReturn = objs.ReadToEnd();
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (objResponse != null)
objResponse.Close();
objRequest = null;
ar = null;
objResponse = null;
objs = null;
}
return strReturn;
}

///
/// Gets the scraping response.
///

/// <param name="result">The result.
protected void GetScrapingResponse(IAsyncResult result)
{

}


Let’s understand the above code:

We have created the method “GetResponse” which take URL as a parameter. You have to pass query string data with URL in this method.

For example: you can call this method like

GetResponse(“http://www.codeproject.com/?cat=4”);


In this method, I created object for HttpWebRequest, HttpWebResponse, StreamReader and IAsyncResult.
  • HttpWebRequest: This object is used to send http web request to web application server. You can use BeginGetResponse and EndGetResponse method of HttpWebRequest object to get response asynchronously.
  • HttpWebResponse: This object is used to get response from web application server.
  • StreamReader: This object is used to get response stream.
  • IAsyncResult: This object is used to send and retrieve asynchronous http web request.


We created HttpWebRequest object using WebRequest.Create method. After creating object, I called BeginGetResponse method to send the http request to web application server. After calling this method, our application execution resume because we used asynchronous method for Http Web Request.

When you need web response then you can use the HttpWebRequest object and call EndGetResponse method. After getting response successfully, we converted it in stream and later on in string variable.

If web applications use “POST” method to send the request data then you have to change the method little bit.

///
/// Gets the response with post.
///

/// <param name="StrURL">The URL.
/// <param name="strPostData">The post data.
/// HTML Result
protected string GetResponseWithPost(string StrURL, string strPostData)
{
string strReturn = "";
HttpWebRequest objRequest = null;
ASCIIEncoding objEncoding = new ASCIIEncoding();
Stream reqStream = null;
HttpWebResponse objResponse = null;
StreamReader objReader = null;
try
{
objRequest = (HttpWebRequest)WebRequest.Create(StrURL);

objRequest.Method = "POST";
byte[] objBytes = objEncoding.GetBytes(strPostData);
objRequest.ContentLength = objBytes.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
reqStream = objRequest.GetRequestStream();
reqStream.Write(objBytes, 0, objBytes.Length);

IAsyncResult ar = objRequest.BeginGetResponse(new AsyncCallback(GetScrapingResponse), objRequest);
//// Wait for request to complete
ar.AsyncWaitHandle.WaitOne(1000 * 60 * 3, true);
if (objRequest.HaveResponse == false)
{
throw new Exception("No Response!!!");
}
objResponse = (HttpWebResponse)objRequest.EndGetResponse(ar);
objReader = new StreamReader(objResponse.GetResponseStream());
strReturn = objReader.ReadToEnd();

}
catch (Exception exp)
{
throw exp;
}
finally
{
objRequest = null;
objEncoding = null;
reqStream = null;
if (objResponse != null)
objResponse.Close();
objResponse = null;
objReader = null;
}
return strReturn;
}

///
/// Gets the scraping response.
///

/// <param name="result">The result.
protected void GetScrapingResponse(IAsyncResult result)
{

}


I created one more method “GetResponseWithPost”. This method actually sends data using Post method to web server. This method takes two parameters: URL and PostData. URL is just an URL of any web application. URL is not contains any query string data. Another parameter PostData contains data to post on the web server.

We need following changes to work with POST method:
  • We need one more parameter to pass Post Data
  • Need to assign “POST” to Http Web Request method property
  • Need to set ContentLength and ContentType
  • Create Stream before sending actual web request to web server

I think you have question, how to know the POST data while submitting web request to web server using browser. For this you can use LiveHTTPHeader add-ons in Firefox. This add-ons display all the post data when you access the web application using Firefox.

DotNet Code Guru