Thursday, December 30, 2010

How to Print in ASP.NET 2.0

One of the most common functionality in any ASP.NET application is to print forms and controls.
There are a lot of options to print forms using client scripts. In the article, we will see how
to print controls in ASP.NET 2.0 using both server side code and javascript.
Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that
can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to
window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy
to add a reference in case someone knows.
 
C# 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;
public class PrintHelper
{
    public PrintHelper()
    {
    }
    public static void PrintWebControl(Control ctrl)
    {
        PrintWebControl(ctrl, string.Empty);
    }
    public static void PrintWebControl(Control ctrl, string Script)
    {
        StringWriter stringWrite = new StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite =
               
new System.Web.UI.HtmlTextWriter(stringWrite);
        if (ctrl is WebControl)
        {
            Unit w = new Unit(100, UnitType.Percentage);
            ((WebControl)ctrl).Width = w;
        }
        Page pg = new Page();
        pg.EnableEventValidation = false;
        if (Script != string.Empty)
        {
            pg.ClientScript.RegisterStartupScript(pg.GetType(),
                                         "PrintJavaScript", Script);
        }
        HtmlForm frm = new HtmlForm();
        pg.Controls.Add(frm);
        frm.Attributes.Add("runat", "server");
        frm.Controls.Add(ctrl);
        pg.DesignerInitialize();
        pg.RenderControl(htmlWrite);
        string strHTML = stringWrite.ToString();
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write(strHTML);
        HttpContext.Current.Response.Write("<script>window.
                                             print();</script>"
);
        HttpContext.Current.Response.End();
    }
}
VB.NET
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Text
Imports System.Web.SessionState
Public Class PrintHelper
    Public Sub New()
    End Sub
    Public Shared Sub PrintWebControl(ByVal ctrl As Control)
        PrintWebControl(ctrl, String.Empty)
    End Sub
    Public Shared Sub PrintWebControl(ByVal ctrl As Control,
                                          
ByVal Script As String)
        Dim stringWrite As StringWriter = New StringWriter()
        Dim htmlWrite As System.Web.UI.HtmlTextWriter =
                   
New System.Web.UI.HtmlTextWriter(stringWrite)
        If TypeOf ctrl Is WebControl Then
            Dim w As Unit = New Unit(100, UnitType.Percentage)
            CType(ctrl, WebControl).Width = w
        End If
        Dim pg As Page = New Page()
        pg.EnableEventValidation = False
        If Script <> String.Empty Then
            pg.ClientScript.RegisterStartupScript(pg.GetType(),
           
"PrintJavaScript", Script)
        End If
        Dim frm As HtmlForm = New HtmlForm()
        pg.Controls.Add(frm)
        frm.Attributes.Add("runat", "server")
        frm.Controls.Add(ctrl)
        pg.DesignerInitialize()
        pg.RenderControl(htmlWrite)
        Dim strHTML As String = stringWrite.ToString()
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.Write(strHTML)
        HttpContext.Current.Response.Write("<script>window.print();
                                                        </script>"
)
        HttpContext.Current.Response.End()
    End Sub
End Class
Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will
contain the controls to be printed. Print.aspx will act as a popup page to
invoke the print functionality.
Step 3: In your Default.aspx, drag and drop a few controls that you
would like to print. To print a group of controls, place them all in a
container control like a panel. This way if we print the panel using our
PrintHelper class, all the controls inside the panel gets printed.
Step 4: Add a print button to the Default.aspx and in the code behind,
type the following code:
C#
protected void btnPrint_Click(object sender, EventArgs e)
    {
        Session["ctrl"] = Panel1;
        ClientScript.RegisterStartupScript(this.GetType(),
       
"onclick", "<script language=javascript>window.open
                  ('Print.aspx','PrintMe','height=300px,width=300px,
                         scrollbars=1');/script>"
);
    }                
VB.NET
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As
                               System.EventArgs) Handles btnPrint.Click
        Session("ctrl") = Panel1
        ClientScript.RegisterStartupScript(Me.GetType(), "onclick",
       
"<script language=javascript>window.open    ('Print.aspx',
                              'PrintMe','height=300px,width=300px,
                                             scrollbars=1');</script>"
)
End Sub
The code stores the control in a Session variable to be accessed in the pop up page,
Print.aspx. If you want to print directly on button click, call the Print functionality in
the following manner :
PrintHelper.PrintWebControl(Panel1);
Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
C#
protected void Page_Load(object sender, EventArgs e)
    {
        Control ctrl = (Control)Session["ctrl"];
        PrintHelper.PrintWebControl(ctrl);
    }
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
                                                            
Handles Me.Load
        Dim ctrl As Control = CType(Session("ctrl"), Control)
        PrintHelper.PrintWebControl(ctrl)
End Sub
Well that's it. Try out the sample attached with this article and print any control you desire.

Send Email in ASP.Net 2.0 - Feed back Form

 
















Introduction
We are using System.Web.Mail.SmtpMail to send email in dotnet 1.1 which is obsolete in 2.0.
The
System.Net.Mail.SmtpClient Class will provide us the same feature as that of its
predecessor.
This article explains how to use System.Net.Mail namespace to send emails.
Using the code
The HTML Design contains provision to enter sender�s name, email id and his comments. On click
of the send email button the details will be sent to the specified email (Admin).
The Send mail functionality is similar to Dotnet 1.1 except for few changes
  1. System.Net.Mail.SmtpClient is used instead of System.Web.Mail.SmtpMail
    (obsolete in Dotnet 2.0).

  2. System.Net.MailMessage Class is used instead of System.Web.Mail.MailMessage
    (obsolete in Dotnet 2.0)

  3. The System.Net.MailMessage class collects From address as MailAddress object.
  4. The System.Net.MailMessage class collects To, CC, Bcc addresses as MailAddressCollection.
  5. MailMessage Body Format is replaced by IsBodyHtml
The Code is Self explanatory by itself.
protected void btnSendmail_Click(object sender, EventArgs e)
      {
        // System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
        // System.Net.Mail.SmtpClient is the alternate class for this in 2.0
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();

        try
        {
            MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);

            // You can specify the host name or ipaddress of your server
            // Default in IIS will be localhost
            smtpClient.Host = "localhost";

            //Default port will be 25
            smtpClient.Port = 25;

            //From address will be given as a MailAddress Object
            message.From = fromAddress;

            // To address collection of MailAddress
            message.To.Add("admin1@yoursite.com");
            message.Subject = "Feedback";

            // CC and BCC optional
            // MailAddressCollection class is used to send the email to various users
            // You can specify Address as new MailAddress("admin1@yoursite.com")
            message.CC.Add("admin1@yoursite.com");
            message.CC.Add("admin2@yoursite.com");

            // You can specify Address directly as string
            message.Bcc.Add(new MailAddress("admin3@yoursite.com"));
            message.Bcc.Add(new MailAddress("admin4@yoursite.com"));

            //Body can be Html or text format
            //Specify true if it  is html message
            message.IsBodyHtml = false;

            // Message body content
            message.Body = txtMessage.Text;
        
            // Send SMTP mail
            smtpClient.Send(message);

            lblStatus.Text = "Email successfully sent.";
        }
        catch (Exception ex)
        {
            lblStatus.Text = "Send Email Failed." + ex.Message;
        }
      }

How to drop all tables from a SQL Server 2005 Database

How to drop all tables, all views, and all stored procedures
from a SQL Server 2005 Database?
It may not be a hardcore requirement on day-to-day basis to drop all tables, views and stored
procedures from a SQL Server database within your environment, but it will be handy to have
such a code at your end when such task is required.
There are 2 ways to accomplish this, first using undocumented stored procedure such as
'sp_MSforeachtable' as follows:
exec sp_MSforeachtable "DROP TABLE ? PRINT '? to be dropped' "
Where the results will have all of the tables to be dropped, ok how about
for views & stored procedure then. Here it goes:
create procedure Usp_DropAllSPViews
as
declare @name  varchar(100)
declare @xtype char(1)
declare @sqlstring nvarchar(1000)
declare AllSPViews_cursor cursor for
SELECT sysobjects.name, sysobjects.xtype
FROM sysobjects
  join sysusers on sysobjects.uid = sysusers.uid
where OBJECTPROPERTY(sysobjects.id, N'IsProcedure') = 1
  or OBJECTPROPERTY(sysobjects.id, N'IsView') = 1 and
sysusers.name ='USERNAME'
open AllSPViews_cursor
fetch next from SPViews_cursor into @name, @xtype
while @@fetch_status = 0
  begin
-- obtain object type if it is a stored procedure or view
   if @xtype = 'P'
      begin
        set @sqlstring = 'drop procedure ' + @name
        exec sp_executesql @sqlstring
        set @sqlstring = ' '
      end
-- obtain object type if it is a view or stored procedure
   if @xtype = 'V'
      begin
         set @sqlstring = 'drop view ' + @name
         exec sp_executesql @sqlstring
         set @sqlstring = ' '
      end
    fetch next from AllSPViews_cursor into @name, @xtype
  end
close AllSPViews_cursor
deallocate AllSPViews_cursor

Always test above script within your test or sample database and be satisfied with results to check,
do not directly attempt on a live database that I will not give you any warranty or guarantee on
above task. Do not forget to have a

How to install Turbo C++ on Windows 7 64bit


Few days ago we have posted an article about installing Turbo C++ on 32 bit Windows 7.
Now we are providing step-by-step procedure how to install Turbo C++ on 64 bit Windows 7.
1. Install the software DOSBox ver 0.73 : download here
2. Create a folder,for example „Turbo" (c:\Turbo\)
3. Download and extract TC into the Turbo folder (c:\Turbo\): download here
4. Run the DOSBox 0.73 from the icon located on the desktop:

5. Type the following commands at the command prompt [Z]: mount d c:\Turbo\ [The folder TC is
present inside the folder Turbo]
Now you should get a message which says: Drive D is mounted as a local directory c:\Turbo\

6. Type d: to shift to d:

7. Next follow the commands below:
cd tc
cd bin
tc or tc.exe [This starts you the Turbo C++ 3.0]

8. In the Turbo C++ goto Options>Directories> Change the source of TC to the source directory
[D] ( i.e. virtual D: refers to original c:\Turbo\ . So make the path change to something like
D:\TC\include and D:\TC\lib respectively )

How to start TurboC++ in the DOSBox automatically:
You can save yourself some time by having DOSBox automatically mount your folders and start
Turbo C++:
For DOSBox versions older then 0.73 browse into program installation folder and open the dosbox
.conf file in any text editor. For version 0.73 go to Start Menu and click on "Configuration" and
then "Edit Configuration". Then scroll down to the very end, and add the lines which you want to
automatically execute when DOSBox starts.
Automatically mount and start Turbo C++3.0 in DOSBox ver 0.73:
Scroll down to the very end, and add the lines:
Those commands will be executed automatically when DOSBox starts!
Please note:
Full screen: Alt and Enter
When you exit from the DosBox [precisely when u unmount the virtual drive where Turbo C++ 3.0
has been mounted] all the files you have saved or made changes in Turbo C++ 3.0 will be copied
into the source directory(The directory which contains TC folder)
Don't use shortcut keys to perform operations in TC because they might be a shortcut key for
DOSBOX also . Eg : Ctrl+F9 will exit DOSBOX rather running the code .

Wednesday, December 29, 2010

How change ASP linkbutton control color at client side on Mouse over

Use <div> to with linkbutton to change color. it will not
work if you do not use div or another container control.
use cssclass property except the id of the controls.
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css" rel="stylesheet">
.customhover a
{
background-color: Purple;
}
.customhover a:hover
{
background-color: Yellow;
}
</style>
</head>
<body>
<form id="Form1" runat="server">
<div>
<div class="customhover">
<asp:LinkButton ID="LinkButton1" runat="server"
CssClass="customhover">Click Here</asp:LinkButton>
</div>
</div>
</form>
</body>
</html>

How to check the control type at run time




using System;
using System.Drawing;
using System.Windows.Forms;
  
class CustomCheckBox: Form
{
     public static void Main()
     {
          Application.Run(new CustomCheckBox());
     }
     public CustomCheckBox()
     {
          int      cyText = Font.Height;
          int      cxText = cyText / 2;
          FontStyle[] afs =
                      { FontStyle.Bold,      FontStyle.Italic,
                        FontStyle.Underline, FontStyle.Strikeout };
  
          Label label    = new Label();
          label.Parent   = this;
          label.Text     = "Sample Text";
  
          for (int i = 0; i < 4; i++)
          {
               FontStyleCheckBox chkbox = new FontStyleCheckBox();
               chkbox.Parent = this;
               chkbox.Text = afs[i].ToString();
               chkbox.fontstyle = afs[i];
               chkbox.Location = new Point(2
                         * cxText,     (4 + 3 * i) * cyText / 2);
               chkbox.Size = new Size(12 * cxText, cyText);
               chkbox.CheckedChanged
               += new EventHandler(CheckBoxOnCheckedChanged);
          }
     }
     void CheckBoxOnCheckedChanged(object obj, EventArgs ea)
     {
          FontStyle fs = 0;
          Label     label = null;
  
          for (int i = 0; i < Controls.Count; i++)
          {
               Control ctrl = Controls[i];
  
               if (ctrl.GetType() == typeof(Label))
                    label = (Label) ctrl;
               else if (ctrl.GetType() == typeof(FontStyleCheckBox))
                    if (((FontStyleCheckBox) ctrl).Checked)
                         fs |= ((FontStyleCheckBox) ctrl).fontstyle;
          }
          label.Font = new Font(label.Font, fs);
     }
}
class FontStyleCheckBox: CheckBox
{
     public FontStyle fontstyle;
}

Monday, December 27, 2010

How to enable the 64bit compatibility on IIS6 and IIS7?

Sometimes, you will get the following error after deploying your web application (developed for 64 bit
environment and if you referred to any GAC DLL in your application) on IIS 6 or IIS7.

Could not find the path of
C:\Windows\assembly\GAC_MSIL_<Dll Name>_<GAC ID>\Bin

This error occurs because of your IIS currently not supporting 64bit applications, so you need to enable
the 64bit
compatibility on IIS and you can resolve this by using the following steps on different IIS
versions based your
requirements.

For IIS6:
Step 1:  Click Start, click Run, type cmd, and then click OK.
Step 2: Type the following command to disable the 32-bit mode:

cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs
SET W3SVC/AppPools/Enable32bitAppOnWin64 0

Step 3: Type the following command to install the version of
ASP.NET 2.0 and to install the script maps at the IIS
root and under:

%SYSTEMROOT%\Microsoft.NET\Framework64\v2.0.50727
\aspnet_regiis.exe -i

Step 4: Make sure that the status of ASP.NET version 2.0.50727
        is set to Allowed in the Web service extension list in
Internet Information Services Manager(if your
application deployed on windows 2003 or 2008).
For IIS7:
Step 1:  Open the Internet Information Service Manager  
from Start Menu or Control Panel --> Administrative
Tools.
Step 2: Expand the Application Pools Node then find your Website
Application Pool then right click on it then click on
Advanced Settings, it will popup the settings screen
here you need to set false for Enable32bitApplication.
This settings may affect your existing 32bit application,
if you get any error on your 32 applications then you
reset the above setting and create a new application pool
just like existing on and use itfor 64bit with
appropriate Enable32bitApplication setting(value must
be false).

Saturday, December 25, 2010

Guarding Against Session Hijacking in ASP.NET

In this tutorial we're going to be looking at something all .Net developers need to be aware of and guard against, and that is prevent session hijacking. Session hijacking is a form of hacking attack that involves accessing a users session state. While the damage can be as small as having access to someone's shopping cart data, or as severe as hijacking a session that contains a users personal, or financial, information. This kind of attack is generally carried out in two forms:
•ID Guessing
•Solen ID's
Session ID guessing is harder for an ASP.NET website because ASP.NET employs a random 120-bit number, but stealing a session ID is more prevalent. There are three main ways hackers steal session ID's:
•Cross-Site Scripting (XSS)
•Main-In-The-Middle Attack
•Gain access to the users cookie
The main reason stealing session ID's from an ASP.NET application takes such little skill from the hacker is because ASP.NET doesn't encode any information in the session cookie other than the ID itself. If the server receives a Request with a valid ID it accepts the Request, no questions asked. Though it is impossible to create a fool-proof defense against such attacks, the developer can take certain steps to make them harder to pull off, and that is what this tutorial looks at.
In this tutorial we will look at intercepting the session cookie (before ASP.NET sees it), taking the MAC (Message Authentication Code), and creating our own MAC, based on the session ID, the users IP address and their User Agent. Our class will also rely on a validation key that is stored in the web.config file. The key will be based on a MD5 hash of a string, and should be different for all applications this is used for. Make sure your key is long and random, shorter keys are easier to guess. We will also be creating a custom Exception that will be used in the class.
Before we start, here's a short method you can use to create the MD5 hash for your validation key. It employs the MD5CryptoServiceProvider Class in the System.Security.Cryptography Namespace:
view sourceprint?
01 /// <summary> 
02 /// method to generate a MD5 hash of a string 
03 /// </summary> 
04 /// <param name="strToHash">string to hash</param> 
05 /// <returns>hashed string</returns> 
06 public string GenerateMD5(string str) 
07 { 
08     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); 
09   
10     byte[] byteArray = Encoding.ASCII.GetBytes(str); 
11   
12     byteArray = md5.ComputeHash(byteArray); 
13   
14     string hashedValue = ""; 
15   
16     foreach (byte b in byteArray) 
17     { 
18         hashedValue += b.ToString("x2"); 
19     } 
20   
21     return hashedValue; 
22 }
Now that we have the creation of the key covered, lets start making our secure session class. First and foremost, as with all classes you write, you need to make sure you have the proper Namespace's for your class, in this case we need seven of them:
view sourceprint?
1 using System; 
2 using System.Web; 
3 using System.Text; 
4 using System.Web.Security; 
5 using System.Configuration; 
6 using System.Security.Cryptography; 
7 using System.Globalization;
Now we need any global variables, in this case we have a single global, the variable that will hold the value of
our key
view sourceprint?
1 private static string secretKey = null;
This class is designed to operate completely silent, meaning it works in the background with zero interaction
from the developer whatsoever. Our class inherits the IHttpModule Interface.
First thing we will do is call the Init() and Dispose() Methods of the IHttpModule. In the Init() Method we will
first check the value of our global variable secretKey, if it doesn't have a value we will initialize it.
We then wire up two Event Handlers, these will handle the BeginRequest Event and the EndRequest Event of
the HttpApplication Class. The Dispose() method is a blank method, but it is required when inheriting from the
IHttpModule Interface.
view sourceprint?
01 /// <summary> 
02 /// method to initialize our class when the page is initialized 
03 /// </summary> 
04 /// <param name="application"></param> 
05 public void Init(HttpApplication application) 
06 { 
07     //find out of we have a validation key, if we dont initialize it 
08     if (secretKey == null) secretKey = GetKey(); 
09   
10     //register event handlers for the BeginRequest and EndRequest events 
11     application.BeginRequest += new EventHandler(onbeginRequest); 
12     application.EndRequest += new EventHandler(onendRequest); 
13 } 
14   
15 public void Dispose()  
16 {  
17 }
Now the Event Handler, we have two to write up:
•onbeginRequest: Handles all transactions at the start of the request cycle
•onendRequest: Handles all transactions at the very end of the request cycle
onbeginRequest is where we do the bulk of our work. The first thing we do is grab the current Request, this
allows us access to all the information we need, including the current ASP.NET_SessionID cookie. Once we
have the cookie in our possession we first check it's length, if it's less than 24 long we throw an exception
because that tells us the cookie doesn't have a MAC attached. If we make it past that check we then grad
the session ID and the MAC value off of the cookie (using string manipulation), then compare the MAC value
with our generated MAC. If they don't match we throw an exception because something's happened to the
cookie. Barring any errors we quickly assign the session ID to the value of the cookie, all before ASP.NET
see's it.
onbeginRequest:
view sourceprint?
01 /// <summary> 
02 /// method for handling the HttpApplication.BeginRequest event 
03 /// </summary> 
04 /// <param name="sender"></param> 
05 /// <param name="e"></param> 
06 public void onbeginRequest(Object sender, EventArgs e) 
07 { 
08     //get the current Request 
09     HttpRequest currentRequest = ((HttpApplication)sender).Request; 
10   
11     //get the ASP.NET_SessionId cookie from the Request object 
12     HttpCookie requestCookie = RetrieveRequestCookie(currentRequest, "ASP.NET_SessionId"); 
13   
14     //check to see if the cookie exists (if == null) 
15     if (requestCookie != null) 
16     { 
17         //if the length is less than 24 we dont have a MAC so we need to throw an exception
            (our custom exception) 
18         if (requestCookie.Value.Length <= 24) throw new SessionerrorException("Invalid Session"); 
19   
20         //get the session id
21         string sessionID = requestCookie.Value.Substring(0, 24); 
22   
23         //get the MAC 
24         string mac = requestCookie.Value.Substring(24); 
25   
26         //create a new MAC based on the session id and some of the users info (user agent, etc) 
27         string macCompare = CreateMAC(sessionID, currentRequest.UserHostAddress,
                                                                                              currentRequest.UserAgent, secretKey); 
28   
29         //check to see if the MAC's match, if not we have a problem 
30         if (String.CompareOrdinal(mac, macCompare) != 0)
                                           throw new SessionerrorException("Invalid Session"); 
31   
32         //set the cookies value to the session id
33         requestCookie.Value = sessionID; 
34     } 
35 }
In the onendRequest we grab the response cookie and make sure it isn't null (that would mean someone
has hijacked the session), if all is OK we append our newly created MAC value to the end of the cookie,
and this can be compared during the next BeginRequest Event, which will be the next page load for the
application.
onendRequest:
view sourceprint?
01 /// <summary> 
02 /// method for handling the HttpApplication.EndRequest event 
03 /// </summary> 
04 /// <param name="sender"></param> 
05 /// <param name="e"></param> 
06 public void onendRequest(Object sender, EventArgs e) 
07 { 
08     //capture the current request 
09     HttpRequest currentRequest = ((HttpApplication)sender).Request; 
10   
11     //get the session cookie 
12     HttpCookie sessionCookie = RetrieveResponseCookie(((HttpApplication)sender).Response,
                                                                                                                                   "ASP.NET_SessionId"); 
13   
14     //make sure the cookie isnt null 
15     if (sessionCookie != null) 
16     { 
17         //add our newly generated MAC to the cookie at the end of the request 
18         sessionCookie.Value += CreateMAC(sessionCookie.Value, currentRequest.UserHostAddress,
                                                            currentRequest.UserAgent, secretKey); 
19     } 
20 }
In our Init() we called a method GetKey, which we use to initialize our secretKey variable. This method
simply checks the web.config file for the SessionKey section and returns the value. An exception will be
thrown if this value doesn't exist in the web.config:
view sourceprint?
01 /// <summary> 
02 /// method for retrieving the validation key from the web.config 
03 /// </summary> 
04 /// <returns></returns> 
05 private string GetKey() 
06 { 
07     //get the key 
08     string validationKey = ConfigurationManager.AppSettings["SessionKey"]; 
09   
10     //check for a null or empty key. If so throw our exception 
11     if (validationKey == null || validationKey == String.Empty)
                                            throw new SessionerrorException("SessionKey not found. Application  
12   
13 ending"); 
14   
15     //return the key 
16     return validationKey; 
17 }
We have four more methods to look at in this class (before we get to our custom Exception class).
They are
•RetrieveRequestCookie: Used to retrieve the current Request cookie.
•RetrieveResponseCookie: Used to retrieve the current Response cookie.
•FindTheCookie: Used to find a cookie by it's name.
•CreateMAC: Used to generate our custom MAC value for the session cookie.
view sourceprint?
01 /// <summary> 
02 /// method for retrieving the Request cookies 
03 /// </summary> 
04 /// <param name="currentRequest"></param> 
05 /// <param name="cookieName"></param> 
06 /// <returns></returns> 
07 private HttpCookie RetrieveRequestCookie(HttpRequest currentRequest, string cookieName) 
08 { 
09     HttpCookieCollection cookieCollection = currentRequest.Cookies; 
10     return FindTheCookie(cookieCollection, cookieName); 
11 } 
12   
13 /// <summary> 
14 /// method for retrieving the Response cookies 
15 /// </summary> 
16 /// <param name="currentResponse"></param> 
17 /// <param name="cookieName"></param> 
18 /// <returns></returns> 
19 private HttpCookie RetrieveResponseCookie(HttpResponse currentResponse, string cookieName) 
20 { 
21     HttpCookieCollection cookies = currentResponse.Cookies; 
22     return FindTheCookie(cookies, cookieName); 
23 }
FindTheCookie takes an HttpCookieCollection and a name as a parameter. From there it loops the length
of the HttpCookieCollection passed to it comparing each cookie name with the name provided. If it finds
a match it returns that HttpCookie, otherwise it returns null
view sourceprint?
01 /// <summary> 
02 /// method for retrieving a cookie by it's name 
03 /// </summary> 
04 /// <param name="cookieCollection">the cookie collection to search</param> 
05 /// <param name="cookieName">the cookie we're looking for</param> 
06 /// <returns></returns> 
07 private HttpCookie FindTheCookie(HttpCookieCollection cookieCollection, string cookieName) 
08 { 
09     for (int i = 0; i < cookieCollection.Count; i++) 
10     { 
11         if (string.Compare(cookieCollection[i].Name, cookieName, true, CultureInfo.InvariantCulture) == 0) 
12             return cookieCollection[i]; 
13     } 
14   
15     return null; 
16 }
Now we just need to generate a MAC for our session cookie. This is done by appending the current session
id with the first segment of the users IP address and his User Agent. We then use the HMACSHA1 Class to
generate a new MAC for the cookie:
view sourceprint?
01 /// <summary> 
02 /// method for generating a new MAC for our session cookie 
03 /// </summary> 
04 /// <param name="id">current session id</param> 
05 /// <param name="ipAddress">ip address of the current Request</param> 
06 /// <param name="userAgent">current user's User Agent</param> 
07 /// <param name="validationKey">validation key from the web.config</param> 
08 /// <returns></returns> 
09 private string CreateMAC(string id, string ipAddress, string userAgent, string validationKey) 
10 { 
11     //create an instance of the StringBuilder with a max length of 512 
12     StringBuilder sb = new StringBuilder(id, 512); 
13   
14     //append the first segment of the user's ip address to the string 
15     sb.Append(ipAddress.Substring(0, ipAddress.IndexOf('.', ipAddress.IndexOf('.') + 1))); 
16   
17     //append the users User Agent to the string 
18     sb.Append(userAgent); 
19   
20     using (HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(validationKey))) 
21     { 
22         return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()))); 
23     } 
24 }
Creating a custom Exception class is fairly straight forward so I am just going to post the code with little or
no explanation. For more information on creating your own exception classes, read this on Creating Custom
Exception In .Net, it has some pretty good information in it.
view sourceprint?
01 [Serializable] 
02 public class SessionerrorException : Exception 
03 { 
04     public SessionerrorException() : base("Invalid Session") { }  
05   
06     public SessionerrorException(string message) : base(message) { } 
07   
08     public SessionerrorException(string message, Exception inner) : base(message, inner) { } 
09   
10     protected SessionerrorException(SerializationInfo info, StreamingContext context)
                                                                                                                : base(info, context) { } 
11 }
Now that we have the coding part done, that is creating the module and the custom Exception, there
are some things we need to add to the web.config file in order to wrap this up. First is the validation
key, which should be a long random string generated with a MD5 hash. This should be placed in the
<appSettings> section of your web.config file, and should look like this
view sourceprint?
1 <appSettings> 
2     <add key="SessionKey" value="3595381625A3DCC07E84E626939254834E0FD16B"/> 
3 </appSettings>
My particular key is a MD5 hash based on a 11 character word (that will remain a secret). The last thing
we need to do is register this HttpModule in our web.config. As you can image this needs to go in the
<httpModules> section of the web.config. That looks like this
view sourceprint?
1 <httpModules> 
2     <add name="SecureSession" type="RLM.Core.Components.Security.SecureSession, SecureSession"/> 
3 </httpModules>
The syntax for registering a module is
Quote
<httpModules>
<add name="YourName" type="YourNamespace.YourClassName, YourProjectName"/>
</httpModules>
There you have it, a way to fight session hijacking in your ASP.NET applications. Remember, there is no
100% foolproof way to prevent this, this class is simply meant as one way to make it harder for hackers
to hijack your users sessions, and thus giving them access to the users information.