Async Httphandlers in ASP.NET

What is the correct way to create a httphandler that potentially can take time and resources to complete.

Well this article explains it very well:
http://msdn.microsoft.com/en-us/magazine/cc164128.aspx

If you don’t want to read all, you find the best solution in the bottom of the article.

But you can also find the code here, download this library C# Threadpool.

AsyncRequest

class AsyncRequest
{
  private AsyncRequestState _asyncRequestState;

  public AsyncRequest(AsyncRequestState ars)
  {
    _asyncRequestState = ars;
  }

  public void ProcessRequest()
  {
    // This is where the non-cpu-bound activity would take place, such as
    // accessing a Web Service, polling a slow piece of hardware, or
    // performing a lengthy database operation. I put the thread to sleep
    // for two seconds to simulate a lengthy operation.
    Thread.Sleep(2000);

    _asyncRequestState._ctx.Response.Output.Write(
            "AsyncThread, {0}",
            AppDomain.GetCurrentThreadId());

    // tell asp.net I am finished processing this request
    _asyncRequestState.CompleteRequest();
  }
}

AsyncHandler

namespace EssentialAspDotNet.HttpPipeline
{
  // AsyncRequestState and AsyncRequest remain the same
  // as in the previous example

  public class AsyncHandler : IHttpAsyncHandler
  {
    static DevelopMentor.ThreadPool _threadPool;

    static AsyncHandler()
    {
      _threadPool =
        new DevelopMentor.ThreadPool(2, 25, "AsyncPool");
      _threadPool.PropogateCallContext = true;
      _threadPool.PropogateThreadPrincipal = true;
      _threadPool.PropogateHttpContext = true;
      _threadPool.Start();
    }

    public void ProcessRequest(HttpContext ctx)
    {
     // not used
    }

    public bool IsReusable
    {
      get { return false;}
    }

    public IAsyncResult BeginProcessRequest(HttpContext ctx,
                     AsyncCallback cb, object obj)
    {
      AsyncRequestState reqState =
                     new AsyncRequestState(ctx, cb, obj);
      _threadPool.PostRequest(
                     new DevelopMentor.WorkRequestDelegate(ProcessRequest),
                     reqState);

      return reqState;
    }

    public void EndProcessRequest(IAsyncResult ar)
    {
    }

    void ProcessRequest(object state, DateTime requestTime)
    {
      AsyncRequestState reqState = state as AsyncRequestState;

      // Take some time to do it
      Thread.Sleep(2000);

      reqState._ctx.Response.Output.Write(
                   "AsyncThreadPool, {0}",
                    AppDomain.GetCurrentThreadId);

      // tell asp.net you are finished processing this request
      reqState.CompleteRequest();
    }

  }
}

AsyncPage

namespace EssentialAspDotNet.HttpPipeline
{
 public class AsyncPage : Page, IHttpAsyncHandler
  {
    static protected DevelopMentor.ThreadPool _threadPool;

    static AsyncPage()
    {
      _threadPool =
       new DevelopMentor.ThreadPool(2, 25, "AsyncPool");
      _threadPool.PropogateCallContext = true;
      _threadPool.PropogateThreadPrincipal = true;
      _threadPool.PropogateHttpContext = true;
      _threadPool.Start();
    }

    public new void ProcessRequest(HttpContext ctx)
    {
      // not used
    }

    public new bool IsReusable
    {
      get { return false;}
    }

    public IAsyncResult BeginProcessRequest(HttpContext ctx,
                                            AsyncCallback cb, object obj)
    {
      AsyncRequestState reqState =
             new AsyncRequestState(ctx, cb, obj);
      _threadPool.PostRequest(
             new DevelopMentor.WorkRequestDelegate(ProcessRequest),
             reqState);

      return reqState;
    }

    public void EndProcessRequest(IAsyncResult ar)
    {
    }

    void ProcessRequest(object state, DateTime requestTime)
    {
      AsyncRequestState reqState = state as AsyncRequestState;

      // Synchronously call base class Page.ProcessRequest
      // as you are now on a thread pool thread.
      base.ProcessRequest(reqState._ctx);

      // Once complete, call CompleteRequest to finish
      reqState.CompleteRequest();
    }
  }
}

Manually start Visual Studio dev. web server

I needed to manually start the Visual Studio dev. web server for profililng purposes…

The web server is located here:
C:\Program Files (x86)\Common Files\microsoft shared\DevServer\9.0\WebDev.WebServer.EXE

Arguments

/port:<port number> Optional, an unused port number between 1 and 65535.
/path:<physical path> A valid directory where the web application is rooted.
/vpath:<virtual path> Optional, the virtual path or application root in the form of ‘/<app name>’.

Example

C:\Program Files (x86)\Common Files\microsoft shared\DevServer\9.0>
WebDev.WebServer.EXE /port:8080 /path:"C:\Users\Administrator\Documents\Visual Studio 2008\Projects\WebApplication\Compiled" \vpath:"\"

Google Sitemap .NET links

Some links with information about creating a Google Sitemap either directly in XML or via some .NET code.

http://gerardmcgarry.com/blog/creating-a-google-sitemap-aspnet-website

http://www.codeproject.com/KB/aspnet/GoogleSiteMapProvider.aspx

.NET Resource localization

ResourceBlender is open source and works for .NET:

http://www.resourceblender.com/

IETester 0.4.2

Usually when I need to test a HTML design, I use Spoon browsers… but I saw this IE Tester 0.4.2 tool.

This is just to remind me, don’t install, it made the JavaScript of Gmail and other sites fail.

So, stick to Spoon, don’t use IETester 0.4.2.

Posted in Development, Software. Tags: , . No Comments »

Visual Studio 2008 debugging and breakpoints

My development tools are currently Visual Studio 2008, Resharper 4.5, Gallio and Testdriven.NET. But for as long as I have used these tools, my Visual Studio debugger has only worked partly.

The problem

When I inserted some breakpoints in my code, the first one was almost all the time hit. However, when I tried to step through the code, it worked fine for a bout 3-6 steps. But then Visual Studio debugger decided that was enough, and just completed the code.

The good thing was, it forced me to write many unit test cases, but sometimes I really think it is nice to visually see the state of your objects, in the code.

I have spoken to colleagues, and tested with different combinations of Gallio, Testdriven.NET and Re-sharper enabled, as I thought they cased the problem. But the debugger just kept bugging me. I had actually given up finding a solution to this problem, thinking that Visual Studio 2010 would fix it.

The solution

So finally, in a complete other context, I stumbled upon this page:

http://code.msdn.microsoft.com/KB957912

And thought…. that title sounds interesting… I quickly moved to the KB article, and started to read. I thought, that sounds exactly as my problem.

With nothing to loose I installed the update, and started to test the debugger… until now it seems to work :)

- please note, I do not use the debugger that often as I write very reliable code :)

NHibernate Fluent Criteria

– Updated on the 2. January 2010

I have been using NHibernate for some time now, and I am very satisfied with the functionality it provides. However, I do really not like “magic strings” as these makes the code resistent to refactoring.

NHibernate makes use of “magic strings” when doing a query using HQL or the Criteria API. I tend to use the Criteria API as this, opposed to HQL, limits the logic encompassed in “magic strings”.

As I mostly use the Criteria API, I thought, why not do something about it :)  So I did. Very quickly a Fluent Criteria interface was implemented. Here is how it is used:

var email = "email@email.com";
var customerType = CustomerType.Default;

var result = nhSession.Criteria<Customer>()
             .Add.Equals(x => x.Email, email)
             .Add.Equals(x => x.Type, customerType)
             .Order.Desc(x => x.Created)
             .NHCriteria
                 .SetMaxResults(1)
                 .UniqueResult<Customer>();

In this line we call the extension method Criteria with Customer as a generic argument:

var result = nhSession.Criteria<Customer>()

By doing so we of the alternate Fluent Criteria API I have implemented. Currently it is only some of the Restrictions and Order classes that have been implemented, but you are free to use these classes and extend them as you wish.

By calling the NHCriteria property, you get the normal NHibernate criteria API, so here you can set the cache options, max results, etc.

Download the source code here http://ovesen.codeplex.com/wikipage?title=NHibernateFluentCriteria&referringTitle=Home

Happy New Year btw :)

Memoryleaks with WinDbg

I have experienced the first major project with a memory leak problem… and how do one get started with Memory leak finding.

It is a tough task and the learning curve is quite steep.

You have to get to know the WinDbg. You can start here: http://blogs.msdn.com/tess/pages/net-debugging-demos-information-and-setup-instructions.aspx

Tess Ferrandez has some very nice “Debugging labs”, well take a look at: http://blogs.msdn.com/tess/

If you have a problem with a memory leak, take a look at his one:

http://blogs.msdn.com/tess/archive/2005/11/25/496899.aspx

Posted in Development. Tags: , , . 5 Comments »

Using Multiple Configuration files for NHibernate (HybridSessionBuilder)

 

I have been using Castle Windsor and NHibernate for some months now, so I am a bit new and still learning. But then again, it is learning developers like me, that asks all the questions.

This post is also written because of a simple question: Does the HybridSessionBuilder support multiple configurations?

Why this question? Well, I have a project where some repositories uses one database and some other uses another database.

Original implementation

My little journey started out with my looking original implementation of the HybridSessionBuilder (HSB). You can read about the original implementation here:

http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/

But as you can see:image

The original implementation used a static session factory and session, so this is does not support multiple configurations.

CodeCampServer/Tarantino

I then found out that the CodeCampServer also was using the HSB. Hoping to find an implementation that supported my request, I then started to read the source code.

But by viewing the source code for CodeCampServer I soon found out that the code, for the HSB, had been updated to support multiple factories and sessions. Yeeeaaaaa :)

Furthermore I found out that the HSB now is a part of a collection of libraries called Tarantino.

I was happy, the HybridSessionBuilder now supported my requests, and it was ready to be used in my projects. I thought.

Test web application

image Then I build a small test web application project. It used Castle Windsor (for dependency injection) and NHibernate. I quickly configured Castle Windsor and made two NHibernate configuration files.

nhibernate.cfg.xml used this connection string:

Data Source=localhost\sqlexpress;Initial Catalog=DB1;Integrated Security=true

nhibernate2.cfg.xml used this connection string:

Data Source=localhost\sqlexpress;Initial Catalog=DB2;Integrated Security=true

My windsor.config.xml looks like this:

<component id="firstRepository" type="HybridSessionBuilderTest.FirstRepository, HybridSessionBuilderTest">
  <parameters>
    <ConfigurationFile>hibernate.cfg.xml</ConfigurationFile>
  </parameters>
</component>
 
<component id="secondRepository" type="HybridSessionBuilderTest.SecondRepository, HybridSessionBuilderTest">
  <parameters>
    <ConfigurationFile>hibernate2.cfg.xml</ConfigurationFile>
  </parameters>
</component>

It basically just configures the two repositories with each own configuration.

But to my surprise, it did not work. I made a small page that prints the connection string of each of the repositories:

image

Only the default NHibernate configuration file was used.

Bug or feature?

That was not the output I was looking for, so to find the problem, I did some more test and dug into the code.

I was expecting an object structure like this:

image

But I got something like this:

image  I identified the following method to be the central, when the session was instantiated:

   1: private ISession getExistingOrNewSession(ISessionFactory factory, string configurationFile)
   2:         {
   3:             if (HttpContext.Current != null)
   4:             {
   5:                 var session = GetExistingWebSession();
   6:  
   7:                 if (session == null || !session.IsOpen)
   8:                 {
   9:                     session = openSessionAndAddToContext(factory, configurationFile);
  10:                 }
  11:  
  12:                 return session;
  13:             }
  14:  
  15:             var currentSession = _currentSessions.ContainsKey(configurationFile)
  16:                                     ? _currentSessions[configurationFile]
  17:                                     : null;
  18:             if (currentSession == null || !currentSession.IsOpen)
  19:             {
  20:                 _currentSessions[configurationFile] = OpenSession(factory);
  21:             }
  22:  
  23:             return _currentSessions[configurationFile];
  24:         }

Patch/solution

The problem I identified is line #5. It returns the existing session based on the default configuration, no matter what you specify in the configurationFile parameter.

I changed it to:

   1: var session = GetExistingWebSession(configurationFile);

 

And tadaaa:

image

The second repository now uses the second configuration file :)

Conclusion

You might ask, why I spend time writing a blog post describing this little change to the HybridSessionBuilder.

First of all, having a HSB that can use multiple configurations is rather important to me and the projects I am working on.

Second of all, as NHibernate and Castle Windsor is still a bit new to me, one of the best ways to learn its capabilities and how to use it, is to dig in deep. And that is exactly what I have done.

And BTW – I have not just learned about HSB, but also CodeCampServer, Tarantino, S#arp and how it handles multiple configurations, and how it all works together.

NHibernateSessionModule

Please note. Before my change is used, you need to also update the NHibernateSessionModule. It does currently not dispose all the sessions that are opened.

Posted in Development. Tags: , , . No Comments »

Multiple Configurations for NHibernate using HybridSessionBuilder

 

I have been using Castle Windsor and NHibernate for some months now, so I am a bit new and still learning. But then again, it is learning developers like me, that asks all the questions.

This post is also written because of a simple question: Does the HybridSessionBuilder support multiple configurations?

Why this question? Well, I have a project where some repositories uses one database and some other uses another database.

Original implementation

My little journey started out with my looking original implementation of the HybridSessionBuilder (HSB). You can read about the original implementation here:

http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/

But as you can see:image

The original implementation used a static session factory and session, so this is does not support multiple configurations.

CodeCampServer/Tarantino

I then found out that the CodeCampServer also was using the HSB. Hoping to find an implementation that supported my request, I then started to read the source code.

But by viewing the source code for CodeCampServer I soon found out that the code, for the HSB, had been updated to support multiple factories and sessions. Yeeeaaaaa :)

Furthermore I found out that the HSB now is a part of a collection of libraries called Tarantino.

I was happy, the HybridSessionBuilder now supported my requests, and it was ready to be used in my projects. I thought.

Test web application

image Then I build a small test web application project. It used Castle Windsor (for dependency injection) and NHibernate. I quickly configured Castle Windsor and made two NHibernate configuration files.

nhibernate.cfg.xml used this connection string:

Data Source=localhost\sqlexpress;Initial Catalog=DB1;Integrated Security=true

nhibernate2.cfg.xml used this connection string:

Data Source=localhost\sqlexpress;Initial Catalog=DB2;Integrated Security=true

My windsor.config.xml looks like this:

<component id="firstRepository" type="HybridSessionBuilderTest.FirstRepository, HybridSessionBuilderTest">
  <parameters>
    <ConfigurationFile>hibernate.cfg.xml</ConfigurationFile>
  </parameters>
</component>
 
<component id="secondRepository" type="HybridSessionBuilderTest.SecondRepository, HybridSessionBuilderTest">
  <parameters>
    <ConfigurationFile>hibernate2.cfg.xml</ConfigurationFile>
  </parameters>
</component>

 

It basically just configures the two repositories with each own configuration.

But to my surprise, it did not work. I made a small page that prints the connection string of each of the repositories:

image

Only the default NHibernate configuration file was used.

Bug or feature?

That was not the output I was looking for, so to find the problem, I did some more test and dug into the code.

I was expecting an object structure like this:

image

But I got something like this:

image  I identified the following method to be the central, when the session was instantiated:

   1: private ISession getExistingOrNewSession(ISessionFactory factory, string configurationFile)
   2:         {
   3:             if (HttpContext.Current != null)
   4:             {
   5:                 var session = GetExistingWebSession();
   6: 
   7:                 if (session == null || !session.IsOpen)
   8:                 {
   9:                     session = openSessionAndAddToContext(factory, configurationFile);
  10:                 }
  11: 
  12:                 return session;
  13:             }
  14: 
  15:             var currentSession = _currentSessions.ContainsKey(configurationFile)
  16:                                     ? _currentSessions[configurationFile]
  17:                                     : null;
  18:             if (currentSession == null || !currentSession.IsOpen)
  19:             {
  20:                 _currentSessions[configurationFile] = OpenSession(factory);
  21:             }
  22: 
  23:             return _currentSessions[configurationFile];
  24:         }

Patch/solution

The problem I identified is line #5. It returns the existing session based on the default configuration, no matter what you specify in the configurationFile parameter.

I changed it to:

   1: var session = GetExistingWebSession(configurationFile);

 

And tadaaa:

image

The second repository now uses the second configuration file :)

Conclusion

You might ask, why I spend time writing a blog post describing this little change to the HybridSessionBuilder.

First of all, having a HSB that can use multiple configurations is rather important to me and the projects I am working on.

Second of all, as NHibernate and Castle Windsor is still a bit new to me, one of the best ways to learn its capabilities and how to use it, is to dig in deep. And that is exactly what I have done.

And BTW – I have not just learned about HSB, but also CodeCampServer, Tarantino, S#arp and how it handles multiple configurations, and how it all works together.

Posted in Development. Tags: , . No Comments »