Wednesday 25 February 2009

HTTP Handlers and HTTP Modules

Every web request to an asp.net 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 asp.net 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 asp.net application where top page displays product images. There must be hundereds of products and ofcourse each product has an image.in 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"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35"/>
< add verb="GET,HEAD" path="ScriptResource.axd"
type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions,
Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
validate="false"/>
"GET" path="CrystalImageHandler.aspx"
type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web,
Version=10.2.3600.0, Culture=neutral,
PublicKeyToken=692fbea5521e1304
"/> </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 asp.net
    application.

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




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"%>

using
System;

using
System.Web;

public class ImageHandler :IHttpHandler
{

public void ProcessRequest (HttpContext context)
{

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

context.Response.Write("Hello
World"
);

}

public bool IsReusable
{

get
{

return false;

}


}





ArrayList Databaseparams = new ArrayList();


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


if
(context.Request.Params.Count > 0)


{


try


{


System.IO.MemoryStream
m =
new
System.IO.
MemoryStream();


string id =
(context.Request.QueryString[0].ToString());


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


MultiPurposeWBS.MSheetService Ms = new
MultiPurposeWBS.
MSheetService();


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


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


{


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


byte[] ar =
(
byte[])(r["Photo"]);


System.IO.MemoryStream
me =
new
System.IO.
MemoryStream();


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



System.Drawing.Image
img = System.Drawing.
Image.FromStream(me);


System.Drawing.Size siz
=
new
System.Drawing.
Size(125,
160);


img = new
System.Drawing.
Bitmap(img,
siz);


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


}


}


catch (Exception ex)


{


string str =
ex.Message;


System.Diagnostics.Debug.WriteLine(str);


}


finally


{


}


}



call this handler from another aspx page.

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




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

product is passed with productid.so 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

ADO.net 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 ADO.net Entity framework wizard for quick start.
On solution right click, Add new item.
Go to Template and select ADO.net 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 ADO.net 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)
{
listBox1.Items.Add(c.CategoryName);
}

}

Conclusion. ADO.net 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");

MessageBox.Show(strreturnval);


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");
MessageBox.Show(strResult);

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);
MessageBox.Show(_inttotal.ToString());


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

Next topic will be on ADO.net 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 mandatory.so 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)

{

listBox1.Items.Add(favMovies);

}

}









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 Asp.net 3.5

Here is a guide to Integrate windows Workflow Foundation Business Process flow in Asp.net 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 Asp.net,Windows Form Application)

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

How?

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

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 asp.net)
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 asp.net)
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)



2.MethodName->processNewUser
3.IsActiviting->True


4.click 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),
 typeof(NewUserCreationWorkflow.Workflow1));
   4:   
   5:  [DesignerSerializationVisibilityAttribute
   6:  (DesignerSerializationVisibility.Visible)]
   7:   
   8:  [BrowsableAttribute(true)]
   9:   
  10:  [CategoryAttribute("Parameters")]
  11:   
  12:  public String webServiceInputActivity1_strfirstName1
  13:   
  14:  {
  15:   
  16:  get
  17:   
  18:  {
  19:   
  20:  return 
((string)
(base.GetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strfirstName1Property)));
  21:   
  22:  }
  23:   
  24:  set
  25:   
  26:  {
  27:   
  28:  base.SetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strfirstName1Property, value);
  29:   
  30:  }
  31:   
  32:  }
  33:   
  34:  public static DependencyProperty
 webServiceInputActivity1_strlastName1Property = DependencyProperty.Register
("webServiceInputActivity1_strlastName1", typeof(System.String), 
typeof(NewUserCreationWorkflow.Workflow1));
  35:   
  36:  [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
  37:   
  38:  [BrowsableAttribute(true)]
  39:   
  40:  [CategoryAttribute("Parameters")]
  41:   
  42:  public String webServiceInputActivity1_strlastName1
  43:   
  44:  {
  45:   
  46:  get
  47:   
  48:  {
  49:   
  50:  return 
 ((string)
(base.GetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strlastName1Property)));
  51:   
  52:  }
  53:   
  54:  set
  55:   
  56:  {
  57:   
  58:  base.SetValue
(NewUserCreationWorkflow.Workflow1.webServiceInputActivity1_strlastName1Property, value);
  59:   
  60:  }
  61:   
  62:  }
  63:   
  64:  private void processNewUser(object sender, EventArgs e)
  65:   
  66:  {
  67:   
  68:  Random r = new Random();
  69:   
  70:  NewUserIDTicket = webServiceInputActivity1_strlastName1 + r.Next(999).ToString();
  71:   
  72:  }
  73:   
  74:  public static DependencyProperty NewUserIDTicketProperty = 
DependencyProperty.Register("NewUserIDTicket", typeof(System.String),  
typeof(NewUserCreationWorkflow.Workflow1));
  75:   
  76:  [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
  77:   
  78:  [BrowsableAttribute(true)]
  79:   
  80:  [CategoryAttribute("Parameters")]
  81:   
  82:  public String NewUserIDTicket
  83:   
  84:  {
  85:   
  86:  get
  87:   
  88:  {
  89:   
  90:  return ((string)(base.GetValue(NewUserCreationWorkflow.Workflow1.NewUserIDTicketProperty)));
  91:   
  92:  }
  93:   
  94:  set
  95:   
  96:  {
  97:   
  98:  base.SetValue
  99:  (NewUserCreationWorkflow.Workflow1.NewUserIDTicketProperty, value);
 100:   
 101:  }
 102:   
 103:  }
 104:   
 105:  }
 106:   
 107:  }
 108:   
 109:   
 110:   
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 asp.net application or create new asp.net application.
here in this case i will integrate this webservice in my e-commerce Asp.net 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.