Author: Pranav Dave

I am working as a System Analyst in one of the reputed IT firm in Mumbai and i like to work on Microsoft technologies and exploring new things.

MVC 4 APPLICATION USING ENTITY FRAMEWORK 5.0 WITH DATABASE FIRST APPROACH

INTRODUCTION
Now a day’s most of the developers will go for Code First approach in the entity framework where the database is very small and easy to manage. In this case developers will create the model first and create the database out of it.
What in the case of large projects? Here developers will prefer to opt for Database first approach where the database is created first and data model is created out of the database.

OVERVIEW
We will be using Visual studio 2012, MVC 4 and entity frame framework 5 for this example.
We will be using Sql Server 2008 R2 for database creation.

Creating a MVC 4 Project

To start with open the visual studio 2012 and select new project from the file menu. The new project dialog box opens as shown below.
1_New_Project
Select ASP.NET MVC 4 Application and provide desired name for your project and click on the OK button. The project Template dialog box opens as shown below.

2_Project_Template
Select Internet Application from the Project Template and click on the OK button.Visual studio opens the MVC 4 project with the name which you have provided.Remove the Default created pages by .net framework 4.5.

Create a database for the project.

We will be creating the database by name “MVC_EF_DatabaseFirst” in Sql server 2008 R2.
Create a table by name Users which will maintain the details for the user.
Below is the script for the same.
USE [MVC_EF_DatabaseFirst]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[UserDetails]
(
[UserID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NOT NULL,
[Address] [varchar](1000) NULL,
[Town] [varchar](50) NULL,
[County] [varchar](50) NULL,
[Country] [varchar](50) NULL,
[Rating] [int] NULL,
[DoB] [datetime] NULL,
CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED
(
[UserID] ASC
)
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

Once you have done with creating the database and table, we will start working on project. Now we need to create the Entity Data Model class file from the Users table. To create Data model class file, we will do reverse engineering for code first.

Right click on the Project -> point to Entity Framework -> click on Reverse engineer Code first as shown below.

Reverse_code_first

This will open the connection Properties. Specify the connection details and click on the OK button as shown below.

Db_connection

This will generate the Entity data model with the mapping class add the connection string in your Web. Config file as shown below.

Mapping_Class

Open the HomeController.cs file and write the code to fetch the data from the model.

Index Page

We will start by creating an index page. Below is the screenshot for the Index page.

Index_no_records_page

Please add the below code to the Index.cshtml page.

Html_Index

In the above html code I have specified the title of the page followed by table which loops through the records for displaying the data.I have also provided the search functionality which will search for the specific record and display it in table.In the controller add the below code so that the index page will display data.

private MVC_EF_DatabaseFirstContext dbContext = new MVC_EF_DatabaseFirstContext();
public ActionResult Index(string strValue)
{
try
{
var GetUserDetails = from s in dbContext.UserDetails select s;
if (!String.IsNullOrEmpty(strValue))
{
GetUserDetails = GetUserDetails.Where(user => user.Name == strValue || user.Address == strValue || user.Town == strValue || user.Country == strValue || user.County == strValue);
}
return View("Index", GetUserDetails);
}
catch (Exception)
{
return View();
}
}

In the above code we have called UserDetails entity through the context and fetch the data into the view.

Add User

Now i will create the Add user page to add new user to the database.  Right click on the Views -> Home -> Add -> View.

It will open a dialog box to add new view. Name the view as AddUser.cshtml. Below is the screenshot for the same.

Add_New_User

Now add the below code in the controller for add user page working.

public ActionResult AddUser()
{
return View();
}

[HttpPost]
public ActionResult AddUser(UserDetail objUserdetails)
{
try
{
if (ModelState.IsValid)
{
dbContext.UserDetails.Add(objUserdetails);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(objUserdetails);
}

In the above code we have created the object of the UserDetails entity and used that object to fill the data into the context.

ModelState.IsValid will validate the data entered by the user. Now I need to provide other validations such length of the string etc on the field.

For that open the UserDetails.cs file under Models folder.

Add the data annotations to each field as shown in the below code.

public partial class UserDetail
{
public int? UserID { get; set; }

[Display(Name="User Name")]
[Required]
[StringLength(50, ErrorMessage = "User name cannot be longer than 50 characters.")]
public string Name { get; set; }

[Display(Name = "User Address")]
[Required]
[StringLength(1000, ErrorMessage = "User Address cannot be longer than 1000 characters.")]
public string Address { get; set; }

[Display(Name = "User Town")]
[Required]
[StringLength(50, ErrorMessage = "User Town cannot be longer than 50 characters.")]
public string Town { get; set; }

[Display(Name = "User County")]
[Required]
[StringLength(50, ErrorMessage = "User County cannot be longer than 50 characters.")]
public string County { get; set; }

[Display(Name = "User Country")]
[Required]
[StringLength(50, ErrorMessage = "User Country cannot be longer than 50 characters.")]
public string Country { get; set; }

public Nullable<int> Rating { get; set; }

[Display(Name = "User Date of Birth")]
[Required]
[DisplayFormat(DataFormatString = "{0:dd MMMM, yyyy}")]
public Nullable<System.DateTime> DoB { get; set; }
}

The above code checks for required, string length and date format.

Edit User

When the user clicks on the Edit Hyperlink in the table it will navigate to the Edit user page.

To create the Edit User page, right click on the Views -> Home -> Add -> View.

It will open a dialog box to add new view. Name the view as EditUser.cshtml. Below is the screenshot for the same.

Edit_user

Create a view by name EditUser.cshtml and add the below code for the same.

Html_EditNow add the below code in the controller for displaying the records in the Edit mode and save it after changes.

public ActionResult EditUser(int id = 0)
{
UserDetail userDetail = dbContext.UserDetails.Find(id);

if (userDetail == null)
{
return HttpNotFound();
}
return View(userDetail);
}


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditUser(UserDetail objUserdetails)
{
try
{
if (ModelState.IsValid)
{
dbContext.Entry(objUserdetails).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
}

catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View();
}

In the above code the Edit user page will display records in the edit mode for that particular user. Once the data is modified the user can save the changes in to the database.

User Details

User details page will display the all the details for that particular user when clicked on the Details link from the grid.

To create the User Details page, right click on the Views -> Home -> Add -> View.

It will open a dialog box to add new view. Name the view as EditUser.cshtml. Below is the screenshot for the same.

User_Details

Create a view by name UserDetails.cshtml and add the below code for the same.

Html_Details

Add the below code in the controller for user detail functionality.

public ActionResult UserDetails(int id = 0)
{
UserDetail userDetail = dbContext.UserDetails.Find(id);

if (userDetail == null)
{
return HttpNotFound();
}
return View(userDetail);
}

The above code will take user id as a input parameter and displays the data accordingly.

Delete User

Create a delete User page by name DeleteUser.cshtml and add the below code in the page.

Html_Delete

Add the below code in the Controller.

public ActionResult DeleteUser(int id = 0)
{
UserDetail userDetail = dbContext.UserDetails.Find(id);
if (userDetail == null)
{
return HttpNotFound();
}
return View(userDetail);
}

[HttpPost, ActionName("DeleteUser")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
try
{
UserDetail userDetail = dbContext.UserDetails.Find(id);
dbContext.UserDetails.Remove(userDetail);
dbContext.SaveChanges();
}
catch (DataException)
{
return RedirectToAction("DeleteUser", new { id = id, saveChangesError = true });
}
return RedirectToAction("Index");
}

The above code will take user id as a parameter and displays all the user details on the page.

When the user clicks on the delete button DeleteConfirmed action result will get fired deleting the user and redirection it back to the index page.

The source code can be downloaded from Here.

ERROR HANDLING USING ELMAH IN MVC

INTRODUCTION

Error Handling is the one of the most important thing which we used to track errors.

There are different ways of handling errors which developers preferred to log errors. Some developers write their own code to log errors in database, XML files or either text files.

There are also third party tools available to log errors. In this article I will show you how to log errors in the database using Google Elmah error handling in MVC application.

OVERVIEW

To integrate Elmah tool in your application you need to download the file from the Google code site.

To download the file click on the following link: – http://code.google.com/p/elmah/.

Or you can install through the Nuget package manager. You can install the Nuget package manager through the visual studio Library Package Manager. For more information visit http://www.nuget.org/

I will be installing the Elmah using the Nuget package manager.

I will be demonstrating the use of Elmah in Visual Studio 2012 using MVC 4 application.

Open the visual studio 2012 and select New Project from the start menu.

This will open the New Project dialog box as shown below.

New_Project

Select MVC 4 web Application from the template and provide the name of the project.

This will open the MVC 4 project template as shown below.

Project_Template

Select the Internet application and click on the OK button to launch the MVC 4 project.

Now, we will install the Elmah through the Nuget package manager.

Select tools from the menu and point to Library Package Manager. Select Manage Nuget Packages for Solution as shown below.

Nuget_manager_Console

This will open the Package Manager Console. Now install the Elmah using the below command.

Install-Package Elmah

This will install the Elmah package in to the application as shown below.

Install_elmah_Nuget

It will automatically add all the details in to the Web.Config file.

A couple of modification is required to make in the Web.config files to make Error logging work.

You need to add handlers and make modification in the Elmah section as shown below.

Just specify the data source, user name and password in your connection string and rest of the settings for Elmah you need to specify as shown below.

Config

Now you need to create the database for logging the errors.

To download the Elmah script visit the link https://code.google.com/p/elmah/source/browse/src/Elmah.SqlServer/SQLServer.sql

Once done with the above configuration we will write a code to generate the error.

Now we need to make use of Elmah for logging the error in the database you have created.

For testing the Elmah error log create a method that will generate the error as shown below.

private void Division()
{
try
{
int i = 0;
int j = 2;
int x = j / i;
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}

Call this method in the Index Action Result.

ErrorSignal.FromCurrentContext().Raise(ex) is used to log error and store it in database.

To check the error, just open the browser and type the URL of your web application followed by elmah.axd. Below is the screenshot.

Elmah

Now access the URL for example. http://localhost:6061/elmah.axd

You can see the screen in the grid format displaying the details of your error.
To view more details related to your error click on the details link next to your error. The details explanation of the error will be displayed as shown below.

Elmah_Details

For more information Elmah Error logging refer to the below link.

http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/logging-error-details-with-elmah-cs

To download the demo project, click Here.

Error logging using Elmah

INTRODUCTION
Developers mostly use the third party controls for logging errors in asp.net applications or some may write custom code for logging errors.

In this article I will mentioned such third party control for logging errors. It is very handy, easy to use and useful control for logging errors in asp.net application.

This tool is developed by Google and it is free and open source. The name of the tool is ELMAH.

OVERVIEW
To integrate Elmah tool in your application you need to download the file from the google code site.
To download the file http://code.google.com/p/elmah/.
The zip file contains the source code and bin file. You need to add the Elmah.dll, ElmahErrorLog.dll, VistaDB.NET20.dll, System.Data.SQLite.dll, Elmah.xml file in your applications bin folder.
Add the reference for above dll files.
Error can be logged in many ways.

  1. In memory
  2. Store error in sql server.

In memory store the error in memory. You can view the error at runtime and the error does not gets stores anywhere.

To make sure the data gets store in somewhere, you need to create the table in sql server.
The source code which you download contains the sql server file. Just run the query and the table will be created automatically as shown below.

As shown above it will create ELMAG_error table in your database. IT also creates couple of procedures for inserting data.

Now we need to configure your web.config file to put elmah to work. Add elmah module to your web.config file.

Just specify the data source, user name and password in your connection string and rest of the settings for elmah you need to specify as shown above.

Now we need to make use of elmah for logging the error in the database you have created.

For testing the Elmah error log create a method that will generate the error as shown below.

using System;
using System.Web.UI;
using Elmah;
public partial class ElmahErrorLog : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Division();
}
}

private void Division()
{
try
{
int i = 0;
int j = 2;
int x = j / i;
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
}

ErrorSignal.FromCurrentContext().Raise(ex) is used to log error and store it in database.

To check the error, just open the browser and type the URL of your web application followed by elmah.axd. Below is the screenshot.

You can see the screen in the grid format displaying the details of your error.

To view more details related to your error click on the details link next to your error. The details explanation of the error will be displayed as shown below.

This is how you can use elmah error logging for logging errors.

This is just the short description of elmah error logging. For more details for elmah error logging click here.

To download the source code click here.

Search/Locate directions/place using Bing maps

INTRODUCTION
You must be familiar with the Google maps. In this article, I will introduced to the Bing maps and provide search functionality on Bing maps.

EXAMPLE
You must have integrated Google maps in your web application and provide search functionality on it. In this article, I will show you to integrate Bing maps in your web application and provide search functionality to search location or directions.

Let us start with the basic example.
To start with, the example you need to call JavaScript api in your html page in the head section  as shown below.

<script type=”text/javascript” src=”http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&#8243;></script>

First, we will start with designing a HTML page. The HTML page will look as shown below.

In the above HTML we have call the Bing map api script in the head section in HTML as shown above.
We will be creating one more script file, which will contain the script for creating Bing maps nad search functionality.
In above HTML we are calling LoadBingMap(); JavaScript method on the body onload for loading maps on as when the page loads.

The below is the method which is used to load Bing maps on page load.

var map = null;
//Load Normal Map.
function LoadBingMap()
{
try
{
map = new VEMap(‘myMap’);
map.LoadMap(new VELatLong(22.55, 72.54), 5, ‘r’, false);
}
catch (e)
{
}
}

map = new VEMap(‘myMap’);
In the above code, the variable map stores the id of the div tag where the map will be loaded.

map.LoadMap(new VELatLong(22.55, 72.54), 5, ‘r’, false);
In the above code, LoadMap() function is used to load a basic Bing map. It will take parameter such as latitude and longitude, type of map to load and so on.

//For Finding Information.
function FindLoc()
{
var txtsearch = document.getElementById(“txtsearch”);
try
{
map.Find(null, txtsearch.value);
}
catch (e)
{
alert(e.message);
}
}

The above code is to find location using maps.

map.Find(null, txtsearch.value);
The above code is to find location on Bing maps.

For more information on visit http://msdn.microsoft.com/en-us/library/bb429645.aspx

That is it. Run the HTML in your browser and see the result. You will get the following result as shown below.

To view my sample application on Bing maps click here:
http://pranavmapia.co.nr/

For more articles on maps visit http://davepranav.co.nr

You can download the source code here.

Introduction to Bing Maps

INTRODUCTION
Here I will introduce you to the Bing maps. This article shows how to integrate Bing maps in your web application.

EXAMPLE
You must have integrated Google maps in your web application, but in this article, I will show you to integrate Bing maps in your web application.
Let us start with the basic example.
To start with, the example you need to call JavaScript api in your html page as shown below.

<script type=”text/javascriptsrc=”http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2“></script>

First, we will start with designing a HTML page. The HTML page will look as shown below.

In the above HTML we have call the Bing map api script in the head section in HTML as shown above.
We will be creating one more script file, which will contain the script for creating Bing maps.
In above HTML we are calling LoadBingMap(); JavaScript method on the body onload for loading maps on as when the page loads.
The below is the method which is used to load Bing maps on page load.

var map = null;
//Load Normal Map.
function LoadBingMap()
{
try
{
map = new VEMap(‘myMap’);
map.LoadMap(new VELatLong(22.55, 72.54), 5, ‘r’, false);
}
catch (e)
{
}
}

map = new VEMap(‘myMap’);
In the above code, the variable map stores the id of the div tag where the map will be loaded.

map.LoadMap(new VELatLong(22.55, 72.54), 5, ‘r’, false);
In the above code, LoadMap is used to load a basic Bing map. It will take parameter such as latitude and longitude, type of map to load and so on.

That is it. Run the HTML in your browser and see the result. You will get the following result as shown below.

I have created a small application representing Bing maps. To view my sample application click here.

You can download the source code here.

Introduction to Webparts

INTRODUCTION
In this article I will show you to use various aspects of webparts in ASP.net. Using webparts you can provide user with the option to drag and drop objects, changing the CSS at runtime.

EXAMPLE
There are 2 basic things in Webparts:-
1. WebPartManager
2. Webparts Zone

WebPartManager
All Webparts is managed under WebPartManager. You are required to use WebPartManager where ever you are using Webparts in your project. Webparts will not work without WebPartManager.

Webparts Zone
There are 4 kind of zone in web part that is required to build a web part. The 4 zones are:
1. WebPartZone
2. EditorZone
3. CatalogZone
4. ConnectionZone

To use different zones add a dropdown list to your webform and add the following items to it.
• Browse
• Design
• Edit
• Catalog
• Connect

You need to write the code on the selectedIndexChange event of dropdownlist.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Text == “Select”)
{
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Design”)
{
WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Browse”)
{
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Catalog”)
{
WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Edit”)
{
WebPartManager1.DisplayMode = WebPartManager.EditDisplayMode;
}
else if (DropDownList1.SelectedItem.Text == “Connect”)
{
WebPartManager1.DisplayMode = WebPartManager.ConnectDisplayMode;
}
}

BROWSE MODE
First we will look at the browse mode. It is the default mode in your webpart. No actions such as drag and drop, changing CSS etc can be performed using browse mode. In case of browse mode only 2 options are seen i.e. minimize and close. Using minimize options you can minimize the webpart and using close option you can close the webpart which can only be restored while being in catalog mode which we will discuss later in this article. Below is the screenshot of sample webpart displayed below.

DESIGN MODE
In design mode we can drag drop objects from one webpart zone to another webpart zone. For that purpose select Design from the dropdown menu and then drag the object from one zone to another zone. In the below screenshots we are dragging control from “Display name “webpart zone to “Enter name” webpart zone.

EDIT MODE
In this mode we can edit the webpart at runtime.  We can perform various actions such as changing the size, color etc of the textbox. Edit mode is further divided in to 4 parts. They are Appearance, behavior, Property and layout. We will first look at the Appearance and Layout part.
First, place an editor zone into the web form. Then place an AppearanceEditorPart and LayoutEditorPart inside the editor zone. Run the application and select the “Edit” mode from the dropdown list.
On selecting the Edit mode from the dropdown menu, the webpart will appear with one more option of Edit. Click edit from the menu available for webparts.

On selecting Edit mode you will get the below output.
You can perform various actions such as changing the title name, specifying the chrome type, changing the width and height of the control etc.
For e.g. if you want to change the title name just specify the title name and then click on the ok button provided below. On clicking the ok button changes will be reflected.
The below is the screenshot.

Now, suppose if you want to change the property of the object in webpart such as changing the CSS of the object in a webpart. This can be achieved using PropertyGridEditorPart.
For that purpose create a user control with textbox and button and place that user control inside the webpart zone.
In this case we will change the CSS class of textbox and button. For that create one css class and give the reference of that css class in your page.
The below is the CSS class.

.textbox_1
{
background-color:White;
color:Blue;
border:solid 2px blue;
}

.button_1
{
background-color:White;
color:Blue;
border:solid 2px blue;
}

.textbox_2
{
background-color:White;
color:Black;
border:solid 2px black;
}

.button_2
{
background-color:White;
color:Black;
border:solid 2px black;
}

In the code behind of the user control write the following code.

string _cssClasstextbox = string.Empty;
string _cssClassbutton = string.Empty;
[WebBrowsable(), Personalizable(true)]
public string CssClassTextbox
{
get { return _cssClasstextbox; }
set { txtname.CssClass = value;}
}
[WebBrowsable(), Personalizable(true)]
public string CssClassButton
{
get { return _cssClassbutton; }
set { btnclick.CssClass = value;}
}
protected void Page_Load(object sender, EventArgs e)
{
txtname.CssClass = CssClassTextbox;
btnclick.CssClass = CssClassButton;
}

The above code changes the CssClass of the TextBox and button. This property will now be available in the webparts edit mode and we will be able to change this at run-time as well. Besides setting the CssClass we have also used two additional attributes in the class declaration:

  • WebBrowsable – It allows a webpart to display a user defined property in edit mode.
  • Personalizable – It allows a property to be editable.

Now run this page. If we choose the edit mode from the webpart menu, we will see the following edit button in options menu of the webpart. The screenshot below illustrates this.

On selecting edit mode from the option, we will have the CSS property in the edit mode. The below is the screenshot.

Currently Textbox and button is using the default Css property. Now we will apply the new CSS class from the stylesheet for e. g textbox_2 and button_2 and click on the ok button.
The style of the textbox and button will get change as shown below.

CATALOG MODE
The catalog zone gives us the option to add/remove, hide/show the webparts at runtime. For example say there are few webparts on Webform such as webpart showing weather condition, time, daily horoscope etc. Now if the user wants to remove or hide the webpart at runtime, then it can be accomplished using catalog mode.
To use catalog mode you need to catalog zone. The catalog zone is further divided in to three parts. They are PageCatalogPart, DeclarativeCatalogPart and ImportCatalogPart.
On the Webform add one catalog zone and add all the above catalog part in to it.

Page catalog
Suppose if you want to remove Enter name webpart from the page at runtime. You can do it by just by selecting close option from the webpart options.

Now you want the same webpart to appear in your page again. To do that select catalog options from the dropdown list. You will see the catalog zone with the all the above three parts as shown below.

You can see in the above screen shot that Enter Name webpart appears in the Page Catalog zone. Select the Enter Name webpart and select the zone from the dropdown list to which you want to add the selected webpart.
The selected webpart will be added to the respective zone which you have selected.

Imported Web part catalog
Suppose user want to add new external webpart. He can do that by importing webpart. We can import files with the extension .webpart. To export a file as a .webpart type, add the following line to your web.config inside the <system.web> tag.

<webParts enableExport=”true“></webParts>

To import webpart, click on the “Imported web part catalog” link in catalog zone.  It will display the fileupload control from where you can upload the file. Once the file is uploaded it will below fileupload control. Select the webpart and select the zone from the dropdown list to which you want to add the webpart. The below is the screenshot.

Selected webpart get added to your webpart zone.

CONNECT MODE
Connect mode allows webpart to connect with each other. We can make static connections through code or we can make connections at runtime according to the requirement. Here webpart is not connecting to database. Instead it is connecting to another webpart.
In our example we will create 2 controls b y name “name.ascx” and “Displayname.ascx”. One is for passing the text and another is for receiving the text.
Add a new class in the App_Code directory and name it ITextProvider. Add the following code to it.

public class ITextProvider
{
public interface ITextToPass
{
string GetText();
}
}

We are going to use this interface in both user controls to pass text between these two entities.
Add one textbox and a button in the name.ascx control. Add the below code in “name.ascx” page just above the page load.

[ConnectionProvider(“TextToPass”, “TextProvider”)]
public ITextProvider.ITextToPass GetTextTransferInterface()
{
return ((ITextProvider.ITextToPass)(this));
}

public string GetText()
{
return txtname.Text;
}

Add one label in another control in “Displayname.ascx”. Add the below code in “Disaplayname.ascx” page just above the page load.

[ConnectionConsumer(“Text”, “TextConsumer”)]
public void GetTextTransferInterface(ITextProvider.ITextToPass provider)
{
lblName.Text = provider.GetText();
}

Run the example. Select connect mode from the dropdown list.  Then select connect option from the webpart, connection zone appears. Then click on the Create a connection to a Consumer link in the connection zone as shown below.

On clicking the hyperlink it will display the below screen.

Select the webpart as a consumer from the dropdown list and click on the connect button.

Once the connection is established you can test the connect mode. Enter any text in name webpart and click on the button. It will display the entered string in another webpart as shown below.

SAVING PAGE STATE IN DATABASE
Suppose there are multiple users accessing your application and you need to save page setting for each users. In that case you need a store the users setting in database.
In this case we will create a database to store users setting. We are going to use the default asp.net database called ASPNETDB.mdf which is automatically created in applications app_data folder. This database already has the appropriate schema to save the page state for every user.
To create the default database for webparts you need to run the utilitynamed as aspnet_regsql.exe which is located in the C:\Windows\Microsoft.NET\Framework\v2.0.50727. This utility helps us to create tables and stored procedures required to customize database. The below is the screenshots.

Just follow the wizard to create the default database. It will create the following tables in database.

That’s it.

To download the source code click here.

Introduction To Windows WorkFlow Foundation(WWF)

INTODUCTION
In this article I will give some brief introduction to Windows Workflow Foundation (WF) using small example. Windows Workflow Foundation (WF) is a Microsoft technology for defining, executing, and managing workflows. This technology was first released in November 2006 as a part of .NET Framework 3.0. The Windows Workflow foundation provides a platform built on the .Net Framework for building workflows. It is not an application or a server product, and is included as a component of the .Net 3.0 framework. It is kind of flowchart that represents various steps to be executed in your application.

There are 2 major features of WWF:-

  1. Visual Representation of process (es)
  2. Can be dynamically modified at run-time

There are two major types of workflows:-

  1. Sequential workflows: used for well-defined, process workflows
  2. State Machine workflows: Organized as state machine diagrams, typically used for workflows with human interaction.


EXAMPLE
Here I will represent a small startup example from the Microsoft press book. This example will validate the postal code based on the condition. Here I will represent example in the series of steps to create a simple workflow console example.

STEP 1:-
Create a Workflow console application. Open visual studio 2008. Select File -> New -> Project from the menu. New project dialog box opens. Select Sequential Workflow console application from the available templates. Specify the project name in the name textbox and click on the ok button to create console application as shown below. We will first start with the designing part.

STEP 2:-
It will create the application with the default files as shown below.

The application will look something as shown below.

STEP 3:-
Drag and drop the IfElse activity from the toolbox as shown below.

It will create the IfElseActivity with two activity branch as shown below.

STEP 4:-
Specify the condition for the IfElseBranchActivity1 as shown below. Select IfElseBranchActivity1 and click on the properties tab. Select Code condition from the condition dropdown menu.

Give the condition name as EvaluatePostalCode in the condition. It will create the default handler for the activity as shown below.

STEP 5:-
Now drag and drop the code from the toolbox in to the IfElseBranchActivity1 .This will create the code activity where you will specify the condition for your application as shown below.

Repeat the same thing for IfElseBranchActivity2.

STEP 6:-
Now specify the handler for code activity. To specify the handler for the codeactivity1, select codeactivity1 and click on the properties tab. Give the handler name as ValidPostalCode . This will create the default handler for codeactivity1.

Repeat the same step for codeactivity2 as shown below. Give the handler name as InValidPostalCode as shown below.

Here the designing part gets over. Now we will start with the coding part.
In this example we are validating the Postal code based on the user’s Input.
Write the code on the EvaluatePostalCode method for validating the use input. The below is the code for validating the postal code.

private void EvaluatePostalCode(object sender, ConditionalEventArgs e)
{
string USCode = @”^(\d{5}$)|(\d{5}$-\d{4}$)”;
string CanadianCode = @”[ASDFGHJKLXYZ]\d[A-Z]\d[A-Z]\d”;
e.Result = (Regex.IsMatch(_code, USCode) || Regex.IsMatch(_code, CanadianCode));
}

Here we are validating US and Canadian Postal Code.
We are declaring public property which will take the user input.

public string _code = string.Empty;
public string PostalCode
{
get { return _code; }
set { _code = value; }
}

I will provide the message to be displayed after validating the user input. For that write the code as shown below.

private void ValidPostalCode(object sender, EventArgs e)
{
Console.WriteLine(“The postal code {0} is valid”, _code);
}
private void InValidPostalCode(object sender, EventArgs e)
{
Console.WriteLine(“The postal code {0} is Invalid”, _code);
}

When you create a project one default file by name Program.cs is created in the solution. It contains the static main method created to run your application. Modify the code as per the requirement.

Add the below code just above the WorkFlowInsance.

Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add(“PostalCode”, args.Length > 0 ? args[0] : “”);
Modify the WorkFlowInsance code as shown below.
WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WWF_Example.Workflow1), dict);

Build the example by selecting Debug -> build <application>
Now it is the time to test the application. To test the application open the command prompt and navigate to the Debug folder which is located in your application folder and then type

<application name> 12345 (e.g. WWF_Example 12345) as shown below.

That’s it. It will test whether the postal code is valid or invalid.

To download the source code Click here.