Authentication and Session timeout – Session expired message on clicking the login button

In my starting phase of Career, My client reported me a peculiar issue. They said that they get redirected to session expired page even before they actually Login.

In that application, We developed a generic methodology, then whenever a user clicks on any action that requires a post back, it first checks whether session is expired or not and if expired then redirects to a custom session expired page. Later, user can click on login link and redirected to Login page.

[As asked by one of my blog readers, There could be many ways for the generic methodology. I have seen people place common code at several place like Master Page,  some put in base class that further worked as base class for all the web pages. I used it in a base class. In my view there are other places like Global.asax and methods could be Application_PreRequestHandlerExecute, Application_AcquireRequestState .]

I analyzed that Issue and found that users used to open the website first page which is obviously the Login page and some of them left the page for a while around 15 or more minutes and after that they when they again back to system, used to enter the credentials and click on login button, it redirects them to session expired page.

It left them annoying and even me too. I have myself seen to many application where I open the Login page and after sometime when I enter my Login details but it redirects me to session expired page.

Some of my colleagues was saying, how a session can expire even before successfully login. I have also found many other developers have same question. So I thought of writing a blog post on it.

So first let me explain, how session works

Session_Life_Cycle

So as you can see above, as soon as user accesses the site and the first page gets opened, the countdown of the session timeout starts. So it does not matter whether you Login or not, session will be expired after the specified amount of time. So if your website does not have a check on session expiration before Login then it wont be visible to your user and even if user Logins after the specified amount of time, A new session will be created.

But so many people get confused about authentication and session. Session start and expire does not have any connection with authentication start and authentication timeout. Authentication works separately.

As you know, A user request any Page, It goes through many HTTPModules and lastly served by a HTTPHandler. We can show it pictorially as

ASP.NET Request Proessing

As you can see, An asp.net request goes through many HTTPModules and finally served by a HTTPHandler. Many features of ASP.NET are developed as HTTP Module. Session and Authentication are also developed as HTTPModules . For session handling we have SessionStateModule which is available under the namespace System.Web.SessionState and various Authentication mechanism in ASP.NET like Form Authentication is also available via a HTTPModule FormsAuthenticationModule which is under the namespace System.Web.Security.  So these two are separate modules and works independently.

Normally in our application, as soon as user clicks on sign out, we used to kill session. Normally, we set authentication time out and session timeout same but what may happen if we have

<forms timeout="15" loginUrl="Login.aspx" name=".ASPXFORMSAUTH">

and

<sessionState timeout="10">

What could happen

user's browsing history

As you can see in the above scenario, I have set session time out is less than authentication timeout. After browsing for 5 mins, I left it for around 12 mins and my session got timeout.  As my session time out is 10 mins while my authentication time out is 15 mins. But I’ll be still authenticated and able to browse application even my session expired and got recreated and my existing session data will be lost.

So normally we put the authentication time out and same time out as same. This is just first step to avoid the discrepancy between the timeout of Authentication and Session.

But at certain browsers, it behaves differently. Like Session gets time out if the last request made was 10 (in my example session timeout is 10 minutes) or more minutes and on every request the counter get resets for 10 minutes but Authentication timeout does not work in same ways in different browsers. Like if have authentication timeout for 10 minutes, the authentication timeout counter does not get reset on every request to 10 minutes. Sometimes there are some performance improvement has been done which resets on the counter only at certain points say if after 5 or 7 minutes as to reset the authentication timeout on very request is costly. And this may lead to discrepancy.

Other scenario, If some how IIS gets reset the sessions of the users connected to that web server will become invalid while the user authentication will still be valid.

To avoid any unprecedented event like above, I put a check for an authentication and session on every page, So that user cannot continue further if session or authentication is not valid. Also if we found user is not authenticated any more then used to clear and abandon the session and redirects the user to login page. Similarly, if session is not available then the remove the user the authentication as well.

Also, at the time of user clicking on Logoff, one should clear and abandon the session. So that same session is not available after Logoff.

So as you can see, that session and authentication works separately and they work parallely and independently.

So for the problem stated earlier in this post, I suggested a solution to avoid the issue but you can yourself can put your own logic to prevent the issue.

Hope you all have enjoyed this post. Please share your valuable feedback.

Cheers,
Brij

Advertisement

FriendlyURL : A new and exciting feature of ASP.NET

This is going to be the last post of 2012 by me. I am very happy that I am writing about a very exciting feature that is coming with ASP.NET.

I am really excited to learn and write on this. I really hated the ugly URLs and the extensions of the page that always visible when one opens the application unless and until you write your own custom url processor. With ASP.NET 4.0, Routing was introduced, which provided the capability to ASP.NET to have easier, manageable and SEO friendly urls, I wrote a post on it. You can click below to have a look on it.

URL Routing with ASP.NET 4.0

But that is little tidy to write. And it looks like writing extra code that does not produces any business functionality.

FriendlyURL as the name suggests gives a clean and SEO friendly URL.Currently it is available via NuGet and in pre release version.

So For this post, I have used my Visual Studio 2012 IDE. I created a new project as File-> New -> Website -> ASP.NET Empty Website.

Once the project got created. I require to install the NuGet for my application. So got to Tools-> Library Package Manager-> Package Manager Console

Package Manager Console

It opens a console then type Install-Package Microsoft.AspNet.FriendlyUrls -Pre and press enter as

FriendlyURL NugetInstallation

As you can see, I typed the command and can be seen in  the first red encircled area and press enter. It’ll install the NuGet and you can see the last red encircled area which shows FirendlyUrl is successfully added.

This can be used with two ASP.NET versions: ASP.NET 4.5 and ASP.NET 4.0.

Now you are ready for working with friendly URLs.

If you have  read the Readme.text. It gives a clear  idea how to start with. But I’ll take you through the steps. So let’s start

Step 1-> Add and Create a Class name preferably RouteConfig.cs ( You can have any name. I used MyRouteConfig.cs) and make it static. Also add the name space in the class Microsoft.AspNet.FriendlyUrls

Step 2-> Create a static Function in the class preferably named as RegisterRoutes with a Parameter of type RouteCollection and add  a line  routes.EnableFriendlyUrls() in the method as

public static class MyRouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.EnableFriendlyUrls();
    }
}

Step 3-> Add Global.asax file and add the following line in Application_Start as

  void Application_Start(object sender, EventArgs e)
    {
        MyRouteConfig.RegisterRoutes(RouteTable.Routes)
    }

Now you can start the development of your application. I have created two pages First.aspx and Second.aspx in my solution

That’s it. Now your code is ready for run.

First PageIf you see the above circled area in the above pic, it does not contain page extension (aspx). So now the url looks pretty. As an end user, I don’t care about the page extension and even some time it just irritates me.

Now if you want to redirect to another page, you can redirect by typing URL without page extension as

Response.Redirect("~\\Second");

There is one caveat here. You can not have a folder and Page with same name at the same level. If you have the name of a folder and the name of aspx page at same level, you would not be able to access the page without extension. So please keep it in mind.

Now you must have a question in Querystring. What will happen with Querystring?

You don’t need to worry at all. QueryStrings will work as earlier . Let’s have a look to the URL http://localhost:57353/First?Id=1001 then you can read the QueryString as below similar as earlier

string Id = Request.QueryString["Id"] as string;

Next point, if I have a URL say http://localhost:57353/First/Products/NewProduct and there is no page as NewProduct. What will happen It’ll open First.aspx.

But, How it works?

It starts from last segment (NewProduct) and will check if there is any NewProduct.aspx. If not then it moves to next segment and continue till it finds the exact aspx page.

Let’s explore more. Go to the server side of the page and include the namespace Microsoft.AspNet.FriendlyUrls. You’ll get bunch of methods that will be very useful at certain times.

  • Request.GetFriendlyUrlSegments() – It returns a collections of string which represents the URL segments. So if I have a URL http://localhost:57353/First/Products/NewProduct and the page exists First.aspx then it returns.
    URLSegments
    So you can see above, there is two segments and one can iterate through it. These url segments can be used to pass the values to a page via URL instead of QueryString. It also looks pretty.
  • Request.GetFriendlyUrlFileVirtualPath() – It returns the File virtual path. For the URL, discussed in the above example it will show as
    File Virtual Path
    You can see it shows the Virtual path of the file.
  • Request.GetFriendlyUrlFileExtension() -It returns the extension of the file. For the above url, it will be shown as File Extension
    As you can see, the extension of the page. As now with friendly url, the page extension is not shown. You can get the extension by the above method.

There are other important methods/features available that can be used to generate the URL etc. I’ll discuss some of those here

An available class FriendlyURL provides few static functions/properties that is very useful. Let’s see

  • FriendlyUrl.Segments ; Returns the segments of of the current URL similar as returned by Request.GetFriendlyUrlSegments()
  • FriendlyUrl.Resolve : This can be used to resolve the FriendlyUrl
    • FriendlyUrl.Href – It takes few parameters virtual path and list of url segments and generate the friendly URL out of it. And it is very useful while generating the URL in data binding and several other places. We can write
      FriendlyUrl.Href("~/First", "Product", 1001);
      

      And what it will return
      FriendlyURLgeneration

Hope you must have liked this new coming feature of ASP.NET. This will will let you get rid of aspx extension at URL , Frankly speaking, during my earlier days of career, I used to see the extension to check if the website is developed in asp.net.

I find this feature as one of the most of the exciting features of ASP.NET. Hope you all enjoy it and also like the post.

Enjoy and Love ASP.NET. And A very Happy New Year to all.
Cheers.
Brij

IsCrossPagePostBack : Cross page PostBack

Download sample from here

Last few days, I was working on one of my module in my web application. During writing code, I came accorss one property IsCrassPagePostBack of Page Class. I have seen this earlier but never tried to dig. So I thought of exploring it and here I am sharing my findings with you all.

First, Let’s start from beginning. We know when we submit a page, entire form data with hidden fields, including view state is posted to the server. One must be using IsPostBack property a lot. It is false when page loaded first time but returns true if any postback takes place. Whenever we click any server side control like button, linkbuttons etc or any other control with autopostback true. All the data including hidden field, View State etc.. is posted to the server and available for processing at codebehind. Continue reading…

Client Ids generation with ASP.NET 4.0

From last sometimes, I started exploring ASP.NET 4.0 webforms enhancement. I really found some exciting enhancements in ASP.NET 4.0 and am sure, this all going to be make web development simple and will provide more flexibility to us.So I started picking the most exciting features of the ASP.NET 4.0 one by one.Earlier I wrote on URL Routing, you can go through to the link as below.

URL Routing with ASP.NET 4.0 [^]

As form the Title, you know that here I am going to discuss how we can control over generation of Client Ids of ASP.NET Server controls in ASP.NET 4.0. This Client Ids was another thing that was earlier mystery for me but later I identified the algorithm that is used to generate the the ClientIds for the server controls by the .NET engine,but they never been user friendly.

Why Client Ids:

Client Ids were always been problem for us.But as now a days, in new age application we are moving more towards the client side programming in new Rich Interent applications. Many new technologies and the way of programming has been evolved in last few years to make very rich UI like JQuery,JSon,Dojo.

In DOM, to access a a control client id play pivotal role.So Microsoft also trying to make our life easier by providing the capability to control over the client id generation which will ensure easy simple and less error prone RIA development.

Client Ids earlier:

So lets discus, how the ClientIds were generated earlier. First I’will statrt with normal control say textbox control or a label. So here the client Ids that are generated, was starting with prefix of all the naming containers from top to bottom with separated as underscore. And actually this was a good idea to generate the unique id at client side. But as I discussed ClientIds are key part of new age development. Lets look at the example for a simple textbox server control.My aspx looks like

So from the above picture we can see that my label and textbox are inside a contentplaceholder. Now lets look at the ClientId

Now here client Id is ctl00_ContentPlaceHolder1_myTextBox.If we go one by one the ctl00 is the counter ,next one is ID of contentplaceholder and next id of textbox.

So one thing as you move the control to some other part the Client Id will get changed as well.

So although we know the ID is going to be unique on the page but still you dont have any control over itFrown . .Net engine will generate the ClientIds according to its algorithm for you ).

So this all about of the simple controls, Now lets talk about some data controls, like gridview listwiew, dropdown etc. Here in these control what we do, we just bind the datasource to the control. And at runtime based on the data, the number of rows(controls) are generated. So what about the client Ids here. Here also the Client Ids are being generated in the same way as I already discussed with prefix of rownumber. So lets have a look to the example.

My aspx code for GridView. Here I am showing ID,Book Name and Price

So in the above example, I have taken a gridview. And in this I have three label in different ItemTemplates. The gridview is in contentplaceholder.

Now look to the ClientIds

You can see the id is like ctl00_ContentPlaceHolder1_gridviewBooks_ctl02_lblID. So here if we go one by one first the counter the contentplaceholder id again rowcounter generated in sequence for every row by .Net engine to make it unique and last lebel ID.

So  it becomes very uneasy to use.

But as new era web development, when we doing lots of work at client side the Client ids become a key part in web development.

Control Client Ids generation with ASP.NET 4.0:

ASP.NET 4.0 provides the power to control Client Ids generation. For that it provide the new property ClientIDMode property to handle this.This property enables us to to specify that, how the Client Ids will be generated for the controls . This provides four options:

  • AutoID
  • Static
  • Predictable
  • Inherit

We’ll discuss one by one.

AutoID:  this property is same as earlier version of .NET.Specify this value if you dont want any changes in the Client Id genration from the earlier version.As I discussed in ClientIDs in earlier versions.

Static: Means the you want the static id of your control.You should use this property when you know the ID will be going to be unique on the page. Here .net engine will generate the Client Ids as it is, without adding any suffixes or prefixes in it. This mode is mainly used for normal single control. Lets look at the example.

Here as you seen in the picture,I set the ClientIDMode for Label AutoID and for TextBox I set it Static. Now lets see the generated Client Ids

Now if you see the client ID of Label it is same as earlier one because here I set it Auto.

But for the TextBox I set it static. So here the Client Id is same as the ID that we set it on aspx page.This is the beauty of ASP.NET 4.0 . So if we set it static the .net engine wont generate a new client id for the control it will use the ID of the control as Client ID.

Note: One thing need to make sure here, if we set the mode static then there should be no control on the page with the same id because it will have the same client id on the page and it may be disastrous when we access it from Clientside.

Predictable: This is one another mode that I liked for the ClienId generation. When you exactly dont know whether the Id is unique on the page or not, then you can use this property.This value enables us the predict the client ids on the rendered page.When you set mode to this, you need to set some more proprties according to your own choice.

Now I will take the example as above.Now here the aspx code would be like

Here One thing we are using datacontrol then we can not set it static because there going to be multiple controls generated based on the data.

So here we will be using mode as Predictable so that we can predict what will be the id of the contrl. One more property ClientIDRowSuffix we need to set it here. I set it ID meand the ID column.

Now lets look at the generated Client Ids

Now here if we look at the ClientID . So here it is MainContent_gridviewBooks_lblName_1. So if look it deeply the we find that here there is no conter like thing. Here we have first id of contentplaceholder the id of gridview the id of label the the suffix id that we set. So its really predictable Smile and similarly for other rows.

Inherit: This is also value to set the to this property.As the name suggests,it means the Id genration of the contrl will be same as parent cpntrol. This is the default behavior of the control.

Setting the property at various levels:

There are various places where we can set the ClientIDMode property.This can be set at control level, page level as well as application. The behavior will be same. We can set it at page directive as below.

To set it at Application level, we need to set it in config file as

and that will be applied across all the pages in the application.

Feedback and Suggestions:

Feedback is key for improvement. I would request to you all to share your feedback and give me some suggestions, which which would encourage and help in more and quality writing.

ViewState: Various ways to reduce performance overhead

Introduction
In this Article, I am going to explore the Viewstate. View state is one thing that always I liked to use. It makes our life easier. As we all know that Viewstate is one way of maintaining the states in the web applications.

As we know, a web page is created every time when a page is posted to the server.It means The values that user entered in the webpage is going to be vanished after the poastback or submit. To get rid of this problem, ASP.NET framework provides a way to maintain these values by virtue of Viewstate. When we enable the viewstate of any control, the value is going to be maintained on every postbacks or server roundtrips.

But how these values get maintained? It doesn’t come free.View state uses hidden valriable that resides on the page to store the controls values. It means that if a page have lots of controls with viewstate enabled the page size would become heavy, in several of kilobytes ie it will take longer time to download.And also on every postback all the data is posted to the server i e increasing the network tarffic as well.

As in new era application, we use lots of heavy controls like gridview etc, on our page which makes page size exponetially heavy.It is always recommended to use viewsate judiciously and even some programmers try to to avoid using this cause of performace overhead.

Here , I am going to discuss how we can reduce the performance overhead caused by viewstate.

Problems with viewstate:
n our new era application, we generally have lots of rich and heavy controls on our page and also provide lots of functionality on the page with the help of few latest technology AJAX etc. To accomplish our task we use Viewstate a lot but as we know it doesn’t come free it has a performance overhead.

As we know viewstate is stored on the page in form of hidden variable. Its always advised to use viewstate as less as possible. we have also other ways to reduce the performance overhead. So we have several ways,here I am going to discuss the following ways

* By compressing decompressing the viewstate
* Aanother way to store the view state at some other server say on web server.

ViewState Compression/Decompression
We can compress the viewstate to reduce the pagesize. By compressing the viewstate we can reduce the viewstate size by more than 30%. But here the question arises, where to compress and decompress the viewstate. For that we have to dig into the Page life cycle. As we know, viewstate is used by the ASP.NET to populate the controls. So we should compress the viewstate after all the changes are done in the viewstate and saving it after compression and we have to decompress the viewstate just before it is used by asp.net to load all the controls from viewstate . So lets jump to thepage life cycle and see our we can fit our requirement.
Page Life Cycle
As we can see there are two methods,One SaveViewState that is responsible for collecting the view state information for all of the controls in its control hierarchy in this method and persist it it in __viewstate hiddenform field. The view state is serialized to the hidden form field in the SavePageStateToPersistenceMedium() method during the save view state stage, and is deserialized by the Page class’s LoadPageStateFromPersistenceMedium() method in the load view state stage. So here in these methods we can compress and decompress the viewstate. Lets take a pictorial view.
Flow
So here, we need to override the methods SavePageStateToPersistenceMedium()for compressing the viewstate and SavePageStateToPersistenceMedium() for decompressing the viewstate. Here I am going to use GZip for compression that is provided by the .NET itself.And this is available in th namespace System.IO.Compression….
Complete article has been published on CodeProject. To view Click here

URL Routing with ASP.NET 4.0

One thing, that was always pinched me , the long URLs that I used to see in my several projects.Due to better managebility, I used to have several folders ie folder hierarchy for maintainability of my application. But the thing that I didn’t like ever that full physical path of pages in URL.There are other ways, which allow us to get rid of it like URL rewriting but that I didn’t like.
Also we could have our own custom URL route handler or some third party
solution
, but they never been strong enough for an application.

Frankly speaking, One of my Client asked me several times , “Why this .aspx extenstion displays in URL” and also told me that he dont like this long urls. I used to tell him, this is the normal behavior of ASP.NET application.But we can change it with our own custom solution but that will require bit time and also require lot of testing.
But when Microsoft releases ASP.NET MVC 2 with .Net framework 3.5 SP1, and provided
this Routing feature with it. I became very happy and started to explore it. In the meantime ,I thought that It should also be provided with ASP.NET, because every time you may not require to follow MVC architecture and also found that MVC has nothing special to do with URL Routing.So I was expecting and waiting
for ASP.NET Webform Routing.
Now Microsoft introduced URL Routing with ASP.NET 4.0.URL routing is fully integrated, very powerful and straight forward.

So What is URL Routing:

We access our webapplication using some URL that is normally the physical path of the of pages.So URL Routing is a way to provide our own URL in lieu of the physical path of the page. One other way, Routing allows us a way to configure our application to accept a requested URL which actually doesn’t map to physical
files. In terms of security perspective of the application, its important because one can easily know the solution structure of the application.

URL Routing

URL Routing


Complete article has been published on CodeProject. To view Click here