HttpHandler with Session State

If you are developing httphandler in asp.net realized that httphandlers can not use session as default.If you want to access session object do it as below.

Add  “System.Web.SessionState” namespace to your handler code.

There are two interface . one of them  must be inherited by your httphandler object:

IRequiresSessionState Interface

Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.

IReadOnlySessionState Interface
Specifies that the target HTTP handler requires only read access to session-state values. This is a marker interface and has no methods.
 
 Example :
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
 
namespace PostmanExamples
{
 
    // IRequireSessionState if you want write access
    public class MyHttpHandlerWithSessionState
        : IHttpHandler, IReadOnlySessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            string s = context.Session["SomeSessionVariable"];
        }
 
        public bools IsReusable { get { return true; } }
    }
}

Session state with web services

 The extra trick needed is on the caller side.  You have to save and store the cookies used by the web service. 

If an XML Web service method uses session state, then a cookie is passed back in the response headers to the XML Web service client that uniquely identifies the session for that XML Web service client. In order for an XML Web service to maintain session state for a client, the client must persist the cookie. Clients can receive the HTTP cookie by creating a new instance of CookieContainer and assigning that to the CookieContainer property of the proxy class before calling the XML Web service method. If you need to maintain session state beyond when the proxy class instance goes out of scope, the client must persist the HTTP cookie between calls to the XML Web service. For instance, a Web Forms client can persist the HTTP cookie by saving the CookieContainer in its own session state. Because not all XML Web services use session state and thus clients are not always required to use theCookieContainer property of a client proxy, the documentation for the XML Web service should state whether session state is used.

See the MSDN documentation on HttpWebClientProtocol.CookieContainer property. 

However, please note if you’re using proxy object to call a web service from your page, the web service and your page cannot share the same session state due to architecture limitation. 

This can be done if you call your web service through redirect. 

Example:

    public class UseWebServiceWithSessionState
    {
        public static void Example()
        {
            // Create a new instance of a proxy class for your XML Web service.
            WebServiceInstance ws = new WebServiceInstance();
            CookieContainer cookieJar;
 
            // Check to see if the cookies have already been saved for this session.
            if (Session["CookieJar"] == null)
                cookieJar = new CookieContainer();
            else
                cookieJar = (CookieContainer)Session["CookieJar"];
 
            // Assign the CookieContainer to the proxy class.
            ws.CookieContainer = cookieJar;
 
            // Invoke an XML Web service method that uses session state and thus cookies.
            int count = ws.PerSessionServiceUsage();
 
            // Store the cookies received in the session state for future retrieval by this session.
            Session["CookieJar"] = cookieJar;
 
            // Populate the text box with the rewslts from the call to the XML Web service method.
            Logger.Log(count.ToString());
        }
 
    }
more info about HttpWebClientProtocol:
http://msdn.microsoft.com/en-us/library/system.web.services.protocols.httpwebclientprotocol(VS.71).aspx

Session_End is not fired

Remarkable Question :
1. Remember Session_End event is supported only in InProc mode.  
2. Session_End won’t be fired if you close your browser. HTTP is a stateless protocol, and the server has no way to know if your browser has closed or not. 
3. Session_End will be fired only (i) after n minutes of inactivity (n = timeout value), or (ii) if someone calls Session.Abandon(). 
4. For case (i) (pt. 3), Session_End will be run by a background thread, which implies:

    a. Your code in Session_End is running using the worker process account. You may have permission problem if you’re accessing resource such as database.
    b. If an error happens in Session_End, it will fail silently.
5. For case (ii), please note that in order for Session_End to be fired, your session state has to exist first.  That means you have to store some data in the session state and has completed at least one request.  
6. Again for case (ii), Session_End will be called only if the abandoned session is actually found. As a result, if you create and abandon a session inside the same request, because the session hasn’t been saved and thus can’t be found, Session_End won’t be called.  This is a bug in v1 and upcoming v1.1.

T-SQL Row_Number() and Paging

In MS SQL 2005 you can use Row_Number() function for paging:

DECLARE @PageNumber AS INT;
DECLARE @PageSize AS INT;
SET @PageNumber = 2;
SET @PageSize = 10;

WITH CustomerCTE AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY LoginDate, CustomerID) AS RowNumber
          ,CustomerID
          ,LoginDate
          ,CustomerID
          ,EmployeeID
      FROM dbo.Customers
)

SELECT *
  FROM CustomerCTE
 WHERE RowNumber BETWEEN (@PageNumber – 1) * @PageSize + 1 AND @PageNumber * @PageSize
 ORDER BY LoginDate , CustomerID;

Disable stop deny web.config inheritance

I find a good article about Configuration Inheritance below:

Each ASP.NET Web Application has its own configuration file called web.config file. 
In fact every directory in ASP.NET application can have one. Settings in each web.config file apply to the pages in the directory where its placed, and all the subdirectories of that directory.This is called 

Configuration Inheritance. 

So if you create an ASP.NET application and set its web.config file, add custom HttpHandlers, UrlRewriting module etc and try to create another ASP.NET Web Application in the subfolder, you can end up having problems because application in the subfolder will inherit all the settings from its parent  web.config.

So if you for example setup UrlRewriter module in your root web applications like this:

      <httpModules>

        <add name=”UrlRewriteModule” type=”UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter”/>

        <add name=”ScriptModule” type=”System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″/>

      </httpModules>

And in your child web application (in subfolder) you are not using UrlRewriteModule, then if you try to run the child Web Application in your browser, you will get error like this:

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. 
Line 88: <httpModules>
Line 89:   <add name="UrlRewriteModule" type="UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter"/>
Line 90:   <add name="ScriptModule" type="System.Web.Handlers.ScriptModule,
          System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
Line 91: </httpModules>

Luckily, there is a easy solution to this problem.

Source Error: 
What happens here is that because UrlRewriteModule is configured in the parent’s folder web.config file, this setting is inherited by the child application’s web.config file, and because of this ASP.NET is looking for the UrlRewriteModule DLL file in the BIN directory, and off course its not there.

First thing you can do is to remove the problematic HttpModule in your child application web.config file using the removecommand like this:

      <httpModules>

        <remove name=”UrlRewriteModule” />

      </httpModules>

This would remove the handler and your application would run fine.
Or you could use <clear/> command like this:

      <httpModules>

        <clear/>

      </httpModules>

This would clear all the HttpModules in your child application.

But what to do when there are many settings in your root web.config file that you don’t want to be propagated to your child applications?

Here is the solution:
With the <location> attribute with inheritInChildApplications set to false in your root web.config file you can restrict configuration inheritance. 
So, by wrapping a section of your web.config file in <location> attribute you can instruct ASP.NET not to inherit those settings to child applications/folders and their web.config files.

In fact  you can wrap the whole <system.web> section in one <location> attribute and disable configuration inheritance so none of the parent settings from <system.web> will be inherited to the child applications you create in subfolders.

Here is how to use this in practice:

  <location path=”.” inheritInChildApplications=”false”>

    <system.web>
    …

    </system.web>   
  </location>

NOTE: Do remember that if you do this, you need to manually insert all the settings you need in the <system.web> for your child applications because none of the settings from the root web.config will be propagated…

Source:
http://www.aspdotnetfaq.com/Faq/how-to-disable-web-config-inheritance-for-child-applications-in-subfolders-in-asp-net.aspx