<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7008996059029054191</id><updated>2012-02-06T11:40:27.488+01:00</updated><category term='asp.net'/><category term='F#'/><title type='text'>Pete's Blog on .NET Development</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://petesdotnet.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7008996059029054191/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://petesdotnet.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Pete</name><uri>http://www.blogger.com/profile/00837792514482633418</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>3</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7008996059029054191.post-3505776038483961852</id><published>2010-07-17T14:39:00.003+02:00</published><updated>2010-07-18T20:53:38.209+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='F#'/><title type='text'>Implementing a simple preprocessor in F# using FsLex</title><content type='html'>&lt;h2&gt;Introduction&lt;/h2&gt;

&lt;p&gt;In this article, I will show how two different lexers can work together to create a tokenizer with preprocessing functionality.&lt;/p&gt;

&lt;p&gt;This is not a perfect solution for implementing the preprocessor used in programming languages like C or C++, but if you have some simpler tasks, this can provide an elegant solution; much simpler than you can achieve by a single lexer/parser pair. In reality this will generate a preprocessing lexer-&gt;tokenizing lexer-&gt;parser pipeline.
&lt;/p&gt;
&lt;p&gt;This article assumes that the reader is familiar with FsLex and FsYacc&lt;/p&gt;

&lt;h2&gt;The problem domain&lt;/h2&gt;

&lt;p&gt;First let me describe the problem that I have, and the need for a preprocessor. The project that I personally have is a case of auto generating code from a single definitions file describing the classes and attributes of the domain. Such a file could look like this:&lt;p&gt;

&lt;pre&gt;
    entity User
        field ID int
        field FirstName string[250]
        field LastName string[250]
        field Email string[250]
        generator DomainObject .\MyProject.Domain
        generator DataAccess .\MyProject.DataAccess
        generator TableScript .\DatabaseScripts\Schemas\dbo\Tables
    end
&lt;/pre&gt;

&lt;p&gt;This file defines that I have a User in my domain model, that I need a domain object (c# class) generated implementing the user; I need a data access object that can save and load a user to/from the database; and I need a table script that can generate a user table in the database. The line&lt;/p&gt;

&lt;pre&gt;
        generator DomainObject .\MyProject.Domain
&lt;/pre&gt;
&lt;p&gt;Defines a type of code generator (DomainObject) and a destination folder (./MyProject.Domain) where the generated file will be saved.&lt;/p&gt;

&lt;p&gt;The three different code generators take care of generating a great deal of trivial code for me, allowing me to concentrate on the important part, domain logic.&lt;/p&gt;

&lt;p&gt;Now let's add another domain object to the script&lt;/p&gt;

&lt;pre&gt;
    entity User
        field ID int
        field FirstName string[250]
        field LastName string[250]
        field Email string[250]
        generator DomainObject .\MyProject.Domain
        generator DataAccess .\MyProject.DataAccess
        generator TableScript .\DatabaseScripts\Schemas\dbo\Tables
    end
    entity UserLog
        field ID int
        field UserID int
        field Action string[250]
        field ActionDate datetime
        generator DomainObject .\MyProject.Domain
        generator DataAccess .\MyProject.DataAccess
        generator TableScript .\DatabaseScripts\Schemas\dbo\Tables
    end
&lt;/pre&gt;

&lt;p&gt;Now, we see some duplications appearing, the same destination folder are being used for the different code generators. If the project is restructured so files will be moved to new folders, the same change will have to be carried out many places. Adding the possibility to define a variable will remove this duplication.&lt;/p&gt;

&lt;pre&gt;
    @DomainOutputFolder=.\MyProject.Domain
    @DataAccessOutputFolder=.\MyProject.DataAccess
    @TableOutputFolder= .\DatabaseScripts\Schemas\dbo\Tables
    entity User
        field ID int
        field FirstName string[250]
        field LastName string[250]
        field Email string[250]
        generator DomainObject $(DomainOutputFolder)
        generator DataAccess $(DataAccessOutputFolder)
        generator TableScript $(TableOutputFolder)
    end
    entity UserLog
        field ID int
        field UserID int
        field Action string[250]
        field ActionDate datetime
        generator DomainObject $(DomainOutputFolder)
        generator DataAccess $(DataAccessOutputFolder)
        generator TableScript $(TableOutputFolder)
    end
&lt;/pre&gt;

&lt;p&gt;Now the output folders are stored in variables, so changing the output folder is a lot easier now. It also gives a better overview of what and where code is generated since the destination folders are placed in the beginning of the file.&lt;/p&gt;

&lt;p&gt;The domain specification script without variables is the format that my tokenizing lexer and parser wants, so the job of my preprocessor is to transform the latter domain specification script with variables to the former script without variables.&lt;/p&gt;

&lt;h2&gt;Implementing the Preprocessor&lt;/h2&gt;

&lt;p&gt;Normally when generating a lexer/parser pair, the lexer emits a series of tokens that the parser can recognize and use to build up an abstract syntax tree. But there is no specification on what type of data the lexer needs to return. It can return integers, strings, or whatever you desire. You can even get the lexer to return an abstract syntax tree directly (with the result that it is completely impossible to understand)&lt;/p&gt;

&lt;p&gt;My solution revolves around a lexer that reads character data and return character data. In order for the output of the preprocessing lexer to be used as an input to the tokenizing lexer, the result must be wrapped in a package that the lexer understands. In this example, I have wrapped the lexer in a TextReader implementation. &lt;/p&gt;

&lt;p&gt;I will start by showing how this is actually used in the project, as it will provide the context in order to more easily understand the solution. Here is first the parsing routine without the preprocessor (I have used the --unicode flag for FsLex, which generates a lexer that operates on char data, not byte data)&lt;/p&gt;

&lt;pre&gt;
let reader = new System.IO.StreamReader (filename)
let lexBuffer = LexBuffer&lt;char&gt;.FromTextReader reader 
Parser.start Lexer.token lexBuffer
&lt;/pre&gt;

&lt;p&gt;Here is the parsing routine with the preprocessor added&lt;/p&gt;

&lt;pre&gt;
let reader = new System.IO.StreamReader (filename)
let preprocessingReader = new PreprocessingTextReader(reader)
let lexBuffer = LexBuffer&lt;char&gt;.FromTextReader preprocessingReader
Parser.start Lexer.token lexBuffer
&lt;/pre&gt;

&lt;p&gt;Notice that the PreprocessingTextReader is simply a decorator pattern. This implies that the preprocessor is usable on other context. The preprocessor simply transform an input text stream.&lt;/p&gt;

&lt;p&gt;The solution thus has two components, a preprocessing lexer, and a specialized TextReader class that uses the preprocessing lexer to deliver the processed result.&lt;/p&gt;

&lt;h3&gt;Preprocessor.fsl&lt;/h3&gt;

&lt;p&gt;Lets first look at the actual preprocessing lexer which make up the core of the preprocessor. This is the component that actually converts the input stream.&lt;/p&gt;

&lt;p&gt;The lexer output is a char array. So every pattern matched should return in an char array. &lt;/p&gt;

&lt;p&gt;First I will show the file, and then go into details with each element. As I said, I assume that the reader is familiar with FsLex and FsYacc, so I will not describe FsLex basics here.&lt;/p&gt;

&lt;pre&gt;
{ 
module Preprocessor
open System.Collections.Generic
open Microsoft.FSharp.Text.Lexing

let variables = new Dictionary&lt;string, string&gt;()

let lexeme = Lexing.LexBuffer&lt;_&gt;.LexemeString

let parseConstant lexbuf =
    let input = lexeme lexbuf
    // Extract "a=b" in "@a=b"
    let s = input.Substring(1)
    let parts = s.Split('=')
    variables.Add(parts.[0], parts.[1])

let resolveConstant lexbuf =
    let input = lexeme lexbuf
    // Extract "xyz" in "$(xyz)"
    let variable = input.Substring(2, input.Length - 3)
    variables.[variable].ToCharArray()
}

let char        = ['a'-'z' 'A'-'Z']   
let identifier = char*
let nonNewlines = [^ '\r' '\n']*

rule preProcess = parse
| eof                           { [||] }
| "@"identifier"="(nonNewlines) { parseConstant lexbuf; [||] }
| "$("identifier")"             { resolveConstant lexbuf }
| _                             { lexbuf.Lexeme }
&lt;/pre&gt;

&lt;p&gt;In order to implement the variables, I must go down the imperative programming style and introduce static mutable data in the lexer in the form of a dictionary that can hold variable names and variable values.&lt;/p&gt;

&lt;pre&gt;
let variables = new Dictionary&lt;string, string&gt;()
&lt;/pre&gt;

&lt;p&gt;Followed by this are two helper functions. The first adds a variable to the dictionary. The second retrieves a variable from the dictionary, and returns it as a char array.&lt;/p&gt;

&lt;pre&gt;
let parseConstant lexbuf =
    let input = lexeme lexbuf
    // Extract "a=b" in "@a=b"
    let s = input.Substring(1)
    let parts = s.Split('=')
    variables.Add(parts.[0], parts.[1])

let resolveConstant lexbuf =
    let input = lexeme lexbuf
    // Extract "xyz" in "$(xyz)"
    let variable = input.Substring(2, input.Length - 3)
    variables.[variable].ToCharArray()
&lt;/pre&gt;

&lt;p&gt;Then comes the lexer rules. The first rule is pretty simple, the end of file indicator simply returns an empty array.&lt;/p&gt;

&lt;pre&gt;
rule preProcess = parse
| eof                           { [||] }
&lt;/pre&gt;

&lt;p&gt;The second rule identifies a variable definition. Upon seeing this, the previously shown helper function parseConstant is called. Note that multiple lexer states could possibly have made this implementation clearer, e.g. eliminating the need for splitting strings and removing the @ character in the parseConstant function. But this implementation doesn't use that. The return value is an empty array.&lt;/p&gt;

&lt;pre&gt;
| "@"identifier"="(nonNewlines) { parseConstant lexbuf; [||] }
&lt;/pre&gt;

&lt;p&gt;The third rule is the one that actually looks up the variable, again using the previously defined helper function.&lt;/p&gt;

&lt;pre&gt;
| "$("identifier")"             { resolveConstant lexbuf }
&lt;/pre&gt;

&lt;p&gt;And last, any other lexeme is returned as is. Because the lexer is generated with the --unicode flag, the lexeme is a char array, and can therefore be returned as is.&lt;/p&gt;

&lt;pre&gt;
| _                             { lexbuf.Lexeme }
&lt;/pre&gt;

&lt;h3&gt;PreprocessingReader.fs&lt;/h3&gt;

&lt;p&gt;The PreprocessingReader class is a specialization of the TextReader
  class that uses the preprocessing lexer and exposes it as a
  TextReader. Seing how the preprocessing lexer was implemented, it is
  clear that the reader should function like this.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The reader has an internal buffer of char data read from the lexer&lt;/li&gt;
&lt;li&gt;When the application reads from the reader, it will return data from the buffer&lt;/li&gt;
&lt;li&gt;If there is no data in the buffer when the application reads from the reader, the reader will read data from the lexer into the buffer first.&lt;/li&gt;
&lt;li&gt;When reading data from the preprocessing lexer into the buffer,
  the function should be able to indicate if we have hit the end of
  file.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The buffer in this case is implemented by a Queue&amp;lt;char&amp;gt; (from the System.Collections.Generic namespace). The buffer is filled by the function chechQueue(). This function will put data in the queue if necessary. The function will return true if there is more data to process, and it will return false, if the queue has been emptied and the preprocessing lexer has passed end of file.&lt;/p&gt;

&lt;p&gt;Since performance is of no concern in this specific application, the implementation is a minimal one, one that simply implements the Read() and Peek() functions.&lt;/p&gt;

&lt;pre&gt;
module PreprocessingReader
open System
open System.IO
open System.Collections.Generic
open Microsoft.FSharp.Text.Lexing

type PreprocessingTextReader (sourceReader: StreamReader) =
    inherit TextReader()

    let reader = sourceReader
    let lexBuffer = LexBuffer&lt;char&gt;.FromTextReader reader
    let queue = new Queue&lt;char&gt;()

    // Checks if there is more data to read. If the queue is empty, it
    // will check if there is more data in the input file, and add it to
    // the queue.
    // If there is more data to process, the function returns true. If
    // all the data in the input file has been processed, the function returns false
    let rec checkQueue () =
        if queue.Count &gt; 0 then
            true
        elif lexBuffer.IsPastEndOfStream then
            false
        else    
            let s = Preprocessor.preProcess lexBuffer
            if (s.Length = 0) then
                checkQueue()
            else
                for c in s do 
                    queue.Enqueue c
                true

    override x.Dispose(disposing) =
        if disposing then reader.Dispose()

    override x.Peek() : int =        
        if checkQueue() then
            queue.Peek() |&gt; Convert.ToInt32
        else
            -1

    override x.Read() : int =        
        if checkQueue() then            
            queue.Dequeue() |&gt; Convert.ToInt32
        else
            -1
&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;I believe that this is an elegant solution to my problem in the context that it is given. But using it in a more complex context could cause problems.&lt;/p&gt;

&lt;p&gt;The first problem with this code is the lack of performance optimization. This implementation reads only a single character at a time. Letting the preprocessor be able to read larger chunks of data at a time would probably yield better performance. But in my case it takes less than a second to execute at compile time if there are changes to the input file, so performance is not a problem here.&lt;/p&gt;

&lt;p&gt;And second, the preprocessor messes up the line numbering. If you are building a compiler and want to show a line number for compilation errors, then a specific line returned by the preprocessor would not necessarily have the same line number in the original file, making it difficult for the user of that compiler to identify where in his/her source code there is a bug.&lt;/p&gt;

&lt;p&gt;And third, there is no handling of looking up a variable that is not defined. This implementation will simple fail with an exception.&lt;/p&gt;

&lt;p&gt;So if you are building advanced parsers and compilers, or are using this to analyze text runtime in a production environment where performance is critical, then you need to resolve those issues before using this type of implementation.&lt;/p&gt;

&lt;p&gt;But if these are not the issues you have, then this is a very simple clean implementation of a preprocessor, where the concerns have been clearly seperated. This preprocessor can easily be extended to implement include files, conditional compilation, and much more. And the preprocessor can easily be used in a different context, it does not need to be used with a parser.&lt;/p&gt;

/Pete&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7008996059029054191-3505776038483961852?l=petesdotnet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://petesdotnet.blogspot.com/feeds/3505776038483961852/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://petesdotnet.blogspot.com/2010/07/implementing-simple-preprocessor-in-f.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7008996059029054191/posts/default/3505776038483961852'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7008996059029054191/posts/default/3505776038483961852'/><link rel='alternate' type='text/html' href='http://petesdotnet.blogspot.com/2010/07/implementing-simple-preprocessor-in-f.html' title='Implementing a simple preprocessor in F# using FsLex'/><author><name>Pete</name><uri>http://www.blogger.com/profile/00837792514482633418</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7008996059029054191.post-2802032810144597161</id><published>2009-09-14T22:25:00.008+02:00</published><updated>2010-07-18T20:54:01.318+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='asp.net'/><title type='text'>Generic Handlers and ASP.NET routing</title><content type='html'>&lt;p&gt;
This article will discuss the use of generic handlers, such as .ashx files, in a web project using ASP.NET routing. 
This is article is based on experience with .NET 4.0 Beta 1 framework. It will probably not apply to .NET 3.5 projects, 
and although I believe the general concept will still be valid in future versions of ASP.NET, the next version may
contain a fix that makes a workaround described here obsolete.
&lt;/p&gt;
&lt;p&gt;
Should any of the functionality described in here be affected by subsequent betas or the final version of .NET 4.0
I will keep this post updated.
&lt;/p&gt;
&lt;h2&gt;The Generic Handler&lt;/h2&gt;
&lt;p&gt;
ASP.NET has long had the option for creating a file that could serve other data than HTML. This could be images
generated dynamically, or files that could come from a binary field in a database, or maybe runtime compression
of javascript files, etc. The uses are many.
&lt;/p&gt;
&lt;p&gt;
The easy way to implement such a generic handler would be to create an .ashx file, and implement the process
request. You could also write a class directly that implements the IHttpHandler interface, and then register
this file with a specific extension for example.
&lt;/p&gt;
&lt;p&gt;
In both cases, you need to implement the &lt;tt&gt;IHttpHandler&lt;/tt&gt; interface.
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
public interface IHttpHandler
{
    void ProcessRequest(HttpContext context);
    bool IsReusable { get; }
}
&lt;/pre&gt;
&lt;p&gt;
The interesting function if &lt;tt&gt;ProcessRequest&lt;/tt&gt; where the implementation writes the actual data,
text or binary, to the output.&lt;/p&gt;
&lt;p&gt;
With the routing feature in .NET 4.0, it would be natural to map a route to either the .ashx file, or just a class
that implements the &lt;tt&gt;IHttpHandler&lt;/tt&gt; interface. The first case is not directly possible unfortunately, but the second
case is very easy to implement. And compared to pre-routing possibilities, you don't need to create mappings in web.config.
&lt;/p&gt;
&lt;p&gt;
I have not really spend a long time investigating the option of getting .ashx files to work with routing
because I'm much more happy with just having a class implementing &lt;tt&gt;IHttpHandler&lt;/tt&gt;. There therefore may be easy
solutions possible for this scenario. But if there was, I wouldn't use them.
&lt;/p&gt;
&lt;h2&gt;Why can't we use .ashx files&lt;/h2&gt;
&lt;p&gt;
In the .NET 4.0 Beta 1 framework you have to add routes to the route table, using 
&lt;pre name="code" class="csharp"&gt;
Routes.Add(string routeName, RouteBase route)
&lt;/pre&gt;
&lt;p&gt;
The &lt;tt&gt;RouteBase&lt;/tt&gt; class is an abstract class in the framework, and there is only one concrete implementation, the
&lt;tt&gt;Route&lt;/tt&gt; class. This class is constructed through one of the constructors:
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
public Route(string url, IRouteHandler routeHandler);
public Route(string url, RouteValueDictionary defaults, IRouteHandler routeHandler);
public Route(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler);
public Route(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler 

routeHandler);
&lt;/pre&gt;
&lt;p&gt;
In every case you need an object that implements &lt;tt&gt;IRouteHandler&lt;/tt&gt;. Again, only one implementation of this interface is implemented, the 

&lt;tt&gt;PageRouteHandler&lt;/tt&gt; that easily routes to an .aspx file. 
This handler does not accept an .ashx file however, as it is not a &lt;tt&gt;Page&lt;/tt&gt;.
&lt;/p&gt;
&lt;p&gt;
So to use .ashx files, you'd need the non-existing &lt;tt&gt;AshxRouteHandler&lt;/tt&gt;. But since I don't miss it, I haven't spend time
investigating how difficult it would be.
&lt;/p&gt;
&lt;h2&gt;Implementing Routes for an IHttpHandler implementation&lt;/h2&gt;
&lt;p&gt;
Since I have dismissed the usage of .ashx files, I will now go into the solution that I use and like, 
creating a route for a class that implements the &lt;tt&gt;IHttpHandler&lt;/tt&gt; interface. To accomplish this, all we need to do is create a class
that implements the &lt;tt&gt;IRouteHandler&lt;/tt&gt;. This interface only has a single function, that is quite easy to implement.
&lt;p&gt;
&lt;pre name="code" class="csharp"&gt;
// This is the actual http handler, the class that should handle the actual requests.
public class MyHandler : IHttpHandler
{
    ...
}

public class MyHandlerRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHandler();
    }
}

// Map the route to extract an image with a specific ID
// This code is added where all the other routes are mapped.
RouteTable.Routes.Add(new Route("Image/{ImageID}", new MyHandlerRouteHandler()));
&lt;/pre&gt;
&lt;p&gt;
That is basically be it. There is a simple problem however. We cannot inspect the route values in our handler. Normally you
would retrieve the route values like this
&lt;pre name="code" class="csharp"&gt;
public class MyHandler
{
    public void ProcessRequest(HttpContext context)
    {
        int imageID = int.Parse((string)context.Request.RequestContext.RouteData.Values["ImageID"]);
    }
}
&lt;/pre&gt;
&lt;p&gt;
The &lt;tt&gt;Request.RequestContext&lt;/tt&gt; property is not initialized however.
&lt;/p&gt;
&lt;p&gt;If you use reflector to reverse engineer and inspect the .NET framework you can see that the &lt;tt&gt;PageRouteHandler&lt;/tt&gt;
class injects this RequestContext
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
public virtual IHttpHandler GetHttpHandler(RequestContext requestContext)
{
    ...
    page.Context.Request.RequestContext = requestContext;
    ...
}
&lt;/pre&gt;
&lt;p&gt;
But because the &lt;tt&gt;RequestContext&lt;/tt&gt; property setter is marked as internal, we cannot do this in our own implementation
of &lt;tt&gt;IHttpHandler&lt;/tt&gt;, so we have to create a workaround for this (or maybe more correctly, a different workaround than the
MS one). I would argue that this behaviour is not logical, and the &lt;tt&gt;RequestContext&lt;/tt&gt; property should be set automatically
by the framework. Hopefully this will be changed before the release. Here is a modified implementation of the above
code that correctly retrieves the route data.
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
public class MyHandler : IHttpHandler
{
    public RequestContext RequestContext { get; set; }
    public void ProcessRequest(HttpContext context)
    {
        int imageID = int.Parse((string)RequestContext.RouteData.Values["ImageID"]);
        ...
    }
}

public class MyHandlerRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHandler() {RequestContext = requestContext};
    }
}
&lt;/pre&gt;

&lt;h2&gt;Generic Solution Without a DI container&lt;/h2&gt;
&lt;p&gt;
Here I will present a solution for a generic route handler so you don't need to create a new route handler class
for each http handler class in the system. This solution has some requirements that are
unnecessary if you are using a DI (Direct Injection) container to control instantiation of your classes.
&lt;/P&gt;
&lt;pre name="code" class="csharp"&gt;
public interface IHttpHandlerBase : IHttpHandler
{
    void RequestContext {get; set; }
}

public class GenericRouteHandler&amp;lt;T&amp;gt; : IRouteHandler
    where T : IHttpHandlerBase, new()
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var retVal = new T();
        retVal.RequestContext = requestContext;
        return retVal;
    }
} 

public class ImageHandler : IHttpHandlerBase
{
   ...
}

// This goes into the route initialization
RouteTable.Routes.Add(new Route("Image/{ImageID}", new GenericRouteHandler&amp;lt;ImageHandler&amp;gt;()));
&lt;/pre&gt;
&lt;h2&gt;Generic solution with a DI container&lt;/h2&gt;
&lt;p&gt;
If you are using a DI container, then you can remove the need for creating a new interface.
It also removes the need for the &lt;tt&gt;where new()&lt;/tt&gt; generic constraint. I prefer using 
&lt;a href="http://structuremap.sourceforge.net/"&gt;StructureMap&lt;/a&gt;
as DI container. Here is my implementation for a generic route handler using StructureMap.
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
public class MyImageHandler : IHttpHandler
{
    RequestContext _requestContext;
    public MyImageHandler(RequestContext requestContext, 
        // Other dependencies that the class needs
        )
    {
        _requestHandler = requestHandler;
        // Store other dependencies
    }
    public void ProcessRequest(HttpContext context)
    {
        ...
    }
}

public class GenericRouteHandler&amp;lt;T&amp;gt; : IRouteHandler
    where T : IHttpHandler
{
    public IHttpHandler(RequestContext requestContext)
    {
        return ObjectFactory.With(requestContext).GetInstance&amp;lt;T&amp;gt;();
    }
}

// Route initialization
RouteTable.Routes.Add(new Route("Image/{ImageID}", new GenericRouteHandler&amp;lt;MyImageHandler&amp;gt;()));
&lt;/pre&gt;
&lt;p&gt;
The &lt;tt&gt;With()&lt;/tt&gt; function tells StructureMap that during this specific
call, this particular instance of the RequestContext should be used for any
constructor parameter of that particular type. This avoids having to create plugin rules
for &lt;tt&gt;RequestContext&lt;/tt&gt; in structure map.
&lt;/p&gt;
&lt;p&gt;
This class, as it is written here, is the one that I use in my own system.
&lt;/p&gt;
&lt;h2&gt;Final Thoughts&lt;/h2&gt;
&lt;p&gt;
I've been working with the ASP.NET 4.0 Beta 1 for some months now, and I really appreciate
the routing feature build in. I find that this works more smoothly than other 3rd party url rewriting
modules that I've investigated. This is likely because there is build in
support in the core of the framework. Some 3rd party url rewriting modules required some
workarounds in order to be able to handle postbacks correctly. With the build in routing
this is never a problem.
&lt;/p&gt;
&lt;p&gt;
And with very little work it is easy to extend this functionlity to not only work with .aspx
pages, but any http handler in the system.
&lt;/p&gt;
&lt;p&gt;
Pete
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7008996059029054191-2802032810144597161?l=petesdotnet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://petesdotnet.blogspot.com/feeds/2802032810144597161/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://petesdotnet.blogspot.com/2009/09/generic-handlers-and-aspnet-routing.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7008996059029054191/posts/default/2802032810144597161'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7008996059029054191/posts/default/2802032810144597161'/><link rel='alternate' type='text/html' href='http://petesdotnet.blogspot.com/2009/09/generic-handlers-and-aspnet-routing.html' title='Generic Handlers and ASP.NET routing'/><author><name>Pete</name><uri>http://www.blogger.com/profile/00837792514482633418</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7008996059029054191.post-2525877024192246578</id><published>2009-08-26T10:54:00.005+02:00</published><updated>2009-08-26T12:11:53.191+02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='asp.net'/><title type='text'>ASP.NET Web forms - Receiving events in a Repeater with ViewState disabled</title><content type='html'>&lt;p&gt;
Welcome to my blog, and my first blog post, ever. I will use this
blog to post information, tips, tricks, patterns, etc. mainly for the
.NET platform.
&lt;/p&gt;
&lt;p&gt;
My first blog post is about overcoming the problem that controls
that can perform postback stops working if you place them inside a
repeater, and the repeater's viewstate is disabled. The page does
post back, but the event is lost. It never arrives at its
destination. A while ago, I created a workaround for this limitation.
It cannot handle all situations, but it can handle those that I find
to be the most common ones.
&lt;/p&gt;
&lt;h2 &gt;The Problem&lt;/h2&gt;
&lt;/p&gt;
Why is the ViewState important for the repeater?
&lt;/p&gt;
&lt;p&gt;
When the browser requests a page, a new instance of the specific
page class is created; and every control that this page contains is
also instantiated, and placed in the page's control tree. When all
initialization logic, event handlers etc have been processed, the
control tree is rendered to HTML, and the instance that was created
is forgotten. When the same user makes a postback, a new fresh
instance is created for every control in the control tree.
&lt;/p&gt;
&lt;p&gt;
The view state is basically a place where the control tree is
serialized to, and deserialized from at post back, to allow
recreating the state of the page after the post back without having
to initialize the page for every post back, avoiding expensive
database operations.
&lt;/p&gt;
&lt;p&gt;
So if for example we have a page with a button and a repeater.
When you click the button, the page does a post back. By
deserializing its state from the view state, the repeater is capable
of recreating its control tree, therefore being able to render the
same HTML again, without having to rebind to the original data.
But the viewstate can take up quite a lot of space in your page.
And say for example that you don't have any buttons on the page, but
you have a button inside the repeater, and when you click the button
you modify the underlying data, thus you have to rebind the repeater
anyway. In this case, you don't need to have the viewstate to render
the same HTML again.
&lt;/p&gt;
&lt;p&gt;
But when you click the button, the ASP.NET framework looks at the
ID of the control that should receive the event, and calls a function
on this control, namely IPostBackEventHandler.RaisePostbackEvent. But
the target for the function is not the repeater itself, but the
button that is located in the control tree inside the repeater. An
because the control tree is not regenerated, there is no one to
receive this event.
&lt;/p&gt;
&lt;h2 &gt;The Workaround&lt;/h2&gt;
&lt;p&gt;
At one project I worked on, we had a page with four repeaters,
each rendering a table with quite a lot of fields. This gave such a
huge viewstate that it was giving performance problems. So I found
this workaround to the problem.
&lt;/p&gt;
&lt;p&gt;
There are two drawbacks to this solutions. You have to place the
repeater inside its own user control. I personally don't really find
this to be a drawback because I always wrap my repeaters inside their
own user controls to better organize the code.
&lt;/p&gt;
&lt;p&gt;
The second drawback is a bit more serious. You cannot just place
any control that has post back events inside the repeater. In fact,
you need to control the event generation yourself. But if your
repeater only does post backs from Button or LinkButton controls,
this should be fairly simple.
&lt;/p&gt;
&lt;p&gt;
The reason why you have to wrap the repeater inside a user control
is because the controls inside the repeater is not capable of
receiving the event; we simply cannot change this fact. Therefore we
must direct the event to a control outside the repeater. That control
happens to be the user control that we are wrapping the repeater in,
thus why we have to wrap it in a user control. This leads to the
second consequence; that you cannot place any control inside a
repeater. This is because controls that fire post back events have a
habit of routing the event to itself. We therefore need to control
the post back javascript code from the user control implementation
itself.
&lt;/p&gt;
&lt;p&gt;
That actually means that we cannot even use Button or LinkButton
controls inside the repeater. But their behavior is very easy to
reproduce, so they are easy to implement in your workaround.
But say that you placed a DatePicker control inside your repeater.
Then you would not be able to use this workaround.
Let's move on to the example:
&lt;/p&gt;
&lt;h2 &gt;The example&lt;/h2&gt;
&lt;/p&gt;
This example is created for .NET 4.0 beta 1. I originally created
this pattern for a .NET 2.0 project, so I know that the pattern works
for earlier versions of the framework, but there might of course be
differences in the implementation.
As I have described, I have the repeater wrapped in a user
control. When you create a new user control, there are basically two
ways to implement the user control:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
The user control has the responsibility of getting data from
the data source, and updating data based on event.
&lt;/li&gt;
&lt;li&gt;
The page (or a presenter in MVP) has the responsibility of
getting data from the data source, and sends the data to the user
control through a public method on this. Button clicks in the
repeater will cause it to raise an event that the page handles, and
updates the underlying data, and tells the repeater to update
itself.
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Option 2 has a more decoupled design, but also more code. As this
post is not about decoupling application logic, but events in a
repeater, my example code will use option 1; the repeater loads data
in Page_Load, and updates data directly, when the event is received.
&lt;/p&gt;
&lt;p&gt;
In my simple example, I load a bunch of objects from a data source
and place them in a repeater-generated table. Each row in the table
has a “delete”-link. Clicking the link will delete the
object and rebind the repeater.
&lt;/p&gt;
&lt;p&gt;
Let's first take a look at my “data source”:
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
namespace RepeaterEvent
{
    public class DataClass
    {
        public int ID { get; set; }
        public string A { get; set; }
        public string B { get; set; }
    }

    public static class DataClassContainer
    {
        public static List&lt;DataClass&gt; Objects;

        public static void Init()
        {
            Objects = new List&lt;DataClass&gt;();
            for (int i = 0; i &lt; 20; i++)
            {
                Objects.Add(new DataClass()
                {
                    ID = i,
                    A = "A" + i,
                    B = "B" + i
                });
            }
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;
The Init() function simply reinitializes the static array, and I
call this function in the Page_Load function in my user control, if
it is not a postback:
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataClassContainer.Init();
        DataRepeater.DataSource = DataClassContainer.Objects;
        DataRepeater.DataBind();
    }
}
&lt;/pre&gt;
&lt;p&gt;
During postbacks, I then modify the Objects collection, and rebind
the repeater to the modified collection.
&lt;/p&gt;
&lt;p&gt;
In my test project, my user control is named RepeaterControl. Here
is the class declaration:
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
namespace RepeaterEvent
{
    public partial class RepeaterControl : UserControl, IPostBackEventHandler
    {
        public void RaisePostBackEvent(string eventArgument)
        {
                ...
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;
The user control implements IPostBackEventHandler so that it may
receive postback events.
&lt;/p&gt;
&lt;p&gt;
As I need to manually generate the event firing code, the
“LinkButton” is replaced by a simple HTML hyperlink. I
use functionality in the .NET framework generate the actual
javascript for me. Let's have a look at the .ascx file.
&lt;/p&gt;
&lt;pre name="code" class="xml"&gt;
&amp;lt;%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RepeaterControl.ascx.cs" Inherits="RepeaterEvent.RepeaterControl" %&amp;gt;
&amp;lt;asp:Repeater runat="server" ID="DataRepeater" EnableViewState="false"&amp;gt;
  &amp;lt;HeaderTemplate&amp;gt;
    &amp;lt;table&amp;gt; &amp;lt;tbody&amp;gt;
  &amp;lt;/HeaderTemplate&amp;gt;
  &amp;lt;FooterTemplate&amp;gt;
    &amp;lt;/tbody&amp;gt; &amp;lt;/table&amp;gt; 
  &amp;lt;/FooterTemplate&amp;gt;
  &amp;lt;ItemTemplate&amp;gt;
    &amp;lt;tr&amp;gt;
      &amp;lt;td&amp;gt;&amp;lt;%# GetA(Container.DataItem) %&amp;gt;&amp;lt;/td&amp;gt;
      &amp;lt;td&amp;gt;&amp;lt;%# GetB(Container.DataItem) %&amp;gt;&amp;lt;/td&amp;gt;
      &amp;lt;td&amp;gt;&amp;lt;a href="&amp;lt;%# GetDeleteScript(Container.DataItem) %&amp;gt;"&amp;gt;Delete&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;
    &amp;lt;/tr&amp;gt;
  &amp;lt;/ItemTemplate&amp;gt;
&amp;lt;/asp:Repeater&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
The GetXYZ functions are functions that I have defined in my code
behind file. I always do this instead of using the Eval function, as
it will provide compile time checking of the properties that I
access. If someone for example removed or renamed a property, they
would receive a compile time error instead of a runtime error.
&lt;/p&gt;
&lt;p&gt;
Here are the three functions.
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
    protected string GetA(object objDataClass)
    {
        var obj = (DataClass)objDataClass;
        return obj.A;
    }
    protected string GetB(object objDataClass)
    {
        var obj = (DataClass)objDataClass;
        return obj.B;
    }
    protected string GetDeleteScript(object objDataClass)
    {
        var obj = (DataClass)objDataClass;
        string eventArgs = "delete:" + obj.ID;
        return Page
            .ClientScript
            .GetPostBackClientHyperlink(
            this, eventArgs);
    }
&lt;/pre&gt;
&lt;p&gt;
As you can see, I use the
Page.ClientScript.GetPostbackClientHyperlink function to generate a
javascript hyperlink, “&lt;a href="javascript:__doPostBack"&gt;javascript:__doPostBack&lt;/a&gt;(...)”
that I can use as the URL for my hyperlink element. The first
parameter is the target for the event. The target for the event is
the user control itself; so we pass “this” as the first
parameter. The second parameter is a string that will be sent to the
RaisePostBackEvent when the link is clicked. I use this format
“delete:{id}” so that I can make something that resembles
the CommandName/CommandArgument behaviour of normal repeater event.
&lt;/p&gt;
&lt;p&gt;
Let's just have a look at the RaisePostbackEvent(...) function:
&lt;/p&gt;
&lt;pre name="code" class="csharp"&gt;
    public void RaisePostBackEvent(string eventArgument)
    {
        string[] args = eventArgument.Split(':');
        string command = args [0];
        string argument = args[1];
        if (command == "delete")
        {
            int id = int.Parse(argument);
            DataClassContainer.Objects.Remove(
                DataClassContainer.Objects.Find(x =&gt; x.ID == id));
            DataRepeater.DataSource = DataClassContainer.Objects;
            DataRepeater.DataBind();
        }
    }
&lt;/pre&gt;
&lt;p&gt;
It simply decodes the argument, and determines what function
should be performed (delete), and which object is the target for this
operation. It then removes it from the “database” and
then rebinds the repeater to the updated data source.
&lt;/p&gt;
&lt;p&gt;
So basically what we have here is something that reproduces the
behaviour of having a LinkButton with a CommandName and a
CommandArgument inside the repeater.
&lt;/p&gt;
&lt;h2 &gt;Conclusion&lt;/h2&gt;
&lt;p&gt;
I have shown you that you can have events fired from inside a
Repeater control, and handle them. But as it's not natively supported
by the framework, there are some limitations. But that said, this
pattern has proved valuable to me in the past, so if you can live
with the limitations, you can chunk off a great part of your view
state. And if you have as much view state as I have had, you can
seriously improve user experience.
&lt;/p&gt;
&lt;p&gt;
As this is my first blog post, I would appreciate comments on how
it is written. Is it too long, too short. Is it clearly
understandable. Were there points I should have focused more on.
Should I have provided more example code?
&lt;/p&gt;
&lt;p&gt;
I have a few ideas for new blog posts, one or two about using
StructureMap in ASP.NET projects, and then I have planned for a long
post on unit testing ASP.NET Web Forms. And I'm talking about real
unit testing, stuff that you can run from NUnit console without being
dependent on a web server. I'm currently writing on that one, but
there is going to be a lot of text. So that will be at least 3
seperate blog posts, maybe more.
&lt;/p&gt;
&lt;p&gt;
I hope you find this useful.
&lt;/p&gt;
&lt;p&gt;
Pete.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7008996059029054191-2525877024192246578?l=petesdotnet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://petesdotnet.blogspot.com/feeds/2525877024192246578/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://petesdotnet.blogspot.com/2009/08/asp.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7008996059029054191/posts/default/2525877024192246578'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7008996059029054191/posts/default/2525877024192246578'/><link rel='alternate' type='text/html' href='http://petesdotnet.blogspot.com/2009/08/asp.html' title='ASP.NET Web forms - Receiving events in a Repeater with ViewState disabled'/><author><name>Pete</name><uri>http://www.blogger.com/profile/00837792514482633418</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry></feed>
