Sunday, June 11, 2006

ASP.NET tips - Level - Intermediate

How many times you have created a Object and wished that you could access the Session variables, Request , response object.
ASP.NET make it possible with

HttpContext.Current

This return the context for every request.
with this you can access the Session, Request, Response object.

One more things this context have is the Items HashTable
You can insert the key, value pair at the beginning of the request ( e.g. in a page ) and access it later on ( e.g. in the business object)

Pros : very easy to handle. No more passing too many parameters
Cons : It is for ASP.NET only. So if the object is being used in Windows apps too, you can not use this feature.


e.g. I have a control that export to excel I have created the object ExportHelper

public static void Export(
Control ctlToRender,
string StrFileName)
{
// Set the Response object
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Buffer= true;
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", String.Format("inline;filename={0}.xls",StrFileName) );
response.Write(RenderControl(ctlToRender));
response.End();
}


public static string RenderControl(Control ctlToRender)
{
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
ctlToRender.RenderControl(oHtmlTextWriter);
return oStringWriter.ToString();
}

In the page you add a button and add this to eventHandler

private void BtnExportToExcel_Click(object sender, System.EventArgs e)
{
ExportHelper.Export(DGSearch, "MyExport");
}
Where DGSearch is the Datagrid you want to export to export.

You see how I am able to use the Response object in my Export Helper object