Posts Tagged ‘ASP.NET’

Excel Repot From Data Table

February 23, 2010
Code for coverting Data table Execl Report

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Reflection;

namespace Common
 /// <summary>
 /// Download Excel
 /// </summary>
 public class DownloadExcel : System.Web.UI.Page

 #region Methods (4)

 // Public Methods (3)

 /// <summary>
 /// Generics the list to data table.
 /// </summary>
 /// <param name="list">The list.</param>
 /// <returns></returns>
 public static DataTable GenericListToDataTable(object list)
 DataTable dt = null;
 Type listType = list.GetType();
 if (listType.IsGenericType)
 //determine the underlying type the List<> contains
 Type elementType = listType.GetGenericArguments()[0];

 //create empty table -- give it a name in case
 //it needs to be serialized
 dt = new DataTable(elementType.Name + "List");

 //define the table -- add a column for each public
 //property or field
 MemberInfo[] miArray = elementType.GetMembers(
 BindingFlags.Public | BindingFlags.Instance);
 foreach (MemberInfo mi in miArray)
 if (mi.MemberType == MemberTypes.Property)
 PropertyInfo pi = mi as PropertyInfo;
 else if (mi.MemberType == MemberTypes.Field)
 FieldInfo fi = mi as FieldInfo;
 dt.Columns.Add(fi.Name, fi.FieldType);

 //populate the table
 IList il = list as IList;
 foreach (object record in il)
 int i = 0;
 object[] fieldValues = new object[dt.Columns.Count];
 foreach (DataColumn c in dt.Columns)
 MemberInfo mi = elementType.GetMember(c.ColumnName)[0];
 if (mi.MemberType == MemberTypes.Property)
 PropertyInfo pi = mi as PropertyInfo;
 fieldValues[i] = pi.GetValue(record, null);
 else if (mi.MemberType == MemberTypes.Field)
 FieldInfo fi = mi as FieldInfo;
 fieldValues[i] = fi.GetValue(record);
 return dt;

 /// <summary>
 /// Gets the date from string.
 /// </summary>
 /// <param name="strDate">The STR date.</param>
 /// <returns></returns>
 public static DateTime GetDateFromString(string strDate)
 DateTime dt;
 Int32 intOADate = Int32.Parse(strDate);
 dt = DateTime.FromOADate(intOADate);
 try //try with dd/MM/yyyy
 IFormatProvider culture = new CultureInfo("fr-FR", true);
 dt = DateTime.Parse(strDate, culture);
 catch //try with MM/dd/yyyy
 IFormatProvider culture = new CultureInfo("en-US", false);
 dt = DateTime.Parse(strDate, culture);
 return dt;

 /// <summary>
 /// Function to export grid data to excel
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="entityList">The entity list.</param>
 /// <param name="hashTable">The hash table.</param>
 public void GetExcel<T>(List<T> entityList, Dictionary<int, string> hashTable) where T : class

 ExportExcel(entityList, hashTable);


 // Protected Methods (1)

 /// <summary>
 /// Exports the excel.
 /// </summary>
 /// <param name="entityList">The entity list.</param>
 /// <param name="hashTable">The hash table.</param>
 protected void ExportExcel(object entityList, Dictionary<int, string> hashTable)

 DataTable dt = GenericListToDataTable(entityList);
 Response.ContentType = "application/";
 Response.AddHeader("Content-Disposition", "attachment; filename=Reports.xls");
 //Response.ContentType = "application/";
 string sep = "";
 ICollection keyCollection = hashTable.Keys;
 int[] keys = new int[keyCollection.Count];
 keyCollection.CopyTo(keys, 0);
 for (int i = 0; i < dt.Columns.Count; i++)

 Response.Write(sep + dt.Columns[i].ColumnName);
 sep = "\t";
 //excelTableColumn = excelTableColumn + "[" + hashTable[keys[i]] + "] text ,";
 //foreach (DataColumn dc in dt.Columns)
 //    Response.Write(sep + dc.ColumnName);
 //    sep = "\t";

 // int i;
 foreach (DataRow dr in dt.Rows)
 sep = "";
 for (int i = 0; i < dt.Columns.Count; i++)
 Response.Write(sep + dr[i].ToString());
 sep = "\t";


 #endregion Methods


The Above code you can be placed in common folder or App_code(freamwork 2.0) when you are creating report page
inherit this class to Report page like following code

/// <summary>
 /// </summary>
 public partial class DelayedVechiclesBodyTypeReport :  DownloadExcel
 #region Private variables
//your code

in Generate Report button Click write the following code :

#region Web Generated Events
 /// <summary>
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btnGenerateReport_Click(object sender, EventArgs e)
 List<ReportDelayedVehicleEntity> delayedVehicleDetailsList;
 delayedVehicleDetailsList = reportService.GetDelayVechiclesBodyTypeReport(Convert.ToInt32( rdoBodyType.SelectedValue));
 Dictionary<int, string> excelHashTable = new Dictionary<int, string>();
 excelHashTable.Add(0, "BodyNo");
 excelHashTable.Add(1, "ModelCode");
 excelHashTable.Add(2, "SuffixCode");
 excelHashTable.Add(3, "ColorCode");
 excelHashTable.Add(4, "JigInDate");
 excelHashTable.Add(5, "FrameNo");
 excelHashTable.Add(6, "ASSPlanned_LO");
 excelHashTable.Add(7, "EngineNo");
 excelHashTable.Add(8, "CurrentStageID");
 excelHashTable.Add(9, "CarFamily");
 excelHashTable.Add(10, "LotCode");
 excelHashTable.Add(11, "SpecSheetNumber");
 excelHashTable.Add(12, "EngineModelcode");
 excelHashTable.Add(13, "StageName");
 excelHashTable.Add(14, "StandardDefectName");
 excelHashTable.Add(15, "Remark");
 excelHashTable.Add(16, "DelayedDays");
 excelHashTable.Add(17, "RootResponsibilityName");
 excelHashTable.Add(18, "RepairResponsibilityName");
 excelHashTable.Add(19, "TargetDate");

 GetExcel(delayedVehicleDetailsList, excelHashTable);


ASP.NET Performance Check List

October 27, 2009

I found these articles very helpful improve the  Performance  of  our  sites

find out from these articles

then  prepare check list like  as follows:

Check List Status (Done/Not Done) Performance (in %)
Database Side
1.       Use proper indexing
2.        Avoid joints for high density tables
3.       Use SQL profiler to check work load
4.       Use Database Tuning Advisor for analyzing database performance
5. Use NOLOCK select Query for viewing data
6.       Select proper Hardware for running SQL Server
7.       Dot use Cursor
8.       Use Custom Pagination in SQL2005 (Row Count)
9.       Add your own check list
1)       Use Trace log to analyze performance of each function
2)       Turn off View Sate if not required
3) Compressing the View State (GZIP)
4)       Minimize use of Session object and don’t initialize large object like data set to session
5) Enabling HTTP Compression Support in IIS 6
6)       Use proper ASP.NET cache mechanism according to situation
7)       Use light weight controls like repeater replace with grid control and minimize use of controls
8)       Use StringBuilder for Complex String Manipulation
9)       Throw Fewer Exceptions
10)   ValueTypes are far less flexible than Objects  avoid boxing and unboxing
11)   Use generic list
12)   Use proper architecture according to   situation (MVP, MVC, N-tire etc)
13)   Add your own check list

then fill Performance column in the above table

Export Reports into Diffrent File Formate using Crystal Reports Service

March 12, 2008

In this article I am going to explain , how to convert crystal reports to different file format using crystal reports service , The export file format that supported by our Crystal Reports as follows :

1) PDF

2) MS Word

3) MS Excel


5) RTF

please do the following steps :

Creating a class file ExportReports.cs


Please place the following code in that file

public ExportReports()
// TODO: Add constructor logic here

public enum ReportFormats : int
None = 0,
PDF = 1,
MS_Word = 2,
MS_Excel = 3,
HTML = 4,
RTF = 5


public byte[] ExportReportsTo(DataList<T> dt, string fileName,

ReportFormats format)

CrystalDecisions.CrystalReports.Engine.ReportDocument doc = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
//DataSet ds = (DataSet)context.Cache.Get(“ExportData”);
CrystalDecisions.Shared.ExportOptions exportOpts = doc.ExportOptions;
if (format == ReportFormats.PDF)
exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
else if (format == ReportFormats.MS_Word)
exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.WordForWindows;

else if (format == ReportFormats.MS_Excel)
exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.Excel;

else if (format == ReportFormats.HTML)
exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.HTML40;

else if (format == ReportFormats.RTF)
exportOpts.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.RichText;

exportOpts.ExportDestinationType = CrystalDecisions.Shared.

exportOpts.DestinationOptions = new CrystalDecisions.Shared.


// Response.Write(doc.ExportToStream(exportOpts.ExportFormatType));
byte[] _stream = new byte[1024];
MemoryStream _ms = new MemoryStream();

_ms = (MemoryStream)doc.ExportToStream(exportOpts.ExportFormatType);
return _ms.ToArray();


the parameter dt support following format :

1)Data set

2) Data Table

3)Data Reader

4) System.Collection.IEnumerable (in this example we used)

you can change the parameter according to your wish

After creating class file we can you this service in your web page (aspx)

before you should create rpt file (eg: NewSubscriptionReports.rpt)

Create Report

Use IDE to design crystal Report Templates :


Save this rpt file to a web folder then use the following code in the page

protected void btnExport_Click(object sender, EventArgs e)

yournamespace.ExportReports.ReportFormats format;
format = ExportReports.ReportFormats.None;
string strExt = “”;
if (ddlFormat.SelectedValue.Equals(“1”))
format = ExportReports.ReportFormats.PDF;
strExt = “Pdf”;
else if (ddlFormat.SelectedValue.Equals(“2”))
format = ExportReports.ReportFormats.MS_Word;
strExt = “Doc”;
else if (ddlFormat.SelectedValue.Equals(“3”))
strExt = “xls”;
format = ExportReports.ReportFormats.MS_Excel;

else if (ddlFormat.SelectedValue.Equals(“4”))
format = ExportReports.ReportFormats.HTML;
strExt = “HTML”;
else if (ddlFormat.SelectedValue.Equals(“5”))
strExt = “RTF”;
format = ExportReports.ReportFormats.RTF;

ExportReports exportReports = new ExportReports();
// System.IO.MemoryStream _ms = new System.IO.MemoryStream();
HttpContext.Current.Response.ContentType = “application/” + strExt;
HttpContext.Current.Response.AddHeader(“Content-Disposition”, “inline; filename=NewSubscriptionReports.” + strExt);



(SchoolService.ReportType.NewSubscriptionReport, startDate, endDate, allReopts, 0, 0), Server.MapPath(“~/Maintenance/SubscriptionReports

/ReportTemplates/NewSubscriptionReports.rpt”), format));


please specify the .rpt file path in calling function:


Photo Resize Handler in

March 12, 2008

Introduction to ASP.NET HTTP Modules and Handlers

All requests to IIS are handled through Internet Server Application Programming Interface (ISAPI) extensions. ASP.NET has its own filter to ensure pages are processed appropriately. By default, the ASP.NET ISAPI filter (aspnet_isapi.dll) only handles ASPX, ASMX, and all other non-display file formats used by .NET and Visual Studio. However, this filter can be registered with other extensions in order to handle requests to those file types, too, but that will be covered later.

Every request flows through a number of HTTP modules, which cover various areas of the application (i.e. authentication and session intofmation). After passing through each module, the request is assigned to a single HTTP handler, which determines how the system will respond to the request. Upon completion of the request handler, the response flows back through the HTTP modules to the user.

The HTTP Pipeline

To understand the role of HTTP modules within ASP.NET, you need to understand how the HTTP pipeline works. Once an HTTP request comes in over port 80 (the regular HTTP port or port 443 for HTTPS and the secure sockets layer), the request passes through a number of stages making up the HTTP pipeline before it’s actually fielded by your application.

Microsoft® Internet Information Services (IIS) is the first participant in the chain. IIS is still used to route the request to the ASP.NET runtime. IIS maps the ASP.NET file extensions to ASPNET_ISAPI.DLL, an ISAPI extension provided with ASP.NET. The job of ASPNET_ISAPI.DLL is to forward the request to the ASP.NET worker process, ASPNET_WP.EXE. From that point on, the request is wrapped up into an instance of HttpContext and piped through a number of ASP.NET classes. The HttpContext class includes members representing such things as the Response and the Request and also includes security information along with anything else you might want to know about the request.

The next step for the request is to pass through an instance of HttpApplication.After the HttpApplication object massages the request, it pushes the request through one or more HttpModule objects. There are a number of system-level HTTP modules.The final piece of the chain is the HttpHandler

HTTP Module

In order to insure that your HttpHandler is hooked up to the HTTP pipeline requires an entry in the application’s web config. or the machine.config file. The same holds true for HTTP modules. When an HTTP Module is added to the pipeline, the ASP.NET runtime will call the methods of the IHttpModule interface at the appropriate times. When the module is first created by the runtime, the Init method is called. As illustrated above, the parameter passed into the Init method allows your code to tie into the HttpApplication object.

The following table lists the key events exposed by the HttpApplication object. Note that all these events are implemented as multicast delegates so that numerous modules can register for each one.

When It’s Called

Before request processing starts

To authenticate client

To perform access check

To get response from cache

To load session state

Before request sent to handler

After request sent to handler

To store session state

To update response cache

After processing ends

Before buffered response headers sent

Before buffered response body sent

In addition to the above methods, we can also respond to the methods in the global.asax file for the HttpApplication object. These events include the session start and end events, as well as the start and end events for the application.

HTTP Handlers

HTTP handlers are the .NET components that implement the System.Web.IHttpHandler interface. Any class that implements the IHttpHandler interface can act as a target for the incoming HTTP requests. HTTP handlers are somewhat similar to ISAPI extensions. One difference between HTTP handlers and ISAPI extensions is that HTTP handlers can be called directly by using their file name in the URL, similar to ISAPI extensions.

HTTP modules are classes that have access to the incoming request. These modules can inspect the incoming request and make decisions that affect the internal flow of the request. After passing through the specified HTTP modules, the request reaches an HTTP handler, whose job it is to generate the output that will be sent back to the requesting browser. The following diagram illustrates the pipeline an ASP.NET request flows through.

Photo Resize Handler

In this article we’ll create a HTTP Handler in ASP.NET to resize an image as per parameters that user passes.

Creating the Handler

please go and find topic from that site

please use following code to PhotoResizeHandler.ashx.cs ( Append)

define a method for resize image in same file :

private static byte[] ResizeImageFile(byte[] imageFile, int height, int width)
using (Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
int newwidth = 0;
int newheight = 0;
float oldwidth = oldImage.Width;
float oldheight = oldImage.Height;
float imgratio = oldwidth / oldheight;
if (imgratio > 1)
newwidth = width;
newheight = Convert.ToInt32 ( height / imgratio);
newheight = height;
newwidth = Convert.ToInt32(width * imgratio);
Size newSize = new Size(newwidth, newheight);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
using (Graphics canvas = Graphics.FromImage(newImage))
//canvas.SmoothingMode = SmoothingMode.AntiAlias;
//canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
//canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
MemoryStream m = new MemoryStream();
newImage.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
return m.GetBuffer();

Invoking Handler from aspx page

You would invoke the handler from aspx page just like you call any other aspx page.
Following Image control invokes the handler:

<asp:Image ID=”Image1″ ImageUrl=”~/PhotoResizeHandler.ashx?imageFile=images/Leaves.jpg&height=200&width=200″
runat=”server” />

or like this :

ImageButton lnkPhotoThumb = ( (ImageButton)( e.Item.FindControl( “PhotoThumb” ) ) );

lnkPhotoThumb.ImageUrl = Page.ResolveUrl( “~/Handlers/PhotoResizeHandler.ashx?imageFile=” + Page.ResolveUrl( “~/UploadedFiles/Resources/”)Leaves.jpg + “&height=120&width=120” );


Also , a big thanks to Shelly (my colleague) who provide me the logic of maintaining the aspect ratio of images 🙂