September 2008 - Posts

Blogging pause
Tue, Sep 30 2008 22:33

Well, sort of...ok, here's the deal: I've been having problems on my leg for several months now. After spending some time siting, I have lots of problems getting up...It's as if the muscle won't stretch....Initially, fibrosis was the most viable option, but it seems like that is not the problem...

It seems like it may be caused by some sort of back problem, so I was advised to avoid being sited at all costs (at least, until I get my next appointment with a specialist, which should only happen in a month or so). What this means is that until I have a definitive answer on what's wrong with my leg (or should I say back?), I'll have to take the advice and that means that this blog will suffer a bit. I will still be writing, but with much less frequency. I do want to finish my MVC series, but I guess it'll take a little more time than I had though. Sorry about that :(

by luisabreu | 2 comment(s)
Filed under:
JQuery shipping with VS
Sun, Sep 28 2008 22:12

I've just read on Scott's blog that JQuery is going to be shipped with VS. This is simply fantastic! I've been a fan of JQuery for some time now. It's impossible not like its amazing flexibility and simplicity...and now we'll have intellisense on VS and it looks like the future client side controls of ASP.NET AJAX (including the AJAX toolkit) will be written over it.

This is just great and I think that it's a good move by MS (reusing instead of trying to build something when there's a great product out there) that should also be followed with other similar projects...

by luisabreu | with no comments
Filed under: ,
Silverlight 2 RC is out
Sun, Sep 28 2008 14:40

I was keen on Silverlight more than a year ago, but unfortunately I've stopped studying it since I just had to work in other areas. It seems like now is the time to pick up where I left since Scott has announced the release of SL 2.0 R.

by luisabreu | with no comments
Filed under:
NHibernate and value objects
Fri, Sep 26 2008 9:23

I do love NHibernate but there’ some things that keeps bothering me: value objects. Yes, NH does support it, but it seems like it’s impossible for having inheritance mapping when you decide to use them. There are some scenarios where inheritance makes sense, even when you’re thinking about value objects. For instance, lets think about contacts…You can probably represent a contact through an instance of type Contact, that could look like this (yes, this is a really simple example):

public class Contact{
  private Contact(){}
  public Contact(String value, ContactKind kind ){ … }
  public ContactValue{ get; private set; }
  public ContactKind{ get; private set; }
}

Where ContactKind could be an enumeration that looks like this:

enum ContactKind{
   Phone,
   Email
}

Ok, you could then have an entity which had a Contacts property that, in practice, would be a collection of value objects. This is a supported scenario by NHibernate. However, suppose that you want to have a more explicit API and that’s why you end up changing Contact to:

public class Contact{
  private Contact(){}
  public Contact(String value){ … }
  public ContactValue{ get; set; }
  protected abstract ContactKind{ get; }
}

So that you could introduce a specific type for each kind of contact. Here’s an example for phone:

public class Phone{
  public Phone(String value) : base (value ){ }
  protected override ContactKind{ get{return ContactKind.Phone} }
}

This kind of change will better express my domain and it will let me do further improvements on the base class (for instance, now I can add validation to the constructor so that I always know that the passed in phone number is valid).

Now, unfortunatelly, NH won’t give me any support for mapping this scenario into a table (ok, if there is a way, please let me know). If you want to do that, you’ll have to add an ID to your contact class and you’ll have to transform it into a component (ok, you can mask this so that only NH sees Contact as an entity). Is this such an exotic scenario that I probably shouldn’t be using it? I think not, but I may be wrong…

by luisabreu | with no comments
Filed under: ,
Leveraging extension methods for a better API
Wed, Sep 24 2008 12:31

Much has been said about extension methods. Some love it; others see them as evil. Good discussions have been made on when to use them (and when not to use them). Greg Young had a good post on when you might want to use them whenever you control the code of a class (btw, that is good advice that I have been using in my projects with lots of success).

Lately, I’ve been using extension methods for improving an existing API. Let me give you an example. In these last months, I’ve been writing lots and lots of domain code. I’ve also been using NHibernate for persistence and one of the things I need to do is test interation between my repository code and database code – if you’re into the name thingy, I guess that you can call it integration tests.

Many of my tests need to insert or clean a table before testing a specific repository method. I end up using IDbCommands a lot for setting up the data and since it’s the db code is controller by NH transaction, you need to enlist the command in the transaction so that everything works out as expected. What this means, is that I need to write something like this:

using( var session = GetSession() )
{
  using( var tran = session.BeginTransaction() )
  {
     var cmd = DatabaseHelpers.CleanCivilParishTable(); //returns IDbCommand
    tran.Enlist(cmd);
    cmd.ExecuteNonQuery();
   //….more code
  }
}

This is the kind of code that could be improved. What I really want is to have something like this:

DatabaseHelpers.CleanCivilParishTable()
                           .EnlistInNHTransaction(tran)
                           .ExecuteNonQuery();

See, much more readable (I really like fluent interfaces), less key strokes, meaning less probability of having carpal syndrome. To write the previous code snippet, you just need to create a new extension method. Here’s the code for the EnlistNHTransaction method:

public static class IDbCommandExtenders {
   public static IDbCommand EnlistInNHTransaction(this IDbCommand cmd, 
                                                                                  ITransaction tran)
    {
            tran.Enlist(cmd);
            return cmd;
    }
}

Oh, and I’ve also got similar code for adding parameters to anIDbCommand… and some other helpers…

So, who can say that extension methods aren’t cool ?

by luisabreu | 4 comment(s)
Filed under:
More flame wars on the way
Tue, Sep 23 2008 23:02

Today is ranting day again. So let's get started, ok?

A couple of weeks ago I had an interesting discussion on Fredrik's Who's to blame, Microsoft and/or .Net Community post comment section.  If you've read the comments, you already know that I'm a firm believer in self education and that you (the developer) are always the main responsible for your ignorance (especially in these days, where there's so many quality info spread around the net - ok, you must learn to look for it, but nevertheless, it's there!).

Today there was also an interesting thread at the ALT.NET list regarding a similar topic. I won't spoil your read here, so go on and read the entire thread. The most interesting thing that resulted form this discussion was Ayende's post Cuddling is considered harmful. Now, I couldn't have said it better:

Development requires a lot of skill, it requires quite a lot of knowledge and at least some measure of affinity. It takes time and effort to be a good developer. You won't be a good developer if you seek the "X in 24 Hours" or "Y in 21 days". Those things only barely scratch the surface, and that is not going to help at all for real problems.

And yes, a lot of the people who call themselves developers should put down their keyboards and go home.

I don't think that we need to apologize if we are working at a high level that makes it hard to beginners. Coming back to the idea that this is not something that you can just pick up.

Ok, lets make things clear. I'm not on the same league as Ayende...He's much smarter than me and that's good because he's a really prolific writer and that means that I have the chance of learning from his thoughts (which, by the way, are still free. So, if you're not a subscriber, do yourself a favor and add it to your feeds list). So, as you can see, my point is not to say that I'm really smart (that would be a tremendous lie), but to make you all see that you must really learn by yourself. That's all there is to it! No whining! Just suck it up like a great developer I know you are!

I'm not sure about you, but most people I know think that programming is easy...The problem is that it's not. You want the truth: it's bloody hard! So, if you want to get good at it, you need to put in some effort, ok?

Some years ago, in a different life,  I was a teacher and most of my students went into programming because they thought programming was all about...playing games! Ok, after leaving that life, I got into real programming and I still see the same thing all over the place: most guys will do the same thing all over again, without ever trying to learn new ways of improving their work. They simply cannot pick up a book or search info on some subject on the Internet in order to improve their skills. They simply stop...If you ask them why haven't they done something, they'll end up saying something like: "oh, I would love to do that, but I need training!". Oh, and then they'll keep looking at you waiting for some thoughts on how to solve their problem. This is the part where I really need to make a coffee break before I loose my temper...

And that's why we have so many bad developers around. Most seem to think that programming is easy or that it doesn't require any (mental) effort. No, I don't expect you to know everything...What I do expect is that you're able to solve problems by yourself and improve your skills along the years (yeah, notice that I said years, not hours, days or months!). Please stop blaming the others for your lack of knowledge. Guess what: overall, MS does some kick ass tools and platforms (I'm not paid by them and this is my opinion). Ok, they've also introduced DataSets, but you owe it to yourself to take the time and see if you should really use them (yes, there are valid scenarios for them; they just aren't adequate for all the things you do). Please don't tell me that MS keeps pushing drag-n-drop demos and that's why you won't improve your skills. Are you trying to convince me that if you're staying on a cliff and MS says "jump" you go ahead and do it?

Please do not ask for training before trying to learn for yourself! After all, what would happen if you needed training for all the things you need to do during your life and didn't learn on school? See where I'm getting?

by luisabreu | 2 comment(s)
Filed under:
The MVC platform – the UrlHelper class
Tue, Sep 23 2008 12:53

Today we’re going to start looking at the “famous” (well, most of the time I call then infamous, but the one we’re looking today is cool) helper classes introduced by the MVC platform. We’re going to start with one of the most important ones: the UrlHelper class. As you’ve seen, you’re be able to access an instance of this class through the Url properties exposed by the ViewPage and ViewUserControl classes. In theses cases, you don’t need to worry about initializing the new class instance because those classes alredy have the code to do that.

You’ll use this class whenever you need to get the url for a specific controller’s action method. The class ends up using its RouteCollection property to give you that information. As you might expect, if you don’t initialize that property (which you really won’t, unless you have specific needs or are writing tests), it will end up using the RouteTable that gets built during the application start event.

You’ll find several interesting methods:

  • Action:  several overloads of this method which let you generate an url based on an action;
  • RouteUrl: several overloads that will return an url based on a specific route info. For instance, if you’ve named your routes (like I generally do), you can pick a route by name and get its url;
  • Content: used for getting the path to a specific resource. You can use this method and pass one of those “relative” urls (“~/something”) and you’ll get the correct url for that resource;
  • Encode: used for encoding an url;

Most of the time, you’ll end up using the Action or RouteUrl methods. Lets start with the Action method.

The simplest thing you can do is call that method and pass the name of an action method. Here’s the signature of that method:

public string Action(string actionName)

If you do that, you’ll end up getting an url based on a method found on the current controller (the current controller is found by calling the GetRequiredString over the RouteData object that is avaiable throught the ViewContext that was passed to the view). If the route associated with the method requires parameters, then you can specify those values by using one of the following overloads:

public string Action(string actionName, object values)
public string Action(string actionName, RouteValueDictionary valuesDictionary)

Do notice that with the 1st version you can pass ana nonymous object with the values you want to pass to the parameters used by your route.

You’re also able to use a different controller by using one of the following overloads:

public string Action(string actionName, string controllerName, object values)
public string Action(string actionName, string controllerName, RouteValueDictionary valuesDictionary)

And  if you’re really picky, you can still end up using another couple of overloads which let you specify the protocol (for instance, you might want to go into https!) and the hostname. In these cases, you’ll be wanting to use one of these:

public string Action(string actionName, string controllerName, object values, string protocol)
public string Action(string actionName, string controllerName, RouteValueDictionary valuesDictionary, string protocol, string hostName)

The RouteUrl method is really similar to this, but as I’ve said, with the available overloads you’re able to select a route by name. These method are really cool and you can use them whenever you need an url and you know the name of a route. This is probably the method I’ve used most times until now.

Before ending, one final note: don’t forget that the strings returned aren’t encoded. So, if you need to encode them pass them through the Encode method.

This is really a short post and I’m not putting any examples of using these methods here. If you think examples are a must, please let me know and I’ll put some here.

More to come on future posts. Keep tuned!

by luisabreu | 2 comment(s)
Filed under: ,
Good book list
Tue, Sep 23 2008 0:50

I've noticed today that J.D.Meier has published his reference book list. This is the kind of list I enjoy because I'm always looking for good reading references. I've read some of them and I can confirm that those are good books (so I guess I'll just take my chances and start reading the other ones on that list).

by luisabreu | with no comments
Filed under:
Installing iTunes on Windows Vista
Tue, Sep 23 2008 0:27

This is a note to self: next time, before installing iTunes don't forget to "activate" VBScript by registering the vbscript.dll on an elevated privilege command line: regsvr32 vbscript.dll

I'm putting this here because I know that I'll end up forgetting it again in a few months whenever I need to install it on another PC running Vista...

by luisabreu | with no comments
Filed under:
The MVC platform – ViewPage and ViewUserControl classes
Mon, Sep 22 2008 11:51

Today we’ll concentrate on the final process related with the view generation. As we’ve seen in the last post, the WebFormView is responsible for instanting the page (or user control) required for rendering the HTML sent back to the client. Lets start with the ViewPage class…It extends the traditional ASP.NET Page class and it will also implement the IViewDataContainter interface. The IViewDataContainer is really simple and it’s only there for letting the View receive the ViewDataDictionary that contains data passed from the Controller:

public interface IViewDataContainer {
   ViewDataDictionary ViewData { get; set; }
}

Besides this property, you’ll notice that the ViewPage introduces several other interesting properties:

  • Ajax: property of type AjaxHelper. You can use this property for adding AJAX to your pages (we’ll see how in a future post);
  • Html: property of type HtmlHelper which gives you access to several utility methods that will help you generate controls on your pages (between other things). More about this on a future post;
  • MasterLocation: property used for putting the location of the master page;
  • Url: property of type UrlHelper. You’ll use this property for getting the correct urls for a specific route;
  • ViewContext: context associated with the current request;
  • Writer: read only property which you can use to get acccess to the HtmlTextWriter that is going to be used for writting the response to the client;
  • TempData: shorcut for the ViewContext.TempData property.

When you’re building views, you’ll end up creating new pages that inherit from this class. Do notice that all your pages must end up inheriting from this class. If you don’t do that, you’ll end up getting an exception because the WebFormView class will always try to cast your pages/user controls to ViewPage or ViewUserControl.

The ViewUserControl is similar to the ViewPage class. It doesn’t have a MasterLocation property because you only apply master pages to pages and not to user controls. However, it has other interesting properties. For instance, the class exposes a ViewPage property. It will try to cast the Page property (that you normally find on the UserControl class) into a ViewPage instance. If it works, then you’ll be able to access (for instance) the Url and Ajax properties from your control. If you don’t have a “valid” page, then you won’t be able to access any of those goodies.

If you look at the internals of the ViewUserControl class, you’ll find out that the ViewData property getter is interesting. You have two options here: you can pass the ViewDataDictionary or you can end up reusing the ViewDataDictionary of its parent. Another interesting thing: you can use a different view engine for rendering partial views!

By now we’ve got an idea of what is available on the views and partial views. Before going on, I’d like to make something clear. Until now, I’ve been saying that a view is an ASPX page and that a partial view is a user control. This is what will happen most of the time (you can probably say that it’s the most natural mapping when you think about ASP.NET and MVC). However, you should also keep in mind that nothing prevents you from “promoting” an ascx into a view. In other words, even though most of the time you’ll end up using the model I’ve been refering to  (ie, pages are mapped into ViewPages and user controls into user ViewUserControl), nothing requires you to do that. A view can be a user control or a page (and the same thing can be said about partial views).

As we’ve seen, you’ll end up influecing the view that is called by returning an ActionResult from your controller method. But what about rendering partial views? A valid scenario for partial views is dividing your pages into smaller components (user controls) and then placing them on your pages. You can do that in several ways. You can use the traditional ASP.NET approach, where you add a register directive to the page or you can use the HtmlHelper and call its RenderPartial method. Do notice that this last option will let you specify the ViewDataDictionary (or even the view engine) while in the first option you’ll end up using the default ASP.NET engine.

It’s interesting to notice that the RenderPartial methods are implemented as extension methods (as are several of the HtmlHelper public methods). We’ll return to them in a future post.

Before ending, there’s time to speak about two other classes. If you want to get a typed view page or view user control, you should use the ViewPage<T> and ViewUserControl<T> classes. These classes expand the previous classes and “transform” the ViewData property into a strongly type property of type ViewDataDictionary<T>. This means that if you’re passing a strongly typed object to your view, you’ll be able to access that object in your view (or partial view) through the ViewData property and access its properties directly.

On the next post, we’ll start looking at the helper classes. Keep tuned!

by luisabreu | 3 comment(s)
Filed under: ,
Future projects: Portuguese C# book on LINQ
Sun, Sep 21 2008 23:20

Ok, I can finally mention this on the open...in the last months I've been working with my friend Paulo on what is supposed to be the 1st Portuguese book on LINQ with C#. We're well on the way to complete the 1st phase of the project and should start the reviewing stages by the end of the month. For now I can only tell you that working in this project with Paulo has been a lot of fun. Let's just hope that the readers end up enjoying it too. Oh, and this should be another FCA book...

So, if you can read Portuguese and you're interested in getting our perspective on the LINQ platform, then just wait another month or two...by then the book should have reached the shelves! :)

by luisabreu | 5 comment(s)
Filed under: , ,
Codebehind files in ASP.NET MVC *ARE NOT* evil
Fri, Sep 19 2008 15:31

Steve Smith has an interesting post with a suggestive name: “Codebehind files in ASP.NET MVC are evil”. So, it seemed appropriate to write a response with the title “Codebehind files in ASP.NET MVC *are not* evil”. I just couldn’t resist it :)

Technically, they must be there for you to get intellisense on your aspx files, but that’s not why I’m saying they shouldn’t be removed. Before going on, I understand Steve’s point of view: keeping the codebehind files might lead you to put code that belongs to the controller on the view. As I said, I understand, but I want to believe that a good developer will understand MVCs strenghts and will, after some time, have no doubts on where some behaviour (code) should go.

On the other hand, I’m not sure that removing the codebehind file will be enough for stopping a “bad” programmer. After all, he can still put the code on the aspx file because he can still add <% %> to a page and put some server code inside it(and, of course, there’s still the <script runat=”server”> element). So, even though I understand the need for helping a fellow programmer understanding MVC, I hope to have demonstrated that if I’m a “bad” ASP.NET programmer, I can still be “bad” on ASP.NET MVC, even though there is no codebehind file.So, removing the codebehind file is just limiting my options and not preventing developers from writing bad code.

I’m also not sure I agree with Steve when he says that views should be dumb. Once again, you can say that I’m being picky, but I can assure you that my views are not dumb…no, they‘re really smart! You see, they’re smart enough to “understand” that they can’t have any business logic in them. The only code you’ll find is presentation related code. And do notice that even though there might be cases where the view uses a color X to present result Y and color Z to present result W, you won’t find any of those rules “embedded” on my views. In other words, you won’t find any method that looks like this:

return ( myObject.Price > 10 && myObject.Price < 100 )  ? “cssClassY” : “cssClassZ”;

Btw, and since we’re talking about this example, I don’t agree with Steve when he says that the css class info should be passed to the view from the controller. I’m not even sure that the controller is the place for taking business decisions, but we’ll leave that discussion for a future post (I do tend do be super-protective with my domain model and I prefer to see the controller as something that coordinates interactions between views and model). Going back to the color scenario, I think that the object passed to the view should be responsible for flagging special conditions and the view should be responsible for picking up the correct css (after all, CSS are all about presentation and presentation decisions should be taken by the view). What this means is that I’d write the previous code so that it looks like this:

return myObject.IsInSpecialPriceInterval() ? “cssX” : “cssY”;

As you might expect, I want to have the chance to write this code on my codebehind file without having to mix it with the markup of my ASPX page. Ok, by now I think there shouldn’t be any doubts that there are cases where codebehind files are useful (and of course, I think that my previous example might have shown how easy it is to propagate busines decisions to the view and vice-versa).

Let me share with you a dream which makes me stick harder with the “pro-codebehind” approach. Wouldn’t it be really cool if we could get a new server side control toolbox similar to the one we’ve got on the Web Forms world but without any of the existing unecessary features (like view state, control state, server side events)? Just think about it for a moment…

Imagine seeing no more of those <% %> floating everywhere on your aspx page…having a clear separation between markup and code, which doesn’t happen with the current view engine. If you want to really imagine it, just compare the old spaghetti ASP code with the elegance of the ASP.NET web forms page but don’t think about events and view state…just concentrate on the markup. Now be honest: do you preffer the spaghetti or the web form’s approach (ok, if we’re talking about eating, I’d go with the spaghetti, but we’re not talking about eating, ok?). If you’re thinking about transition from Web Forms to MVC, which would be best?

So, yes, you can say that I have a dream…a vision…call it whatever you want it. I’m seeing a lightweigth server side control model where I can put server side tags on the page and initialize their values on the codebehind file. And yes, in this case you bet I can’t live without a codebehind file.

Even though this whole new “server control toolbox” is just a dream (and I’m thinking it will stay like that for a long long time), I still want the options of getting my codebehind file. So, if you really must take it away (by default), please do leave the old checkbox option where I can choose to have a codebehind file.

Bottom line: I  prefer to have more options, even though that will mean more responsibilities. But again, this is just my opinion and you know what happens with opinions: everyone is entitled to one!

by luisabreu | 10 comment(s)
Filed under: ,
The MVC platform – the WebFormView class
Fri, Sep 19 2008 14:17

So, after a long walk we’ve finally reached the WebFormView class. This class is responsible for instantiating a view (which may be an ASP.NET page or a user control) and generating the output that is going to be sent to the client. The class implements the IView interface which was reintroduced in this last preview (5, if you’re reading this in the future) and looks like this:

public interface IView {
        void Render(ViewContext viewContext, TextWriter writer);
}

As you can see, the Render method receives a ViewContext which contains information about the current context and a TextWriter instance you can use to output the HTML of the pages. It’s important to understand that the WebFormView isn’t an ASP.NET page or ASP.NET user control; it’s just a class that will instantiate the requested page or user control and render its HTML.

In order to achieve this, the WebFormView class’ constructors will receive the path to the requested resource and (optionally) the path to a master page that must be applied to the view that is being built (master pages will only be used when rendering a view). There’s also another interesting property exposed by the class: the BuildManager property.  This property lets you specify the builder (an IBuildManager type) used for getting an instance of the class from the specified path. The IBuildManager interface defines the following contract:

internal interface IBuildManager {
  object CreateInstanceFromVirtualPath(string virtualPath, Type requiredBaseType);
  ICollection GetReferencedAssemblies();
}

The BuildManagerWrapper builder is used by default and it implements the previous interface by reusing the BuildManager class.

The WebFormView class will call the IBuildManager.CreateInstanceFromVirtualPath on the current builder in order to create a view instance. But here’s the thing: it will always try to convert the created instance into an element of type ViewPage or ViewUserControl. These are the basic types that your ASP.NET MVC pages or user controls must extend in order to be considered MVC views. As you might expect, these classes extend the traditional Page and UserControl ASP.NET classes. We’ll come back to these classes in a future post. For now, knowing that both of them expose a ViewData property and a RenderView method is more than enough for the rest of this post.

Back to the WebFormView class…so, after instantianting the object and casting it to ViewPage or ViewUserControl, the WebFormView class ends up passing the ViewDataDictionary (which contains info about the current view) and calling the RenderView method in order to generate the HTML sent back to the client.

And that’s all. There’s really nothing more to it. On the next post, we’ll take a closer look at the ViewPage and ViewUserControl classes. Keep tuned!

by luisabreu | with no comments
Filed under: ,
The MVC framework – customizing the search locations
Fri, Sep 19 2008 12:45

In the last post, we’ve seen what view engines do and how the WebFormViewEngine is responsible for initiating the properties that specify the places where the views (ASP.NET pages and user controls) are supposed to be located. At the time, I mentioned how you could register your own engine, but I forgot to point that you can easilly use that info to customize the place where your views are searched. So, if you don’t like the current restrictions but you do want to use ASP.NET pages and user controls, you can always inherit from the VirtualPathProviderViewEngine and build the array with the new locations from within the constructor of your new class.

Another thing I didn’t mention was that the VirtualPathProviderViewEngine uses caching for saving path info. This means that after finding the path to a view, it will add it to the cache and in future requests it will just return the path that exists there. In future versions you should be seing a plugable cache provider in the API of the class (meaning that you will be able to pass your own custom cache instances).

Ok, now we’re ready to keep going and the next post will be about the WebFormView class. Keep tuned!

by luisabreu | 1 comment(s)
Filed under: ,
The MVC platform – view engines
Wed, Sep 17 2008 11:42

In the last post of the series, we’ve seen how PartialViewResult and ViewResult actions will end up using the response sent back to the client. We’ve also seen that these classes expose several properties that need to be set in order for them do to their work and that the Controller base class introduces several methods that will save us some work when we want to use some of the predefined default values.

Today we’ll pick up where we left. Lets start with the existing view engines…as we’ve seen, view engines are responsible for locating views and they implement the IViewEngine interface. Currently, the platform introduces 3 classes that implement this interface:

  • VirtualPathProviderEngine: this abstract class is responsible for  finding the path to a specific (partial) view. It won’t create an IView since it delegates that work to any derived class;
  • WebFormViewEngine: as you can deduce from its name, this engine is responsible for rendering ASP.NET pages (views) and user controls (partial views). This class extends the VirtualPathProvider engine and is responsible for creating an instance of the type WebFormView;
  • CompositeViewEngine: its job is to handle all the registered view engines and return the correct ViewEngineResult for the current scenario. It implements the IViewEngine interface by going through all the registered view engines and calling the appropriate method (FindView or FindPartialView) over each of those instances. When one of them returns a valid ViewEngineResult, it will return that result to the called. This is the default engine used whenever you don’t specificate  a specific engine.

Now that we’ve got a global view, it’s time to digg a little deeper into the code. As we’ve seen, the VirtualPathProvider engine is abstract and its main responsibility is getting the path to the physical ASP.NET file that contains the HTML that will be returned from the client. It introduces some important properties. The MasterLocationsFormats, PartialViewLocationFormats and ViewLocationFormats are used to hold several strings with the paths where the views are expected to be found. You can also specify which virtual provider is used. By default, you’ll get the default VirtualPathProvider, but you can always extend the class and set up the protected VirtualPathProvider property.

This class introduces two abstract methods that must be implemented by a derived class (CreatePartialView and CreateView) in order for instantiang the correct IView. As I’ve said, the WebFormViewEngine extends the VirtualPathProviderViewEngine and is responsible for initiating the locations properties (which it does so on its constructor). It will also implement the abstract methods specified before. The code is so short that I’ll just put it here:

public class WebFormViewEngine : VirtualPathProviderViewEngine {         public WebFormViewEngine() {
            MasterLocationFormats = new[] {
                "~/Views/{1}/{0}.master",
                "~/Views/Shared/{0}.master"
            }; 
            ViewLocationFormats = new[] {
                "~/Views/{1}/{0}.aspx",
                "~/Views/{1}/{0}.ascx",
                "~/Views/Shared/{0}.aspx",
                "~/Views/Shared/{0}.ascx"
            }; 
            PartialViewLocationFormats = ViewLocationFormats;
        } 
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) {
            return new WebFormView(partialPath, null);
        } 
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) {
            return new WebFormView(viewPath, masterPath);
        }
    }

The WebFormView will be responsible for building an instance from the required ASP.NET resource (page or user control) and rendering the HTML. We will talk about this class in detail in the next post.

Back to the view engines, we still need to talk about the CompositeViewEngine. As I said, this is the default engine used by default. In fact, it’s not really an engine because it won’t be able to do anything by itself. What it does is maintain a collection  of IViewEngine instances. When a request comes in, it will go through all the previous registered engines and it will try to get an engine that returns a valid response for the current request. When that happens, it will return that result to the caller.

As you might expect, you can also create your own engine. In order to use it, you need to register it (probably during the application start event) by adding it to the static Engines property of the ViewEngines class:

ViewEngines.Engines.Add( new MyEngine() );

The current release of ASP.NET MVC will only register the WebFormViewEngine by default for you. One more observation: When adding a new engine, you might need to employ some sort of locking because the Add method isn’t really thread safe.

As you can see, the main function of a view engine is locating and returning a valid IView that will be responsible for rendering the response sent back to the client. On the next post we’ll take a look at how the WebFormView class does its work. Keep tuned!

by luisabreu | with no comments
Filed under: ,
New laptop: presenting the Toshiba U400-133
Tue, Sep 16 2008 22:51

Ok, I shouldn't have, but the truth was that I ended up buying a new notebook. It's a Toshiba and it looks great...at least on paper, that is :)

I guess that this means that now I don't really have many excuses for not blogging more often...

by luisabreu | 1 comment(s)
Filed under:
The MVC platform – action result views
Tue, Sep 16 2008 12:28

In the last post we’ve seen how ActionResult derived classes will encapsulate the return values of action methods. Today, we’ll talk about two special types of action results: the PartialViewResult and ViewResult action result classes.

The PartialViewResul introduces most of the logic used when redering a view (to me, view is something that generates info sent back to the client). It introduces several important properties, presented on the following list:

  • TempData: property of type TempDataDictionary, used for storing temp data info. We’ve already talked about that property in the past. Generally, the controller will initialize this property when it creates this kind of action result;
  • View: property of type IView, that ends up holding a reference to the view responsible for returning the result to the client;
  • ViewData: property of type ViewDataDictionary, used for passing info from the controller to the view;
  • ViewEngine: property of type IViewEngine that is responsible for getting a view used for rendering the HTML sent back to the client;
  • ViewName: string which is used to identify the name of the view that should render the current response;

The PartialViewResult implements the ExecuteResult by doing several important things. First, it will initialize ther properties presented on the previous list. The most interesting piece of work is trying to find the view (which is done by the FindPartialView method). To do that, it ends up using the IViewEngine instance and calling the FindPartialView method. By the way, the IViewEngine interface looks like this:

public interface IViewEngine {
  ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName);
  ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName);
}

I’ll leave further investigation on how the view engine works for a future post. For now, you just need to keep in mind that you can use if to get a valid reference to a view that will render the response returned to the client.

The ViewEngineResult is a simple class that has only two properties: SearchedLocations and View. The View will hold a reference to an IView implementation that will render the view; SearchedLocations will end up giving you the locations where the view has been searched. This info will be given to you in the form of an exception whenever the view engine doesn’t find a view with the specified name in the search locations.

After getting a valid reference to an IView interface, the PartialViewResult class ends up calling the Render method exposed by the IView interface. Btw, here’s the contract introduced by this interface:

public interface IView {
  void Render(ViewContext viewContext, TextWriter writer);
}

As you can see, the Render method doesn’t return a string. Instead, it will receive an instance of the TextWriter class that the view will use to ouput its HTML. You can find more info on why this was done by reading this post by Brad Wilson.

As I‘ve said, the ViewResult class expands the PartialViewResult class by adding a new property called MasterName. In practice, this means that you’ll have the option of applying a master page when you return an item of this type. Internally, this class follows similar steps for getting the view, so I won’t be repeating myself here.

In practice, you’ll use the PartialViewResult for outputing  a small part of a view. That’s why you don’t have the master page options when dealing with them. On the other hand, you’ll use the ViewResult for getting a “complete” view. As you might expect, the Controller class exposes several methods that will let you reduce the ammount of typing needed for instanting these types of action results.

I think that by now we can all agree that the MVC platform is really a very modular platform and you can easilly customize its features/internal workings by replacing just small pieces of code. On the next post, we’ll keep looking at it and we’ll talk about view engines implementations. Keep tuned!

by luisabreu | 2 comment(s)
Filed under: ,
Codeplex, SvnBridge and Tortoise
Tue, Sep 16 2008 11:25

I’ve only noticed today, but it seems like now it’s official: you can use Tortoise to access Codeplex projects.

by luisabreu | with no comments
Filed under:
The MVC platform – understanding ActionResult classes
Mon, Sep 15 2008 12:12

In the last post we’ve seen how the ControllerActionInvoker ends up using the ActionResult class returned from your controller methods in order to generate the response that is sent back to the client. Today, we’ll take a  look at the existing ActionResult classes and see what each of them do. Lets start with the base ActionResult class.

public abstract class ActionResult { 
        public abstract void ExecuteResult(ControllerContext context); 
}

As you can see, this is really a very simple abstract class which has only one method called ExecuteRequest. This method receives the current ControllerContext, which means that you’ll be able to access all the the HTTP server side objects and you’ll also be able to get a reference to the current Controller. In the latest release, you’ll have access to the following ActionResult’s derived classes:

model

Lets start with the simple ones…The EmptyResult class doesn’t really do anything. It’s there only to let you specify that a specific action won’t return anything to the user. You can use the HttpUnauthorizedResult to indicate that the current user hasn’t got enough permissions for the current operation (internally, the ExecuteResult method sets the status code of the response to 401).

RedirectResult doesn’t do much too…You can use this action result whenever you need to redirect to another url. Since we’re talking about redirections, there’s also a RedirectToRouteResult. With this class, you’re able to pass a route name and a RouteValueDictionary and it redirect the user to the url calculated from those parameters.

Controller methods don’t always need to get HTML. You can also return JSON from your controller’s methods. The JsonResult class is there and will help you do that. Internally, it uses the JavaScriptSerializer and it serializes the object that is passed to its Data property.

You can also return text from a controller method by using the ContentResult class. This class will write the specified text to the output and you can also set the encoding and content type of the current response. Until now, we’ve assumed that all action methods returned ActionResult instances (in fact, I’ve even said that in one of the previous post), but the truth is that you can also return another type. When that happens, the instance returned from your object is wrapped in a ContentResult action, which is then responsible for converting it to a string (by calling the Convert.ToString method) and pushing it through the response stream. Btw, it’s also interesting to point out that if your method returns void, you will end up using the EmptyResult action.

Finally, you’ve also got the PartialViewResult class. There’s also a ViewResult class, that extends the PartialViewResult class. Both these classes will let you render views that return HTML to the client. I won’t be spending more time on these classes becaus the next post will be about them. The base Controller class exposes several methods that encapsulate the creation of these types of action results. Currently, you have access to these:

  • ContentResult: responsible for creating an action of type ContentResult;
  • JsonResult: as you might expect, this method will return an instance of the JsonResult type;
  • PartialViewResult: used for partial rendering. Returns an instance of type PartialViewResult;
  • RedirectResult: used for returning an object of type RedirectResult that will redirect the user to a new url;
  • RedirectToRouteResult: responsible for creating an instance of type RedirectToRouteResult;
  • ViewResult: returns an instance of the ViewResult object which ends up rendering a page.

So, when you build your own controller methods, you can create a new instance of the ActionResult you want or invoke the method with the some name and pass it the correct parameters for the current scenario. As I’ve said, on the next post we’ll take a closer look at the PartialViewResult and ViewResult classes. Keep tuned!

by luisabreu | 1 comment(s)
Filed under: ,
PostSharp RTMed…
Fri, Sep 12 2008 10:24

PostSharp 1.0 is now  in RTM. Get it from here.

by luisabreu | with no comments
Filed under:
More Posts Next page »

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover