ASP.Net State Server

Introduction

In the world of web applications Sessions are commonly used to keep key information about users. Before going into the details of State Server lets have a quick look over different session management solutions provided by ASP.Net. Here are the different modes for storing session in ASP.net:-

InProc
This is the default mode. In this session data is stored in web server's (IIS) memory space. In case IIS is restarted all sessions data will be loss when this mode is configured.

StateServer
This is the out of the process way of storing session. In this mode session data is stored in a separate process (ASP.Net State Service). Incase IIS is restated then session data will not be effected when this mode is configured.

SQLServer
In this mode session's data is stored in SQL server. Incase IIS or SQL Server is restarted session will not loss. But is slower than State Server.

Custom
In this mode we can specify any custom provider.

Off
In this mode sessions are disabled.

Now if your application is hosted on a web farm/garden then users will claim that their sessions is getting loss too frequently. Consider a scenario when there are two servers hosting an application. Now if one request goes to server 'A', its session will be created on that particular server and in case other request from same user goes to server 'B' then on that server session will not exist so user have to log in again. Also if you are using Inproc mode and your IIS is restarted due to recycling or application deployment then all of your session will lost. In such scenarios we can configure seperate state server to avoid such problems.

How to configure State Server in ASP.Net

There are three steps to configure state server:-
  1. State Server Service Configuration
  2. Session State Section Configuration
  3. Machine Key Configuration

1- State Server Service Configuration
First go to Windows Control Panel -> Administrative Tools and Open Services. Now search for 'ASP.NET State Service'. Now set service start-up type to Automatic. Generally we configure a separate server as a state server but by default it is disabled. To enable saving state for remote machines, we have to configure some registry settings. So open registry editor and navigate to following location:-

HKLM\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\

Now you have to set two parameters here:-
AllowRemoteConnections: It will allow other computers to use this computer as state server. Set it to 1. Default value is 0.
Port: Specify the port on which state service will run. By Default it is 42424. Keep it same unless you have some specific reason.

2- Session State Section Configuration
After that you have to modify your application's web.config file and set Here is a sample:-
<?xml version="1.0"?>
<configuration>
    <system.web>
        <sessionState mode="StateServer" stateConnectionString="tcpip=Type_State_Server_IP_Here:42424"
                                    cookieless="false" timeout="20" />
    </system.web>
</configuration>

3- Machine Key Configuration
Now we are almost done with state server configuration. One last thing is to set machineKey in our application's web.config. Here is a sample web.config file with machine key.
<?xml version="1.0"?>
<configuration>
    <system.web>
        <machineKey validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"    decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F" validation="SHA1" decryption="AES"/>
    </system.web>
</configuration>

You can generate a machine key from Pete's Nifty Machine Key Generator

Advantage and Disadvantage of State Server
Here are few things which you should keep in mind before going for state server:-

Advantages
  • Since session data is stored in a separate location so any issue with IIS will not affect sessions.
  • User will not face session loss in case of web farm or web garden.
Disadvantages
  • This approach is slower than InProc because of object serialization/de-serialization.
  • State server must be running otherwise application will not work.
  • In InProc mode any object can be stored in session but in state server case objects should be serializable.

Conclusion
State Server is a must have when you are using session and working web farm or web garden. Feel free to post comments.

Creating advanced Excel 2007 Reports on Server

Recently I was looking for an Advance tool through which I can generate complex Excel Reports. And after going through many tools I found EP Plus. For further details see this link. Through this tool we can easily create reports with charts, graphs and other drawing objects. I have planned to shared few samples with the community, so if any one is interested in using this library he will get a good kick start.

In this sample application I have tried to explain that how you can generate a report using DataTable. I also demonstrated how to use different formatting options and formulas.

So, here is the code:-

/// <summary>
/// Creates the data table.
/// </summary>
/// <returns>DataTable</returns>
private static DataTable CreateDataTable()
{
    DataTable dt = new DataTable();
    for (int i = 0; i < 10; i++)
    {
        dt.Columns.Add(i.ToString());
    }
 
    for (int i = 0; i < 10; i++)
    {
        DataRow dr = dt.NewRow();
        foreach (DataColumn dc in dt.Columns)
        {
            dr[dc.ToString()] = i;
        }
 
        dt.Rows.Add(dr);
    }
    return dt;
}
 
private void button1_Click(object sender, EventArgs e)
{
    using (ExcelPackage p = new ExcelPackage())
    {
        //Here setting some document properties
        p.Workbook.Properties.Author = "Zeeshan Umar";
        p.Workbook.Properties.Title = "Office Open XML Sample";
 
        //Create a sheet
        p.Workbook.Worksheets.Add("Sample WorkSheet");
        ExcelWorksheet ws = p.Workbook.Worksheets[1];
        ws.Name = "Sample Worksheet"; //Setting Sheet's name
        ws.Cells.Style.Font.Size= 11; //Default font size for whole sheet
        ws.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet
 
 
        DataTable dt = CreateDataTable(); //My Function which generates DataTable
 
        //Merging cells and create a center heading for out table
        ws.Cells[1, 1].Value = "Sample DataTable Export";
        ws.Cells[1, 1, 1, dt.Columns.Count].Merge = true;
        ws.Cells[1, 1, 1, dt.Columns.Count].Style.Font.Bold = true;
        ws.Cells[1, 1, 1, dt.Columns.Count].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
 
        int colIndex = 1;
        int rowIndex = 2;
 
        foreach (DataColumn dc in dt.Columns) //Creating Headings
        {
            var cell = ws.Cells[rowIndex, colIndex];
 
            //Setting the background color of header cells to Gray
            var fill = cell.Style.Fill;
            fill.PatternType = ExcelFillStyle.Solid;
            fill.BackgroundColor.SetColor(Color.Gray);
 
 
            //Setting Top/left,right/bottom borders.
            var border = cell.Style.Border;
            border.Bottom.Style = 
                border.Top.Style = 
                border.Left.Style = 
                border.Right.Style = ExcelBorderStyle.Thin;
 
            //Setting Value in cell
            cell.Value = "Heading " + dc.ColumnName;
 
            colIndex++;
        }
 
        foreach (DataRow dr in dt.Rows) // Adding Data into rows
        {
            colIndex = 1;
            rowIndex++;
            foreach (DataColumn dc in dt.Columns)
            {
                var cell = ws.Cells[rowIndex, colIndex];
                //Setting Value in cell
                cell.Value = Convert.ToInt32(dr[dc.ColumnName]);
 
                //Setting borders of cell
                var border = cell.Style.Border;
                border.Left.Style =
                    border.Right.Style = ExcelBorderStyle.Thin;
                colIndex++;
            }
        }
 
        colIndex = 0;
        foreach (DataColumn dc in dt.Columns) //Creating Headings
        {
            colIndex++;
            var cell = ws.Cells[rowIndex, colIndex];
 
            //Setting Sum Formula
            cell.Formula = "Sum("+ 
                            ws.Cells[3, colIndex].Address+
                            ":"+
                            ws.Cells[rowIndex-1, colIndex].Address+
                            ")";
 
            //Setting Background fill color to Gray
            cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
            cell.Style.Fill.BackgroundColor.SetColor(Color.Gray);
        }
 
        //Generate A File with Random name
        Byte[] bin = p.GetAsByteArray();
        string file = "d:\\" + Guid.NewGuid().ToString() + ".xlsx";
        File.WriteAllBytes(file, bin);
    }
}

Here is the snapshot of Excel File which is created through above code:-

Hopefully this will be useful for you, keep posting your comments.For further details and download see EP Plus home page.

Export to Excel in .Net

There is a wonderful open source Excel Library through which you can easily convert DataSet into multi sheet excel file, just by one line of code like this:-

ExcelXmlWorkbook sheet = ExcelXmlWorkbook.DataSetToWorkbook(sourceDataSet);

Also adding a sample code which will really help you to create reports:-

 
private void YougeshSample()
{
    DataTable dt = CreateDataTable();
 
    ExcelXmlWorkbook book = new ExcelXmlWorkbook();
    book.Properties.Author = "Zeeshan Umar";
    book.Properties.Company = "Sample Company";
    book.Properties.Title = "Sample Title";
    book.Properties.Subject = "Subject";
 
    Worksheet ws = book[0];
    ws.Name = "Sample Sheet Name"; //Sheet Name
    ws.Font.Name = "Calibri";//Setting font for all sheet
    ws.Font.Size = 11;
 
    int rowIndex = 0;
    Row row;
    row = ws[rowIndex++];
 
    int colIndex = 0;
    foreach (DataColumn dc in dt.Columns) //Creating Headings
    {
        row[colIndex].Value = "Heading " + dc.ColumnName;
        row[colIndex].Border.Sides = BorderSides.All;
        row[colIndex].Style.Interior.Color = Color.LightGray;
        colIndex++;
    }
 
    foreach (DataRow dr in dt.Rows) // Adding Data into rows
    {
        colIndex = 0;
        row = ws[rowIndex++];
        foreach (DataColumn dc in dt.Columns)
        {
            row[colIndex].Value = Convert.ToInt32(dr[dc.ColumnName]);
            row[colIndex].Border.Sides = BorderSides.Left | BorderSides.Right;
            setIntegerFormat(row[colIndex]);
            colIndex++;
        }
    }
 
    row = ws[rowIndex++];
    colIndex = 0;
    foreach (DataColumn dc in dt.Columns) //Adding summ formula for last row
    {
        row[colIndex].Value = FormulaHelper.Formula("sum", 
            new Range(ws[colIndex, 1], ws[colIndex, 9]));
        row[colIndex].Border.Sides = BorderSides.All;
        row[colIndex].Style.Interior.Color = Color.LightGray;
        colIndex++;
    }
 
    string s = "c:\\" + Guid.NewGuid().ToString() + ".xml";
    book.Export(s);
}
 
private static DataTable CreateDataTable()
{
    DataTable dt = new DataTable();
    for (int i = 0; i < 300; i++)
    {
        dt.Columns.Add(i.ToString());
    }
    for (int i = 0; i < 10; i++)
    {
        DataRow dr = dt.NewRow();
        foreach (DataColumn dc in dt.Columns)
        {
 
            dr[dc.ToString()] = i;
        }
        dt.Rows.Add(dr);
    }
    return dt;
}
 
private void setIntegerFormat(Cell cell)
{
    cell.DisplayFormat = DisplayFormatType.Custom;
    cell.CustomFormatString = "#,##0";
}
 
private void setDateFormat(Cell cell)
{
    cell.DisplayFormat = DisplayFormatType.GeneralDate;
    cell.CustomFormatString = "dd\\-mmm\\-yyyy\\ hh:mm";
}

For further details see this link:-
A Very Easy to Use Excel XML Import-Export Library

To download latest version of library see this link:-
Excel Xml Library 2.45 released

How do disable back button in browser

Generally there are cases when we want to disable back button in browser. We have multiple options to disable back button in browser. Here are the few:-

Java Script Way
We can use following java script to prevent back button:-
<script type = "text/javascript" >
function disableBackButton()
{ 
window.history.forward();
}
setTimeout("disableBackButton()", 0);
window.onunload=function()
{
null
};
</script>

HTML Way
We can also add Meta Tags in Head Section like this:-
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />

If you want to do above approach through code. Here is the trick:-

HtmlMeta pragma = new HtmlMeta();

pragma.HttpEquiv = "Pragma";

pragma.Content = "no-cache";

Page.Header.Controls.Add(pragma);

 

HtmlMeta expires = new HtmlMeta();

expires.HttpEquiv = "Expires";

expires.Content = "-1";

Page.Header.Controls.Add(expires);


ASP.Net Way
In ASP.Net we can use Cache to disable back button like this:-

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));

Response.Cache.SetNoStore();

Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

A potentially dangerous Request.Form value was detected from the client


Above error comes because by default ASP.Net blocks the possible Script Injection request. e.g. if user type <script>alert('yes');</script> in your text box and when you display the text in text box, this java script will be executed instead of displaying text.

To resolve this problem you need to keep few things in mind:-

1- We can remove HTML Tags from TextBoxes with a simple regular expression filter like this:-
<asp:textbox id="txtSecureTextBox" runat="server" onblur="this.value = this.value.replace(/&lt;\/?[^>]+>/gi, '');">

2- Add ValidateRequest="false" in your Page directive line incase you want to disable this on single page.
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false"/>

3- Incase you want to disable validation through out the site then you can do it in your web.config file like this:-
<configuration>  
  <system.web>  
    <pages validateRequest="false" />  
  </system.web> 
</configuration>

4- Use HTMLEncode whenever you are displaying unsafe contents in labels like this:-
Label1.Text = Server.HtmlEncode(TextBox1.Text) 

For further details see Request Validation - Preventing Script Attacks.