Session hijacking fix

session hijacking is not something new to discuss.Users are authenticated based on their login credentials (e.g. user names and passwords) and are issued session IDs that will effectively serve as temporary static passwords for accessing their sessions, which makes session IDs a very appealing target for attackers. The moment a user enters his credentials on login to authenticate, these data are stored in the session and cookies are generated in the client browser. When we logeed out we assume session is terminated. But in realiity we can see the cookie values are not deleted from the client browser, even if the session is ended, and such cookie values could be exploited by a hacker to breach into the website’s sensitive zone, without being aware of user name and password. There are several approaches to overcome such session hijacking kinds of attacks. I would like to share one of the approach we did in our client place. You can see Login() and Logout functions getting called on user actions and the caopde make sure that prevent session hijacking

        public ActionResult Logout()
        {
            //Clear all cookies
            var count = Request.Cookies.Count;
            for (int i = 0; i < count; i++)
            {
                var cookie = Request.Cookies.Get(i);
                if (cookie != null)
                {
                    cookie.Expires = DateTime.Now.AddHours(-1);
                    cookie.Value = string.Empty;
                    Response.Cookies.Add(cookie);
                }
            }
            Session.Abandon();
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Account");
        }
        public ActionResult Login()
        {
            //Clear all cookies. Any cookie set before login should be invalid. since it can enable session fixation attacks
            if (Request.Cookies["__CKIE"] == null || Request.Cookies["__CKIE"].Value == string.Empty)
            {
                var count = Request.Cookies.Count;
                for (var i = 0; i < count; i++)
                {
                    var cookie = Request.Cookies.Get(i);
                    if (cookie != null)
                    {
                        cookie.Expires = DateTime.Now.AddHours(-1);
                        cookie.Value = string.Empty;
                        Response.Cookies.Add(cookie);
                    }
                }
                Response.Cookies.Add(new HttpCookie("__CKIE", "1"));
                Response.Redirect("~/Account/Login", true);
            }
            else
            {
                var cookie = Request.Cookies["__CKIE"];
                cookie.Expires = DateTime.Now.AddHours(-1);
                cookie.Value = string.Empty;
                Response.Cookies.Add(cookie);
            }
            return View();
        }

Force IE8 *not* to use Compatibility View

If you want to make sure IE or the user doesn’t dictate how you code, or how the layout is manipulated by compatibility view, add the following to your section…

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
or
<meta http-equiv="X-UA-Compatible" content="IE=8" />

‘edge’ tells IE8 to use it’s highest compatibility mode available. It should be safe to assume future flavors of IE will handle it the same way.It should force IE8 to render as IE8 Standard Mode even if “Display intranet sites in compatibility view” is checked.
In Corporate Networks administrators MAY have a policy to “Display intranet sites in compatibility view” whicn might mess up your website that you are targetting for latest versions.Micorosft introduced compatibility mode for some weird reason, and it will only mess things up more times than be helpful. What it will do is make IE behave like it’s IE5, and that’s most likely the reason why not everything works.

Web Development Improvements with VS 2010

There are many more features shipped with Visual studio 2010 which helps you to develope web application. I was just going through some of the features that provided by VS2010 as well as ASP 4.0.
ASP.NET MVC
ASP.NET MVC was introduced as an add-on framework to ASP.NET 3.5 SP1 in March 2009. Visual Studio 2010 includes ASP.NET MVC 2, which includes new features and capabilities.This let you group controllers and views into sections of a large application in relative isolation from other sections. Each area can be implemented as a separate ASP.NET MVC project that can then be referenced by the main application. This helps manage complexity when you build a large application and makes it easier for multiple teams to work together on a single application.
This will be a very small piece of ice berg. Well, I am going to have a separate thread on ASP.NET MVC.
IntelliSense Enhancements – JavaScript
VS 2010 has come up with rich developer experience in JavaScript writing. They have included intelligence to recognize objects that have been dynamically generated by methods such as register Namespace and by similar techniques used by other JavaScript frameworks. They also addressed the performance of display IntelliSense with little or no processing delay. Documentation comments are now parsed as you type and are immediately leveraged by IntelliSense.
HTML and JavaScript Snippets
In the HTML editor, IntelliSense auto-completes tag names. The IntelliSense Snippets feature auto-completes entire tags and more. Visual Studio 2010 includes over 200 snippets that help you auto-complete common ASP.NET and HTML tags, including required attributes (such as runat=”server”) and common attributes specific to a tag (such as ID, Text etc).It is also support download of additional snippets, including you can write your own snippets that encapsulate the blocks of markup that you or your team use for common tasks.
CSS Improvements
One of the major areas of work in 2010 has been to help render HTML that is compliant with the latest HTML standards. This includes changes to how ASP.NET Web server controls use CSS styles.
New Project Templates
In earlier version of ASP.NET when we create a web application it creates only minimal files.Ex: Web.Config, app_data ,Default.aspx etc. With VS 2010 they have shipped new project templates that contain major changes. The following figure shows the project layout that is created when you create a new Web Application project. (The layout for a Web Site project is virtually identical.)
The project includes a number of files that were not created in earlier versions. In addition, the new Web Application project is configured with basic membership functionality, which lets you quickly get started in securing access to the new application. The intention of these changes to the project templates is to provide guidance on how to start building a new Web application. With semantically correct. , the pages in the templates represent best practices for building ASP.NET 4 Web applications. The default pages also have a two-column layout that you can easily customize.We can then go into the Site.css file and modify CSS class definitions to change the background color of the page as well as that of the header, as in the following example.
Web.config File Refactoring
The web.config file has grown big over the past release of web frame work as to include new features. With Asp.NET 4 as VS 2010 , the major configuration elements have been moved to the machine.config file, and applications now inherit these settings. This allows the Web.config file in ASP.NET 4 applications either to be empty.
jQuery Included with Web Forms and MVC
The Visual Studio templates for both Web Forms and MVC include the open-source jQuery library.
Enabling View State for Individual Controls
By default, view state is enabled for the page, with the result that each control on the page potentially stores view state even if it is not required for the application.In earlier versions of ASP.NET, developers could disable view state for individual controls in order to reduce page size, but had to do so explicitly for individual controls. In ASP.NET 4, Web server controls include a ViewStateMode property that lets you disable view state by default and then enable it only for the controls that require it in the page.
ASP.NET Chart Conrol
The ASP.NET Chart control expands the data-visualization offerings in the .NET Framework. Using the Chart control, you can easily create ASP.NET pages that have intuitive and visually compelling charts for complex statistical or financial analysis.
Well , I know that blog is not going to cover all features that shipped with VS 2010 as well as ASP 4.0.I am planning spent some time and take up one by one features and come up with detailed code samples for each.

GridView JavaScripts

GridView Control – Javascripts
While working with Grid View I had to write few small JavaScript snippets to perform certain tasks like reading values form one text box in the grid View and assign to a hidden filed so that we can access the same in server side for any changes if user made. Looks simple but I am sharing some of the JavaScript’s which I wrote for Grid View on asp.net page.Read the text box placed in a Grid View and assigns the values to the hidden field. The script is wired to submit button click on client side:
Likewise for adding any events associated with a grid View control for example if you have a check box on the grid and if you want to attach a JavaScript associated with each control on the grid please add following code in the server side on Grid View row data bound.

function SubmitSaveClick() {   
//get reference of GridView control
    var grid = document.getElementById("");
    //variable to contain the cell of the grid
    var cell;
    if (null != grid) {
        if (grid.rows.length > 0) {
            //loop starts from 1. rows[0] points to the header.
            for (i = 1; i < grid.rows.length; i++) {
                //get the reference of first column
                cell = grid.rows[i].cells[2];
                //loop according to the number of childNodes in the cell
                for (j = 0; j < cell.childNodes.length; j++) {
                    //if childNode type is text
                    if (cell.childNodes[j].type == "text") {
                        cell.children[3].value = cell.children[0].value;
                    }
                }
            }
        }
    }
    return true;
}
try
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DateTime dtConvert;
        string dateFormat = string.Empty;
        CheckBox chkGender = e.Row.Cells[1].FindControl("chkGender") as CheckBox;
        chkGender.Attributes.Add("onclick", "ChangeDate();");
        if (chkGender.Checked)
            e.Row.Enabled = true;
}
catch (Exception ex)
{
   LogException(ex);
}

Pagination in asp.net

Requirement :
There was a functional; requirement to pull the customer data from the database and display on a web page. But in one query itself will return 1000 records at a time. Seeing 1000 records a t a time was not handy for the user as well as it will be a major hit for the performance aspect. So the requirement was to provide something a kind of page like feeling to the user for the bulk record user where user can see a page at a time where he can go next and previous page same as in a book.
Solutions:
Well, this is not something new to scratch the head. Microsoft has addressed as well as provided solutions for this- nothing but pagination. Basically, you show just one page on screen and provide a navigation bar on top or on bottom of the page (or both) so user can navigate to other pages if wants. The paging can be implemented 2 of the below ways.
• Default Paging – can be implemented by simply checking the Enable Paging option in the data Web control’s smart tag; however, whenever viewing a page of data, the ObjectDataSource retrieves all of the records, even though only a subset of them are displayed in the page
• Custom Paging – improves the performance of default paging by retrieving only those records from the database that need to be displayed for the particular page of data requested by the user; however, custom paging involves a bit more effort to implement than default paging
Default Paging:
To enable default paging we need to explicitly set AllowPaging property of DataGrid control to True. Use PageSize property to set the number of records to be displayed per page. PageSize has a default value of 10. DataGrid control has a property CurrentPageIndex which gives the index of current page being displayed i.e. for the first Page DataGrod1.CurrentPageIndex will be zero. Another property PageCount exposes the total number of pages. In other words PageCount indicates the number of pages in DataGrid control to display all the data from the data source. We will make use of above properties to implement paging in our ASPX page. When the user clicks on a page hyperlink on the ASPX web form, postback operation is performed. On postback, PageIndexChanged Event of DataGrid is called. What all we need to do is implement an eventhandler for the PageIndexChanged event as follows.
Custom Paging:
One problem with Default Paging is, every time we request for a page in the DataGrid, it retrieves complete data from the database. This problem can be a bottle neck if the volume of date we are working with is huge. A genuine suggestion to this problem which comes into mind immediately is to fetch only that data which we need to display on the page. This is what custom paging is all about i.e. fetching only required data from database. To enable Custom paging we need to explicitly set AllowCustomPaging property of DataGrid control to True. Use PageSize property to set the number of records to be displayed per page. We need to set VirtualItemCount property of DataGrid control. This property tells the DataGrid
Pagination using object data source:
I have explored some features of ObjectDataSource control with GridView, which is shipped with ASP.net 2.0. The ObjectDataSource control is used to bind the controls to middle-tier busines objects.it will help us in implementing the custom paging mechanism very easily without the need to build page numbers separately i.e. we can still use inbuilt paging feature of GridView to display page numbers and we can use ObjectDataSource control to fetch the records that is required only for that page.WE have implimented paging using this in our application.Here for example given below we need to pass the parameteres of startindex,pagesize as well as page size as a parameter to selected method as well as sql query.Here also I have passed sort directins also.

ASP.NET Ajax

What is ASP.NT AJAX?
Let me try to put it in simple words what i understood.
ASP.NET Ajax is a set of extensions to asp.net to implement AJAX functionality. AJAX stands for Asynchronous JavaScript and XML, which, very simply put, is a way of transferring data between the server and client without the sending the entire page, and thereby creating a complete post back. This allows for a richer experience for the user, since loading dynamic content can be done in the background, without refreshing and redrawing the entire page.
Well, if you are not aware of what is Ajax surly you might be unknowingly experienced what it is. If you have ever used Gmail or Outlook Web Access, you have used an Ajax enabled web application, and especially Google have made Ajax very popular.
Now let me try to give a fare idea on what is Ajax Control Tool kit?
The Ajax Control Toolkit contains a rich set of controls that you can use to build highly responsive and interactive Ajax-enabled Web applications. The Ajax Control Toolkit contains more than 40 controls, including the AutoComplete, CollapsiblePanel, ColorPicker, MaskedEdit, Calendar, Accordion, and Watermark controls. Using the Ajax Control Toolkit, you can build Ajax-enabled ASP.NET Web Forms applications by dragging-and-dropping Toolkit controls from the Visual Studio Toolbox onto a Web Forms page.
Well, here I am not daring to explain you complete AJAX technology provided by Microsoft rather love to explain where I have used it and what is the technical problem which made me to go behind Ajax with a simple example. Sounds good right?
Problem definition:
I was developing a module which has a complex UI with 4 grid view controls across 2 tab controls! And among that one grid has dropdown box, in change of value we need to do some server side coding. So here what happen each time when user change the values of these dropdown user experience a flicker due to post back.
The Solution :The solution was very simple wit Ajax tool kit.
In the CodeBehind, there’s the value change event captured. OnSelectedIndexChanged.
In the markup part, we use two new things, when compared to regular ASP.NET: The ScriptManager control and the UpdatePanel control. The ScriptManager makes sure that the required ASP.NET AJAX files are included and that AJAX support is added, and has to be included on every page where you wish to use AJAX functionality. After the manager, we have one of the most used controls when working with AJAX, the UpdatePanel. This control allows you to wrap markup which you would like to allow to be partially updated, that is, updated without causing a real postback to the server.
The UpdatePanel control is probably the most important control in the ASP.NET AJAX package. It will AJAX’ify controls contained within it, allowing partial rendering of the area.
The tag has two childtags – the ContentTemplate and the Triggers tags. The ContentTemplate tag is required, since it holds the content of the panel. The content can be anything that you would normally put on your page, from literal text to web controls.
This is something very minimal to explain the AJAX technology. I would suggest please go in to deep in to this technology, and I promise you will be getting interesting things that we can go ahead and implement in our web applications.