Wednesday, 25 February 2009

HTTP Handlers and HTTP Modules

Every web request to an application is handledby http handlers.httphandlers are classes that are designated to process webrequest. There are separate handlers for each URL request.It means .aspx, .asmx file extensions are handled by different httphandlers.For example to request an page which has .aspx extension, request is handled by pagehandler,System.Web.UI.PageHandlerFactory class. Httphandler is class that implement IHTTPhandler interface.IHttphandler has a method void ProcessRequest(HttpContext context); and property bool IsReusable {get{;}set{;}}; It means customized httphandlers can be created.Reason to create customized httphandlers is that sometimes we need to process some functionality when a URL is requested ,however we don't want to place our code in aspx page as we don't need to process a page processing it would create overburden in processing. Let's look
at e-commerce application where top page displays product images. There must be hundereds of products and ofcourse each product has an asp.netapplication image is not simply displayed through Picture Box control as in desktop application.Images are rather rendered through reponse object.we cannt simply use response object in same page or control(custom control) ..We need to separate image processing code from the current page. where to pass image id through url.therefore all image displaying code is placed in ProcessRequest method which Httpcontext as a parameter which current context. All httphandlers are also configured in web.config file, for example httphandler for .asmx
webservices ,Crystalreport are defined in web.config file as

<httpHandlers> remove verb="*" path="*.asmx"/> < add verb="*" path="*.asmx" validate="false"
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
< add verb="GET,HEAD" path="ScriptResource.axd"
type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions,
Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
"GET" path="CrystalImageHandler.aspx"
type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web,
Version=10.2.3600.0, Culture=neutral,
"/> </httpHandlers>

Custom httphandlers should aslo be defined web.config file.This is called registering httphandlers , however there is also another method to register a httphandlers without web.config file changes.

Registering Httphandlers without web.config/Machine.config file changes.
using .ashx extension, httphandlers are registered automatically and all web requested that are processed through .ashx, are convereted to custom httphandlers.

  • Open any

  • Right click on soultion andclick on Add New Item.
  • From template select Generic
  • Name it as

here is class which is created inherited
from Ihttphandler and implement two memebers. The Class is created directly
under Web handler directive.

<%@ WebHandler Language="C#" Class="ImageHandler"%>



public class ImageHandler :IHttpHandler

public void ProcessRequest (HttpContext context)

context.Response.ContentType = "text/plain";



public bool IsReusable


return false;



ArrayList Databaseparams = new ArrayList();

Now we we will place our custom code to render an image in
processRquest Method.

(context.Request.Params.Count > 0)




m =

string id =

//a webservice where all data access code
is placed.

MultiPurposeWBS.MSheetService Ms = new

DataSet ds =
"select * from DProducts where
+ int.Parse(id) + "", Databaseparams.ToArray());

foreach (DataRow r in ds.Tables[0].Rows)


context.Response.ContentType = "image/JPEG";

byte[] ar =

me =

me.Write((byte[])(r["Photo"]), 0,

img = System.Drawing.

System.Drawing.Size siz

img = new

img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);



catch (Exception ex)


string str =







call this handler from another aspx page.

in the example i ve created a datalist. tag is defined in datalist with url:

id="one" src ="Imagehandler.ashx?EmpID=<%#DataBinder.Eval(Container.DataItem, "ProductID")%>" />

product is passed with when datalist is populating data, each time img tag pass url with data and fetch reponse cache data , that is inserted in ashx , file..

Ihttphandler is helpful when rendering RSS feeds as xml with no html data.

Monday, 23 February 2009

ADO.NET ENTITY framework tools

if you are using Viusal studio 2008 , .NET 3.5 is included in Viusal studio 2008. Other requirements are following.

The third one is actually a tool for creating entities from database through wizard and using visual designer to map entities with database objects.

Wednesday, 18 February 2009

ADO.NET Entity Framework Model entity framework model represents an object model that contains classes (LINQ To SQL ) entities, and association between objects.These objects are based & mapped to the datasource we provide.

Object relational designer is used to create entities.Lets create a Northwind database Object Model and query it through LINQ.I am using Entity framework wizard for quick start.
On solution right click, Add new item.
Go to Template and select Entity Framework Model.

Name it with Nortwindsamplemodel.In th wizard Generate from database.

in next step , choose connection to datasource and datasource.
  • click on new Connection
select server name from dropdown list.
choose authentication options.
select database from dropdownlist.(In example i have used Northwindump database which is a replicated database of northwind)
Test connection and press OK
for th System administrator password (sa) i am keeping password in .config file for simpilicty of this tutorial therefore i have select the option in the step given
->Yes include the sensitive data ine connection string.
Now select the database objects you want to include as entities.

Designer creates .edmx file with database entities(tables,views,stored procedure) as object on designer surface and also creates association based on Primary key,Foreign key relationship between tables in database.Every object is mapped exactly to one matching table in database.There is no option to map one object to joined table in entity framework.

Below figure shows Created Entities(Objects based on tables) and associations.

Now our model is complete and we just need to query the data via the model.

We will use LINQ for this purpose.(Note that DataContext is the main class to send and receive the data from database however we dont code it by our self as wizard has done it)
Lets create store and query category object through LINQ.

using (NorthWindDumpEntities NorthwindStore=new NorthWindDumpEntities())
var _categorylist = from _catlist in NorthwindStore.Categories
select _catlist;
foreach (Categories c in _categorylist)


Conclusion. entity together with LINQ saves greater time to do same thing by creating objects manually and doing a lot of coding.

Friday, 13 February 2009

Anonymous methods & Lambda expressions

When we declare a Delegate we usually write this code,

public delegate string aDelagateFunc(string name);

Now create a function with same signature
string otherfunc(string n)
return "hello " + n;

call this function through delegate

aDelagateFunc del = new aDelagateFunc(otherfunc);
stringstrreturnval = del("World");


To reduce this amount of code , to make the called function as Inline function , C# 2.0 introduced new feature with called " anonymous Methods".

Lets declare another delegate
public string string aDelagateFunc2(string name);

associate delegate with anonymous method
aDelagateFunc2 del2 = delegate(string s) { return "hello " + s; };
Now call anonymous method
MessageBox.Show(del2("anonymous method"));

In C# latest version ( with .Net 3.0 installed) same amount of code can be done even more shorter as anonymous methods which is called lambda expression.

in Lambda expression => operator is used to indicate the parameters on left side as input parameters(similiar to a function input parameters) and right side contain statement block(function body).

let define another delegate
public delegate string LambdaDelegate(string name);

on a button click event , write this code

LambdaDelegate _lamdadel = strname => "hello " + strname;

string strResult = _lamdadel("Lamda Expression Example");

As we see here , lambda expression code makes coding styles even more simplier.

strname as input parameters is not given explicit type,it is implicitly converted to type string by complilor , however type can be defined explicitly as

LambdaDelegate _lamdadel = ( string strname) => "hello " + strname;

It is called Type Inference as C# compiler infer the type of input parameters from function body( determine how paarmeters are used in function body.)

There can be more than one input parameters seperated by commas.
LambdaDelegate _lamdadel = ( string strname,string strlastname) => "hello " + strname;
It is not necessary to always providea input parameters , you can leave it black if no input parametrs are required like LambdaDelegate _lamdadel= ()=>"hello ";

Query operators for example count can also be used with lambda expression.

int[] numb=new int[]{1,2,3,4,5,6,7,8,9};
int _inttotal = numb.Count(n => n % 2 != 0);

This lambda expression is used in LINQ as in given sample Zenab's Tech Blog.Net: LINQ Basics

Next topic will be on Entity framework MODEL and LINQ to SQL.

Wednesday, 11 February 2009

LINQ Basics

Language Integrated Query is .net 3.0 new features for querying data source where data source is in the form collection of objects. It can be simple array, classes or sql databases.You can say simple "It is general type query language in .net World that can be applied to a variety of data sources."
Advantage of LINQ over conventional query languages(like SQL for databases) has one pattern of coding querying data source. For example Oracle or SQl server, posgres has different syntax of SQL and if one has to query that data sources in their relative syntax, one has to learn the syntax of each data source sql syntax.Other Advantage is of course is highly scalable object oriented code in n- tier Architecture.

LINQ query is executed through foreach statement and foreach statement requires that object that is quried should implement IEnumerable Interface.That is if you query a simple array , it can be queried easily with LINQ as it by default implments IEnumerable interface.All types that implments this interface are called queryable types.

Let start with simple string of array as datasource and execute it through LINQ.I will use Visual studio 2008 for example and i see

using System.Linq; namespace by default in windows forms application.

Open Windows form application. drag & drop Listbox & a button control on form. write this code on button click event.

private void button1_Click(object sender, EventArgs e)


String[] MoviesList = new String[] {"Dantes peak","Twister","Shashank redemption","Trueman show","National Treasure" };

var moviesn = from greatmovies in MoviesList

select greatmovies;

foreach (String favMovies in moviesn)





Result is shown in screen shot below.

I will discuss LINQ in depth with LINQ to SQL features later.

Sunday, 1 February 2009

Step by Step Guide to Integrate windows Workflow Foundation Business Process flow in 3.5

Here is a guide to Integrate windows Workflow Foundation Business Process flow in 3.5 C#

Windows workflow foundation is rather a programming model for creating business process workflows. before Jumping on development , you must need to know three things about windows workflow foundation

1. It has a Process Model Designer
2.Runtime Engine & Runtime Services(such as Tracking services of workflow,persistence services to store workflow execution detail in sql database.)
3.Hosting( to host a workflow in some application like,Windows Form Application)

As i described earlier windows workflow foundation is a programming model and to integrate a workflow in , one might think using workflow's base Libraries .yes, but the most exciting thing is to use that specific process's web service.


Let expose the whole Workflow as a webservice and call that webservice from a
Now it seems interesting. Here is step by step guide to expose a workflow as webservice and calling webservice methods from

1.Open Visual studio 2008( or Visual studio 2005 with .Net 3.0 Installed).
2.Select sequential Workflow Library Template

To expose workflow as webservice , drag & drop two activities on designer
1. WebserviceInputActivity which enable workflow to receive input parameters from webservice(of course we will pass parameters from
2. For a WebserviceInputActivity,we need WebserviceOutputActivity as well which returns a value from workflow to the calling method.Its is placed only on designer if there is a return value of the method that is activated in WebserviceinputActivity.

To expose Methods(that contains our workflow logic) as Web Method
Create an Interfacein the current project

To expose workflow as webservice , you need to drag & drop two activities on designer
1. WebserviceInputActivity which enable workflow to receive input parameters from webservice(of course we will pass parameters from
2. For a WebserviceInputActivity,we need WebserviceOutputActivity as well which returns a value from workflow to the calling method.Its is placed only on designer if there is a return value of the method that is activated in WebserviceinputActivity.
To Expose workflow methods as Web methods,you need to create interface nad define each method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NewUserCreationWorkflow
interface INewUserRequest
string processNewUser(string strfirstName, string strlastName);
Now in the workflow designer ,open the properties of the webserviceinput activity as it is marked with red icon (it means you to set some properties of it).

  1. Interfacetype-->NewUserCreationWorkflow.INewUserRequest(click next to interfacetype property and dialog window is opened)

3.IsActiviting->True next to strfirstname and strlastname, adialog window is opened , click on "Bind to New Member" (to bind new member. these are input parameters and by binding to these parameters designer will create code for these properties).
Normal 0 false false false MicrosoftInternetExplorer4

   1:   public static 
 DependencyProperty webServiceInputActivity1_strfirstName1Property =
   2:   DependencyProperty.Register
   3:  ("webServiceInputActivity1_strfirstName1", typeof(System.String),
   5:  [DesignerSerializationVisibilityAttribute
   6:  (DesignerSerializationVisibility.Visible)]
   8:  [BrowsableAttribute(true)]
  10:  [CategoryAttribute("Parameters")]
  12:  public String webServiceInputActivity1_strfirstName1
  14:  {
  16:  get
  18:  {
  20:  return 
  22:  }
  24:  set
  26:  {
  28:  base.SetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strfirstName1Property, value);
  30:  }
  32:  }
  34:  public static DependencyProperty
 webServiceInputActivity1_strlastName1Property = DependencyProperty.Register
("webServiceInputActivity1_strlastName1", typeof(System.String), 
  36:  [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
  38:  [BrowsableAttribute(true)]
  40:  [CategoryAttribute("Parameters")]
  42:  public String webServiceInputActivity1_strlastName1
  44:  {
  46:  get
  48:  {
  50:  return 
  52:  }
  54:  set
  56:  {
  58:  base.SetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strlastName1Property, value);
  60:  }
  62:  }
  64:  private void processNewUser(object sender, EventArgs e)
  66:  {
  68:  Random r = new Random();
  70:  NewUserIDTicket = webServiceInputActivity1_strlastName1 + r.Next(999).ToString();
  72:  }
  74:  public static DependencyProperty NewUserIDTicketProperty = 
DependencyProperty.Register("NewUserIDTicket", typeof(System.String),  
  76:  [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
  78:  [BrowsableAttribute(true)]
  80:  [CategoryAttribute("Parameters")]
  82:  public String NewUserIDTicket
  84:  {
  86:  get
  88:  {
  90:  return ((string)(base.GetValue(NewUserCreationWorkflow.Workflow1.NewUserIDTicketProperty)));
  92:  }
  94:  set
  96:  {
  98:  base.SetValue
  99:  (NewUserCreationWorkflow.Workflow1.NewUserIDTicketProperty, value);
 101:  }
 103:  }
 105:  }
 107:  }
As NewUserIDTicket is return value , we need to place WebServiceOutputActivity.
After Placing, Set properties of WebServiceOutputActivity.

  • InputActivityName->webServiceInputActivity1
  • Sendingoutput->processNewUser
  • ReturnValue->(click next to the property, a dialog box opened click on 'Bind to new member' , enter NewUserIDTicket. )

Now Publish the workflow as webservice.
In solution explorer, Right click on project and select 'Publish as Webservice'.
VS will create web.config,.asmx,.dll files.

Now open application or create new application.
here in this case i will integrate this webservice in my e-commerce web example.

Add webservice
Create a User interface form.
Add Webform
Place two textboxes , tree labels and a button

On a button click event write this code:

protected void Button1_Click(object sender, EventArgs e)
string newid;
NewUserWebservice.Workflow1_WebService _userwebservice = new NewUserWebservice.Workflow1_WebService();
newid= _userwebservice.processNewUser(TextBox1.Text.Trim(),TextBox2.Text.Trim());
Lbluserid.Text =newid;

Build the solution and run.