July 2008 - Posts

It's official: I'm on vacations!
Thu, Jul 31 2008 23:26

So, don't expect too many updates on the next month :)

by luisabreu | with no comments
Filed under:
My favourite TV series
Thu, Jul 31 2008 15:25

Ok, since today is my last day at work before vacations, I’ve though that it would be a great time to relax and since I was talking with a friend of mine about TV series, I thought that I should publish my top 6 TV series of all time, starting from 6 to 1.

6. Frasier

One of the best comedy series of all times. So good that I’ve ordered it from the UK recently. After all, it did in 3 golden globes…

5. Everwood

Really a great suprise. Unlike most of the other entries on this list, this is not a comedy. Unfortunately, this is one of those series that I’ve managed to watch several times on TV (FOX) but that I won’t be able to buy in DVD (unfortunately, they’ve decided not to release it in DVD).

4. House M.D.

Really really cool show…I’ve known Hugh Laurie since the Black Adder series and it was weird seeing that it took him so long to achieve start status…

3. How I met your Mother

What a spectacular comedy. Really! Just look how it made straight to number 3 :) Here in Portugal, FOX live is still passing the show, so I’ve reserved 30 mins a day to see it. Really, really funny stuff! Highly recommended…

2. Lost

What can I say? Really…this is the only TV series I know that has so many fans. The plot is really ellaborate and you can’t seem to get enough of it…at least, I can’t!

1. Black Adder

Classic! To me, the best series of all times. Rowan Atkinson (probably more know as Bean) is superb and the result is a show full of irony where you simply can’t stop laughing. I’ve watched the series (I only have 4) several times and they’re always funny. I’m not sure if it will ever leave number 1 spot on my favorite TV series list!

by luisabreu | 5 comment(s)
Filed under:
The MVC framework – the TempData property
Thu, Jul 31 2008 14:58

As we’ve seen in the last post of the series, the MVC platform introduced the notion of “request associated data” by creating the TempDataDictionary which can be accessed through the Controller’s TempData property. As we’ve discussed, the data you put in that dictionary will only “survive” a single request. What this means is that the data you add to the dictionary will only be there on the second request that comes in after it was added to the dictionary. It’s not there on the third! Here’s an example that might explain how it works:

  • You add some info to the TempData property of your controller;
  • The controller finishes its processing and sends back the response (recall from the previous post that at the end of the processing the TempData dictionary is persisted by the current TempData provider);
  • A new request is processed by a controller (doesn’t have to be the same controller that was responsible for setting the TempData) and the TempData is recovered by the current provider.
  • This request ends and TempData is saved. It’s important to understand that only those items that have been “changed” (or “touched”) will be saved. For instance, if during the 1st processing you add two elements to the TempData and then, on the 2nd, you change the values of only one of those entries, then only that item will be available on the third request!

As you can see, this “protocol” is really cool for keeping values that you might need on a second request. Generally, you’ll see lots of examples where TempData is used to keep info you’re putting on a form so that you can recover it quickly on a second request if the user has introduced incorrect data. In my experiences, I’ve noticed that TempData is also cool for:

  • pagination: suppose you have a search page and you only want to show x items at once. You can use TempData to save the search words while the user goes through all the pages;
  • passing data between controllers: this works really well when you’re redirecting from one controller to another and you need to pass out-of-band information.

I’m sure that there might be quite some more uses for it, but these are two I’ve used with success in the recent past (ok, ok, I admit it! In these last 2/3 weeks :) ).

As you might expect from such a modular platform, the TempDataDictionary isn’t really be responsible for saving/loading those dirty entries (though it does expose the expected Load and Save methods in preview 4). That work is done by a type that implements the ITempDataProvider interface. Currently, this interface defines the following contract:

public interface ITempDataProvider
{
    TempDataDictionary LoadTempData();
    void SaveTempData(TempDataDictionary tempDataDictionary);
}

The preview 4 of the ASP.NET MVC platform defines a single ITempDataProvider: the SessionStateTempDataProvider class. This is really a simple class. The only thing it does is add an entry to the session (named  __ControllerTempData) which points to the TempDataDictionary maintained on the TempData property of the controller.

In practice, this means that if you want to use this property you must ensure that you’ve enabled session state (by default, the MvcHandler does that; so, if you’re creating your own handler and you want to reuse the “Controller logic”, don’t forget to add the IRequiresSessionState interface to your handler). As you might also expect, if you change the default session provider, you might need to garantee that the items you’re adding to the TempDataDictionary are serializable.

If you really don’t want to rely on session state, you can also implement your own temp data serializer by implementing the ITempDataProvider interface. After doing that, just pass an instance of that type to the TempDataProvider property of your controller.

Before ending the post, I’d like to point you to one custom error that I’ve seen pop up once or twice on the MVC forums. The dreaded “The provider requires SessionState to be enabled”. Ok, if you’re developing a custom HTTP handler, this means that you’ve forgot to add the IRequiresSessionState interface to the implementation list of your class.

What might be more intriguing is getting this error without using a custom HTTP handler. For instance, look at this example…As you can see, the problem is that he was trying to use a singleton controller and that would really break everything up! As you can see, there are really several things which might lead you to  a session error…

On the next posts, I’ll keep talking about the MVC framework. Keep tuned!

by luisabreu | 1 comment(s)
Filed under: ,
The MVC framework – the Controller lifecycle
Thu, Jul 31 2008 11:52

In my last post,we’ve seen how the MvcRouteHandler creates an IController instance that is responsible for processing the current request. Today I’ll keep talking about the MVC platform and we’re going to step through the tipical controller lifecycle.

When you build a new controller, you end up extending the System.Web.Mvc.Controller class. This class implements several interfaces. The IController is a special interface and it’s the one you need to implement if you don’t want to reuse the behavior of the Controller class. This interface has only one method:

public interface IController
{
    void Execute(ControllerContext controllerContext);
}

Currently, the Controller class implements the Execute method by perfoming the following actions:

  • initializes the ControllerContext property with the parameter passed to the method (do notice that the ControllerContext extends the RequestContext class by adding a new property – called Controller – which will let you get a reference to the controller that is handling the request. Yes, I guess that you won’t really be using this property from within a controller, but do notice that this class is extended – more about this in future posts - and this property might be usefull when you’re not in the controller scope);
  • initializes the TempData by using the currently set TempDataProvider. TempData is a just a temporary dictionary which, by default, is persisted on the current session state. Keep in mind that you can create your own TempDataProvider, which is responsible for persisting the data wherever you want.The only thing you shoudl keep in mind about TempData is that the data you put there will only be persisted (ie, saved) between two consecutive requests;
  • Gets a reference to the current action (by getting the value of the action parameter from the current RouteData);
  • Gets a reference to an instance of the ControllerActionInvoker and calls its InvokeAction to start the “real” processing of the current request. As we’ll see in a future post, this class is responsible for doing most of the work associated with the response that is returned to the client (ie, it will end up calling your controller methods and filters);
  • Saves the TempData dictionary.

As you can see, the  basic lifecycle of the controller is not really complicated. There are still some more details which I didn’t mention in the previous lists. For instance, you must have noticed that I mentioned that the ControllerActionInvoker class ends up calling your controller methods and *filters*. Filters? Yeah, filters. You can see filters as a way of intercepting the “normal” execution of a controller action, at different stages.

Currently, and as you might expect, there are several types of filters. Do notice that the advantage of creating your own filters is that you’ll end up creating classes that can be reused across different controllers (and even different projects). If you just need to perform a specific operation on a particular case, you can follow another approach: instead of creating a filter, you can rely on the fact that the Controller class implements most of the “filter interfaces”. This means that  you can simply override the necessary methods and add the code you want there.

On the other hand, if you’re into filters (and I’ll have more to say about this), then you’re supposed to build custom attributes which can be applied to your controller class or your controller’s methods. For instance, if you’re interested in acting before or after a specific controller action is executed, then you can simply extend the  ActionFilterAttribute type and override the methods you’re interested in. After doing that, you just need to apply that custom attribute to the controller (or method) you want.

And that’s it: this is the basic lifecycle of the Controller class. On the next post, we’ll keep talking about some of the internal details that haven’t been mentioned here. There are still lots of things to talk about, so stay tuned!

by luisabreu | with no comments
Filed under: ,
Routes and namespaces
Wed, Jul 30 2008 23:15

As I've said in one of my previous posts, you can have 2 controllers with the same name, but on different namespaces. The problem with this approach is that you'll only be able to get a route by specifying its name. So, if you don't want to use a name or if you can't (for instance, if you're using the HtmlHelper.ActionLink, which simply doesn't let you specify a name), you're out of luck.

Steve Sanderson extended the Route class so that you can indicate a namespace when trying to get a route by controller name from the route collection. It's still a bit rough, but it should point you on the right direction.

by luisabreu | 1 comment(s)
Filed under: ,
ASP.NET MVC: we need a declarative control model
Wed, Jul 30 2008 14:34

Yes, I’ve been asking this for some time now…in fact, this is the only thing I miss from the traditional ASP.NET Web Forms model. Those clear aspx pages, with really few <%%> crap (oopss, I mean tags) springled through out my pages – the only place I did need them was inside templates.

Notice that I’m not asking for viewstate or postback events. No, no, no! I don’t want that! What I want is to put something like this:

<div id=”mySpan” runat=”server”>Hello, world!</div>

And be able to access them from the codebehind page. This would lead to much cleaner pages…btw, and since 'I’m asking, I’d like to make it clear that I don’t want that ID based on container generation “thingy” either! Ok, now that I’ve made the complaint of the day, it’s time to go back to business…

by luisabreu | 2 comment(s)
Filed under: ,
More C# style trivia
Mon, Jul 28 2008 12:31

In one of my last posts, I’ve said that I didn’t like the new recommendation of not using _ to prefix member fields. At the time, we all seem to agree that using hungarian was really a bad thing. So, I’ve searched the web and I’m putting here a link on the use of Hungarian notation by the man himself.

Interestingly, the article seems to confirm that most guys got it wrong (including the Petzolds’ book). My favourite quote is

But to me the question was always less “what the names should be?” but rather “what are the things that should be named?”

Even if you don’t agree with hungarian (I’m not a hungarian “believer”), I think that reading the article will give you another perspective on the subject.

by luisabreu | with no comments
Filed under: ,
Book review: Powershell pocket reference
Mon, Jul 28 2008 10:52

[Disclaimer: I’ve received a copy of this book for review]

I’m really happy to  have received a copy of this book. It’s really a simple, easy to read, concise book which contains all you need to get started with PowerShell. You can easy read the book in 1 or 2 days (that is, if you’re reading from cover to cover). If you’re near a computer, then you can always try to run the examples and even try some new things on your own (being a concise book, you’ll find lots of references which you need to explore).

As you might expect, this is not a complete guide to Powershell. You won’t also be getting info on how to build custom cmdlets or on how to extend Powershell.

Overall, I’d say this is a good reference book that you should have by your side if you’re starting working with Powershell. I’m giving it 7/10.

by luisabreu | with no comments
Filed under:
Still on getting info about the current Route
Thu, Jul 24 2008 12:25

In one of my previous posts, I’ve showed how you could access the Values property of the RouteData class to get info about the current controller and action. What I forgot to mention at the time was that you should use the GetRequiredString method to get the url parameter values that must be filled when you request a specific route. That means that I should have written the following code:

var controllerName = route.GetRequiredString( "controller" );
var actionName = route.GetRequiredString( "action" );

instead of the code that I presented on that post.
by luisabreu | with no comments
Filed under: ,
The MVC framework – the MvcHandler, the IControllerFactory and the ControllerBuilder types
Thu, Jul 24 2008 12:20

As we’ve seen in the previous post, all “MVC routing requests” are handled by the MvcRouteHandler class which will simply return an instance of the MvcHandler type. The MvcHandler is an IHttpHandler which is responsible for creating other classes that end up handling the current request and processing its response.

This handler doesn’t create an instance of the controller directly as you might think! Instead, it will try to get a reference to an IControllerFactory element, which will be responsible for creating a IController instance (in other words, the MvcHandler creates the controller that will handle the request though a controller builder). If you look at the ProcessRequest method, you’ll see that it uses the static GetControllerFactory method of the ControllerBuilder class for getting a reference to an IControllerFactory:

IControllerFactory factory = ControllerBuilder.GetControllerFactory();

The ControllerBuilder class is interesting and it gives you another extensibility point: you can use its static Current property to get a reference to the current builder instance and then call the SetControllerFactory method to setup the factory that will end up creating the controller that handles the request (as you might expect, if you do this, the GetControllerFactory method will return an instance of that custom factory).

Instead of wasting time writing about how you can customize the factory, I’ll simply point you to Fredrik Normen’s post on that subject (the only thing I’d like to add is that I’ve used this solution in some dummy MVC apps and it is really great when you’re using IOC).

The IControllerFactory interface defines a contract with two methods:

public interface IControllerFactory {
  IController CreateController(RequestContext context,
                                                                    string controllerName);
  void DisposeController(IController controller);
}

As you can see, the factory receives the current RequestContext and the controller name, which is recovered by the MvcHandler during the initial phase of the ProcessRequest method (it uses the GetRequiredString instance method of the RouteData class to get that info). As you might expect, the DisposeController method ends up getting called at the end of the request and you can use it to do some cleanup (if you need to).

If you don’t build your own controller factory, you’ll end up getting a default factory: an instance of the DefaultControllerFactory class.  The first thing this class does is recover the type of the controller that should handle the current request. It first tries to get a list of namespaces defined on a “custom” Namespaces entry available on the DataTokens property of the current route. If it doesn’t find any match, then it tries to search in the namespaces collection of the associated controller builder instance. And finally, if it didn’t find any matches in the previous attempts, it will simply try to look in all the available namespaces.

What this means is that you can now have controllers with the same name, in different namespaces and you can hint the factory about which controller should be instantiated to handle a specific route request (as you’ve seen, this can be done when creating the route or by customizing the associated controller builder). Do notice that if you do this (ie, build several controllers with the same name) you’ll need to define the namespace associated to each route. If you don’t and get multiple controllers, you’ll end up getting an exception.

As you might expect, the DefaultControllerFactory relies heavily on reflection to perform its work. If it had to handle to discover all the controllers during all the calls, you’d really have ppor performance! Instead, it relies on the ControllerTypeCache class to discover and cache all the controller types available on all the assemblies “loaded” by the web app. So, at the end of the day, the ControllerTypeCache does all the hard work of getting the controller types and enforces the convention that controller type names should end up with “Controller”.

After getting the controller from the factory, the handler will call the Execute method and pass it the current context. In the next post we’ll keep following the handling of an MVC request. Keep tuned.

by luisabreu | with no comments
Filed under: ,
Getting information about the current Route
Thu, Jul 24 2008 10:41

One of the things I needed when I started playing with ASP.NET MVC is getting info about the current Route. That’s easy when you’re on the controller, but what happens when you need that info on a module?

In these scenarios, the easiest way of achieving this is getting a reference to the current HttpContext, wrapping it up on an instance of type HttpContextWrapper and then passing it to GetRouteData method of the existing route collection. Here’s some demo code that does just that:

var route = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
var controllerName = route.Values["controller"];
var actionName = route.Values["action"];

After getting the RouteData associated with the current request, you can easilly get all the information associated with the current route. In this case, I’ve just recovered the current controller and action which had been set as parameter variables on the url pattern. Not hard, right?

by luisabreu | with no comments
Filed under: ,
Book review: Professional IIS 7 and ASP.NET Integrated Programming
Wed, Jul 23 2008 12:24

[Disclaimer: I’ve received a copy of this book for review]

I’ve just finished reading the Professional IIS 7 and ASP.NET integrated programming book by Dr. Shramram. If you’re trying to understand how to leverage the new IIS 7 managed features, then this book is just what you need. If you don’t know what you must to to add a GUI interface to your own custom modules/handlers, then this book is for you too!If you want to learn how to administer IIS 7, then this book isn’t for you.

The book is really complete (in fact, it’s too complete, if such a thing exists – more details on this in the next paragraphs) reference that contains lots of examples that show you how to integrate your ASP.NET code with IIS 7 and how to extend IIS 7.  Having said this, I’ve found one or two things that annoyed me while I read the book.

For starterts, you’ll see lots of C# 2.0 code. Why not use C# 3.0? It simply doesn’t make sense to me, but ok, I can live with that…The second thing that I really didn’t like is the ammount of repetition that you’ll get in the book. For instance, you’ll get at least one chapter on how to extend the integrated configuration system which are illustrated with “dummy” classes. And then, in a following chapter you’ll end up developing “real” config classes for supporting an url module. My question is simple: why not build the necessary config classes for the module instead of “wasting” paper with the dummy classes?

And since I’m talking about repetitions, there’s really one thing I hated: why do we see pages of code which are repeated under the form of snippets so that the author can explain what each one of them do? Including the InitializeComponents is really really uncessary, if you ask me…

In conclusion, this book will give all you need if you’re interested in understanding how to integrate your ASP.NET code with IIS 7 or if you’re interested in seeing how to expand IIS 7. I’m giving it a 7.5/10 due to the ammount of unnecessary repetition that the book contains. If it weren’t for that, I wouldn’t have any problems in giving it an 8, but I can’t simply ignore the fact that this book has over 600 pages and it could really just have about 400 without any content loss!

by luisabreu | 2 comment(s)
Filed under:
The MVC framework – the MvcRouteHandler
Wed, Jul 23 2008 11:46

As we’ve seen in the previous post, by default you’ll end up using the MvcRouteHandler class for setting up the handler that will return the HTTP response to the client. As you can see (by looking at the code), the GetHttpHandler will only return a new MvcHandler and pass it the current RequestContext. If this class is really simple, then why am I talking about it here? I’m doing that because this is the first class of the MVC pipeline that you can replace if you’re not interested in using the default MVC handler.

When will you want to replace this class? Whenever you think that having a “simple” handler is more than enough for a specific request. For instance, if you think that creating an MvcHandler is just too much for getting the bytes of an image that are stored on the db or you just want to reuse and old handler you’ve built for that, then you can simply create your own IRouteHandler class and implement it so that it returns the handler you want.

A quick example should make this really easy to understand. Lets suppose you’ve got a ImageHandler class that looks like this:

public class ImageHandler:IHttpHandler
{
  //code that implements the interface and gets the image from
  //the database
  //note: remember that you can receive an instance of the RequestContext 
  //class so that you can easilly recover
  //the parameters from a user-friendlier url.
  //the best way of passing this RequestContext to your class
  //is (probably) to define a constructor that receives a reference to
  //an item of that type.
  public ImageHandler(RequestContext context)
  {
     //more code
  }
}

Now, you just need to create your own route handler that creates elements of this type. Here’s a simple class that does just that:

public class ImageRouteHandler: IRouteHandler
{
  IHttpHandler IRouteHandler.GetHttpHandler(RequestContext context)
  {
      return GetHttpHandler(context);
  }

  protected virtual IHttpHandler GetHttpHandler(RequestContext context)
  {
     return new ImageHandler( context );
  }
}

Now, the only thing you need is to set it up a route so that the requests get forwarded to our new route handler:

var route = new Route ( “images/{name}”, new ImageRouteHandler() );
routes.Add( “images”, route);

If you really feel like it, you can also add a new extension method that will do that for you:

public static class MyRouteCollectionExtensions
{
   public static void MapImageRoute( this RouteCollection routes, String name, String url)
  {
     var route =  new Route ( url, new ImageRouteHandler() );
     route.Add( name, route);
  }
}

And then, you could simply add a route by writing the following:

routes.MapImageRoute( “images”, “images/{name}” );

where routes is a reference to an existing RouteCollection (which you’ll normally get from the RouteTable.Routes property). You could add more overloads that would handle default values and constraints (for more info on these, check my routing series), but I thought that the current code was more than enough for helping you get started building your own handlers.

And that’s all for today. On the next post, I’ll start looking at the MvcHandler and we’ll see how it accomplishes all the stuff

by luisabreu | 4 comment(s)
Filed under: ,
Loads cannot pass other loads...or can they?
Thu, Jul 17 2008 22:17

Great post by Joe Duffy (does this guy ever sleep???) which points to a somewhat disturbing fact regarding some of the conventions taken as granted today...want to know what I'm talking about? Then go read it ASAP!

by luisabreu | with no comments
Filed under:
ASP.NET MVC Preview 4 is out
Wed, Jul 16 2008 22:51

And you can get it from codeplex.

by luisabreu | with no comments
Filed under: ,
Opera 9.5: finally with a good enough debugger for JS
Tue, Jul 15 2008 23:28

In these last days I've finally upgraded to Opera 9.51. I've always been a Opera user, though when I was actively developing for the web, I've generally ended up using Firefox and IE only. Now, the good news is that the latest version of Opera already has a JS debugger, which means that now I have the minimum tools for using it while building ASPX pages!

Btw, one note: make sure you remove previous installed versions before installing the new one. I didn't do that and ended up not getting dragonfly properly configured (or at least, the menu item wasn't property configured to load dragonfly).

by luisabreu | with no comments
Filed under:
C# style conventions: more religious wars coming!
Tue, Jul 15 2008 23:24

Yes, it's one of those posts where you either agree or disagree completely :)

Anyway, after having a 15 minutes discussion with my friend Paulo (which, btw and as usual, disagrees with me) yesterday at 1AM, I've decided to write this post. The problem: MS recommends that variable names shouldn't have any sort of prefix like the _ or m_.

And what do I think? Well, I don't like! And I will only use that it my boss say something like: "hey, you must use that or we stop paying your paycheck". Ok, why don't I like that convention? Simply because I:

  • want to know if the current reference is pointing to a field or to a variable that was passed to a method;
  • don't like using this to disambiguate between field names and parameter names;

These 2 reasons are more than enough for using the _ prefix for field names. What do you think?

by luisabreu | 16 comment(s)
Filed under:
Scott Gu on MVC Preview 4
Tue, Jul 15 2008 23:07

Great post by Scott presenting the new things one can expect to see in the next preview of ASP.NET MVC. This means that it's time to pick up where I left and go back to the internals of the MVC platform.

by luisabreu | with no comments
Filed under: ,
Why I’m not buying an IPhone
Wed, Jul 9 2008 10:59

Simply because you can only buy it (officially) from a mobile phone operator. Simply a no-no to me…

by luisabreu | 5 comment(s)
Filed under:
Just wondering: will Silverlight 2.0 support indexing when it's out?
Tue, Jul 8 2008 23:29

This is one of the things I've been thinking about in these last days. To be honest, I still see Flash only sites (feel free to add Silverlight to the list too) as more trouble than they're worth it. Even though some say they're more usable, I'd say that's nonsense. To be honest, they aren't really integrated in what you expect to get from the web (and main example that confirms this is that you can't bookmark the "current" location in a flash application - ok, to be fair, I should say that you can probably use the same tricks you have with AJAX, but how many sites do that).

Forgetting about usability and concentrating back in your work as web developer, flash had a huge problem: it was "invisible" to search engines which wouldn't index their content. Well, guess what? It seems Adobe has come with a way for the search engines read the swf files. This is really huge and leaves me wondering how much time will MS take to do the same thing for Silverlight...

by luisabreu | 1 comment(s)
Filed under:
More Posts Next page »