February 2009 - Posts

Outlook 2007 rant: replying in plain text
Fri, Feb 27 2009 14:45

One of the things I do like to do is reply all my mail in plain text. So, like any normal person, I went straight to the options and searched for something about mail replying. And yes, there are a couple of options there. Just to  be sure, I’ve set them all to plain text. Despite that, whenever I hit the reply button, I’d always get rich text if the original message was in plain text.

After some searching, it seems like the only way to get this automatically for all mails is by reading all messages in plain text or by creating a macro. So, I went with plain text. Now, I’d really love to know why can’t I have something that lets me read my messages in the original and *always* reply in plain text…

by luisabreu | 3 comment(s)
Filed under:
Code contract is out
Wed, Feb 25 2009 18:29

Check the announcement here and the site is here.

by luisabreu | with no comments
Filed under: ,
Paul do Mar mini-vacations
Tue, Feb 24 2009 14:22

I’ve just returned from a mini-vacations at Hotel Paul do Mar. Even though the services could be a little better, it was a really nice place to say and relax (as you can see from these photos). Now I’m relaxed and ready for more work (which involves ending the LINQ book which is going to be released by the publisher on March).

by luisabreu | with no comments
Filed under:
The MVC framework: using the IDataErrorInfo interface
Thu, Feb 19 2009 12:36

On these last posts, we’ve seen how we can automatically fill an object from data submitted by a form. today, we’re going to take a look at how you can use the IDataErrorInfo and get automatic validation support. The first thing you should know is that IDataErrorInfo isn’t defined by the MVC fraemework. In fact, this is an existing interface defined on the System.ComponentModel namespace and it only exposes two read-only properties: Error and Item. Error returns an error which indicates what’s wrong with this object and Item returns an error message for a specific property of that object (ie, when that property doesn’t hold a valid value).

Theoretically, reusing this interface means that you’re able to reuse the interface and get validation across several windows platforms (WPF, windows forms and ASP.NET MVC). In order to get things going, we’re going to reuse the User class introduced in a previous post and we’ll add validation to it. Here’s how the class looks like after we’ve added the interface to its list of implemented interfaces:

public class User: IDataErrorInfo {
    public Int32 UserId { get; set; }
    public String Name { get; set; }

    public string this[ String columnName ] {
        get  {
            if (!ColumnNameIsValid(columnName)) return null;
            return ValidateProperty( columnName );
        }
    }

    private String ValidateProperty( string propertyName ) {
        // real world you'd probably cache this info...could probably use an existing
        //framework for validation and cache the results so that you don't have to get
        //this info for all the properties
        if( propertyName.Equals( "Name", StringComparison.CurrentCultureIgnoreCase  )) {
            return String.IsNullOrEmpty( Name ) ? "Name cannot be empty" : null;
        }
        return UserId <= 0 ? "UserId must be a positive number" : null;
    }

    private Boolean ColumnNameIsValid( String name ) {
        return new[] {"UserId", "Name"}.Any( prop => prop.Equals( name, StringComparison.CurrentCultureIgnoreCase ) );
    }

    public string Error {
        get {
            String[] propNames = {"UserId", "name"};
            var errors = propNames.Select( prop => ValidateProperty( prop ) );
            return errors.Count() == 0 ? null : "The object is not in a valid state";
        }
    }
}

Since this is demo code, I’m just hard coding the validation rules and using some simple simple rules (Ids must be positive and Names cannot be empty). As you can see, the Item property checks to see if the name of the property is valid and, if it is, it tries to validate its current value. When the value isn’t valid, we return an error message with information about the error. As we’ve seen, the Error property should return an error message if the object is in an invalid state. Now, we should probably change the markup for the view so that it is able to give error messages when something goes wrong:

<% using( var frm = Html.BeginForm("UpdateUser", "Home")) {%>
  <label for="userid">User id:</label>
  <%= Html.TextBox( "userid" ) %>
  <%= Html.ValidationMessage( "userid"  ) %>
  <br />
  <label for="name">Name:</label>
  <%= Html.TextBox( "name" ) %>
  <%= Html.ValidationMessage( "name"  ) %>
  <br />
  <input type="submit" value="Confirm" />
  <br />
  <%= Html.ValidationSummary( ) %>
<% } %>

As you probably recall, we’re adding the validation helpers in order to get feedback whenever there’s an invalid value on a property of the object. Finally, we need to update the UpdateUser action so that it won’t redirect to a new page if the information submitted in the form leads to an object in an incorrect state. Here’s a possible implementation of that method:

public ActionResult UpdateUser(){
    var user = GetUserFromSomewhere();
    if( !TryUpdateModel( user ) ) {
        return View( "User", user );
    }
    return View( "ShowInfo", user );
}

If you compare the previous snippet with the code we had in the other post, you’ll notice that we’re using the TryUpdateModel (instead of the UpdateModel). The reason is simple: with UpdateModel, we would get an exception if there was any validation errors (ie, you’d have to wrap the UpdateModel call in a try/catch block since you’d probably be interested in showing the form to the user again). So, with the previous code, here’s what you’ll be getting when you pass a negative user id and an empty name:

error

As you can see, you end up getting error information for each property that has an incorrect value and, since we’ve added a summary, we’re also getting the general error message returned by the Error property. It’s now time to take a peek at how validation is implemented internally.

If your model object implements this interface, then the default binder will call the Item property for each property that is set to see if its value is valid. After that, it will try to get an error message for the object itself by accessing the Error property. When any of these properties return an error, that info is added to the current ModelState so that it’s available to the view. It’s also interesting to point out that validation is performed on the virtual OnPropertyValidated and OnModelUpdated methods (if you extend the DefaultModelBinder class and override these methods, then don’t forget to call the base methods or you won’t have any validation support).

Ok, now that you know how things work  under the hood, you can probably see that the code  I’ve used in this example might not really be the most performant code you could have. To start with, we can probably agree that returning null for the Error property is probably the best option since we’re running validation all over again on that property’s body. However, there probably are some scenarios where you have dependencies between properties and you’d probably be interested in running validation when your object is completed hydrated. So, you could return null from the Item property, but then you’d only be able to return a string from the Error property (which wouldn’t be good for reporting several errors).

I guess that the bottom line is that  you can probably use this validation mechanism for basic validation (ex.: ensuring that a field has n chars or that the entered date is valid) but it’s really not that usable for real complex validations. Again, only my opinion.

Keep tuned for more on the MVC framework.

by luisabreu | 3 comment(s)
Filed under: ,
I love SQUASH
Wed, Feb 18 2009 19:49

And unfortunately, I still can’t play it (due to back injury). Ok, here’s why I do love this game!

by luisabreu | 1 comment(s)
Filed under:
The MVC framework: using ValueProviderResult instances
Wed, Feb 18 2009 14:30

Yesterday we’ve seen how we can  use the UpdateModel/TryUpdateModel to update an instance of an existing object with data that was sent back to the server during the current request. At the time, I’ve mentioned the ValueProviderResult class and promised a more detailed analysis of it in a future post. Since I like to keep my promises, today we’re going to look at the code of this class and see how it is used by the runtime.

ValueProviderResult instances are used internally when you want to automatically update the properties of an object with the values submitted on a postback. In other words, you’ll be using instances of this type whenever you use the binding operations for “recovering” objects from the values submitted on a request (if you don’t recall it, you’re able to do this with Bind attribute or by using the UpdateModel/TryUpdateModel methods). As we’ve seen yesterday, if you’re calling the UpdateModel/TryUpdateModel methods, you can  pass a dictionary of ValueProviderResult instances.Each entry of this entry of the dictionary is identified by a name (more about this on the next paragraphs).

If you look at the ValueProviderResult, you’ll see that it has three public properties: RawValue, AttemptedValue and Culture. RawValue points to an object which has the raw value of the object (this is the property used for updating the object’s property). AttemptedValue stores the new attempted value as a string (generally used for validation errors). Finally, there’s a CultureInfo object (Culture property) which is used when  converting value into a specific type. This will all make sense when we follow the normal usage of a ValueProviderResult instance.

Besides these properties, there is also the ConvertTo method (which has two overloads). This method is called by the default binder and is responsible for returning a value of the specified type (which, as you might expect, depends on the property and on the specified culture – remember the Culture property? ).

In practice, all the values of your properties are converted by instances of ValueProviderResult objects. For instance, if you recall yesterday’s example, we had a User class with two properties:

public class User {
    public Int32 UserId { get; set; }
    public String Name { get; set; }
}

Whenever you recover an instance of this type through binding, you need (at least) two ValueProviderResult instances: one for updating the value of the UserId property and another for updating the value of the Name property. But how are these instances created? If you’re not using the UpdateModel/TryUpdateModel overloads that receive the required dictionary of ValueProviderResult, then you’ll end up inheriting the one that is defined by the ControllerBase class (which is way at the top of the controller hierarchy you get when you reuse the default controller architecture).

This default dictionary is populated by using the current submitted values: for each entry, you’ll get a ValueProviderResult object identified by the that NameValueCollection entry key and filled with info recovered from that NameValueCollection entry. As I’ve said, the default binder is then able to use this dictionary for recovering the values that should be passed into the properties of the object you’re “recreating”.

You should take 2 points from this post:

  • if you’re not happy with getting all the values form the current request, then you can pass your own ValueProviderDictionary (ie, a custom ValueProviderResult which has the values you want) to the UpdateModel/TryUpdateModel methods (this is not possible when using the Bind attribute);
  • if you’re building a custom IModelBinder, then don’t forget to recover  the property value from an existing ValueProviderResult.

And that’s it for today. More on the MVC on the next posts.

by luisabreu | 1 comment(s)
Filed under: ,
The MVC platform: updating your objects
Tue, Feb 17 2009 12:13

Today we’re going  to keep looking at the MVC platform and see how we can update an object by using the UpdateModel/TryUpdateModel methods. As we’ve seen, you can hook up an action method parameter with a binder. By doing this, the parameter will be instantiated and its properties’ values, automatically filled up from the HTTP data that is passed during the current request. Unfortunately, this might not be adequate to all the scenarios. There might be times where you need to update an existing object,  instead of creating a new one and filling it with values recovered from the current request payload.

In these cases, you can use the UpdateModel method for updating the properties of an existing object with the values submitted in the current request. To illustrate its use, we’ll assume that we have a User class that looks like this:

public class User    {
   public Int32 UserId { get; set; }
   public String Name { get; set; }
}

Now, let’s assume that we’ve got an action which recovers a user and passes it to a view which renders it:

public ActionResult User() {
    //demo code: in the real world you’d probably
    //load this info from a database or web service
    var user = new User {
                        UserId = 1,
                        Name = "Something"
                    };
    // in the real world you’d need to persist this object
    //or add more info in hidden fields in order to update the 
    //object without overriding other updates (ie, need more info
    //for optimistic locking)
    return View( user );
}

And then, the User view would look like this:

<% using( var frm = Html.BeginForm("UpdateUser", "Home")) {%>
      <label for="userid">User id:</label>
      <%= Html.TextBox( "userid" ) %>
      <br />
      <label for="name">Name:</label>
      <%= Html.TextBox( "name" ) %>
      <br />
      <input type="submit" value="Confirm" />
<% } %>

As you can see, we’ll render a form that submits its data to the UpdateUser method of the Home controller. In the UpdateUser method, we need to recover the user and update it with the info submitted on the form. Instead of going through the form’s fields, we’ll just delegate that work to the UpdateModel inherited from the Controller class:

public ActionResult UpdateUser() {
    //demo code: in real world code, you’d recover this object 
    //based on the way you’ve saved it in the previous user method
     var user = new User {
                            UserId = 1,
                            Name = "Something"
                        };
    // update the object by getting the values submitted in form
    // this method might throw (see next paragraphs)
    UpdateModel( user );
    return View( "ShowInfo", user );
}

As you can see, we don’t recover the values submitted in the form. Instead, we just delegate that work to the inherited UpdateModel method. There are several overloads of this method. For instance, there’s an overload which lets you pass arrays with the name of the properties that should be included and/or excluded. This overload is useful when you don’t want to recover all the values from the form. For instance, if in the previous example you didn’t want to update the value of the UserId property), you’d just need to use the override of that method that receives an array of properties names that should be updated:

UpdateModel( user, new[]{ "Name"} );

As I’ve said, there are other overloads. For instance, there’s one overload which lets you pass a dictionary of ValueProviderResult objects which are used for recovering the form’s submitted data (more about this in future posts). Bottom line: you’ve got several overloads of this method and you should look at its signatures to decide which one is indicated for your current scenario.

There’s also another method which you can use to perform a similar operation: I’m talking about the TryUpdateModel method. The main difference between these two methods is that the UpdateModel will throw if the updated object is in an invalid state, while the latter will return false when the object is in an invalid state.

Internally, both methods delegate the work to the existing binders and that’s how you get to know if an object is on a valid or invalid state (recall that binders perform validation for objects that require it – I think I still haven’t talked about the IDataErrorInfo interface, so I’ll just say that your objects might implement this interface in order to indicate if it’s in a valid or invalid state and the binder – at least the default one – will automatically pick up this info and add eventual errors to the model state).

And that’s all for today. More about the MVC framework in future posts.

by luisabreu | with no comments
Filed under: ,
The MVC platform: working with files
Thu, Feb 12 2009 12:20

The latest release of the MVC platform introduces some classes which simplifies the code you need to write when you need to work with files. Today, we’re going to concentrate on the available options you can use when you need to download a file from an action method. We’ll start by looking at the base FileResult abstract class.

This class exposes only a public constructor which receives a string. This string is used for identifying the content type of the file that is going to be downloaded. The class also introduces a public property (with a getter and a setter) which you can use to define the name that is shown on the download dialog that is presented to the user when the action is executed and the file returned.

Finally, the class implements the ExecuteResult by defining the content-type and content-disposition headers which are returned to the client. The process of writing the contents of the file to the response stream are delegated to the derived classes (which must implement the abstract WriteFile method).

Currently, the platform introduces three concrete instances of the FileResult type. Your first option is using FileContentResult.You should use this type whenever you have the bytes of the file you want to return. If you’ve got  a reference to the a stream, then you can also use the FileStreamResult class. As you’ve guessed, you’ll need to pass a reference to the stream you want to write to the response that is returned to the client. Do keep in mind that the class ends up calling Dispose on this stream after copying to the  response stream that is returned to the client.

Finally, if you’ve got a physical location to a file that you want to return to the client, you can use the FilePathResult class. This file is pretty simple and it will simply call Response.TransmitFile and pass it the path you’ve previously sent into its constructor.

Returning files hasn’t been easier! On the next post we’ll keep looking at the MVC platform. Stay tuned!

by luisabreu | 1 comment(s)
Filed under: ,
The MVC platform: the new anti forgery token
Mon, Feb 9 2009 21:33

Today we’re going to talk about a new feature introduced by the RC version of ASP.NET AJAX: the anti forgery token. The idea is render a hidden token which is validated during post back, ensuring that your app is protected against cross-site request forgery. Using this feature in your apps is as simple as calling the Html.AntiForgeryToken from within your form and adding the ValidateAntiForgeryTokenAttribute to the action method you want to protect.

Using it is simple, but what happens behind the scenes? That’s what we’re going to see right away.

Unlike what you might expect, the AntiForgeryToken method is really an instance method of the HtmlHelper class. Currently, you have 2 overloads: one without parameters and another with a single parameter that lets you pass a String with the salt that should be used in the creation of the token (more about that in the next paragraphs).

Internally, this methods performs some interesting operations:

  • it starts by getting the “HTTP only” cookie which is used for keeping an anti forgery token created internally. If it finds an existing anti forgery cookie in the cookie collection available from the current request, it will deserialize its  value. If there isn’t any cookie, a new one will be created and initialized with random new anti forgery token.
  • The token obtained is used to create a new anti forgery token which ends up being persisted in a hidden field of the form.

Now, we need to understand how this token is verified during a post back. As you might suspect, the ValidateAntiForgeryTokenAttribute performs an important role in this verification. By now, you shouldn’t be surprised to know that the ValidateAntiForgeryTokenAttribute is a filter which also implements the IAuthorizationFilter. When its OnAuthorization method is called, it starts by recovering the previously created cookie and recovers its value (as you recall from the previous paragraphs, the cookie value should be generated during the initial rendering of the form and is only a random anti forgery token).

After getting that value, the attribute tries to recover the serialized value of the token that has been injected in the view through a form’s hidden field. It will then compare both deserialized values and see if they’re equal. If they are, then it will perform one last check: compare the salt on the token and see if it matches the initial salt that was passed when you called one of the overloads of the Html.AntiForgeryToken.

As you’ve probably guessed, if any of these checks fails you’ll end up with a HttpAntiFogeryException which ends the current request processing (in this case, eventual exception filters will get a crack at handling the current exception).

Until now, I’ve been talking a lot about anti forgery tokens, but I still haven’t mentioned the class that is responsible for representing that concept. It’s time to say hi to the… yep, you’ve guessed it: the AntiForgeryToken class! This is a really simple class which exposes only three properties: Salt, Value and CreationDate. Of them, you’ll only able to set the salt (that is, that’s the only property you can influence when you use the helper method). Internally, it uses the RNGCryptoServiceProvider class for generating a random number that guarantees the uniqueness of the token.

And we’re missing only one thing to tie up the anti forgery history: the serialization process. Along the post, I’ve mentioned serialization several times. That job is performed by the AntiForgeryTokenSerializer class which is where all the “cool tricks” are. If you look at the code, you’ll end up seeing that serialization is performed through a singleton instance of the TokenPersister type, which inherits from the PageStatePersister class. The class has to create a dummy page in order to get a valid state formatter which is used for serializing the cookie and hidden field’s values.

And that’s it. Easy, right? Keep tuned for more on the internals of the MVC framework.

by luisabreu | 1 comment(s)
Filed under: ,
The MVC platform: validating submitted data
Sun, Feb 8 2009 14:56

A few posts back, we’ve seen how we could use the AuthorizeAttribute to authorize the execution of a certain request. Today, we’ll look at another Filter which lets you validate the submitted input. Notice that we’re not talking about what I call domain validation (ie, we’re not checking if a field is null or if it has a different type of data than the one that is expected): we’re talking about input validation that ensures that a request doesn’t contain any chars that might be considered dangerous data.

If you’ve been developing web apps with ASP.NET Web Forms, then you’ll probably remember the ValidateRequest attribute of the page directive, right? That’s the kind of input validation I’m talking about here. Let’s get started…

In web forms, you’d generally enable this validation by using the previous attribute on a page (or probably by using the config file). However, that doesn’t really work here in MVC land. Why? If you think about it, it’s really simple: don’t forget that data is recovered from the current request by the controller, not by the view. So, if we want to validate the input values, we need to do it on the controller level.

To solve this problem, the team decided to add a property to the Controller class (in fact, it was added to the ControllerBase class) named ValidateRequest. When this property is set to true, the ControllerActionInvoker instance is responsible for validating the received data before invoking the requested action method.

If you want, you can also use the ValidateInputAttribute for indicating which methods should run the input validation (keep in mind that by default all the input validation will be run in all the requests). The ValidateInputAttribute is a filter attribute which implements the IAuthorizationFilter interface (which is also implemented by the AuthorizeAttribute class), so it’ll run before your action method and before other existing filters.

Using this attribute is really simple: you only need to pass a boolean which enables (or disables) input validation. Here’s an example that shows how you can disable input validation for a method:

[ValidateInput(false)]
public ActionResult About() {
//more code…

If you want, you can also apply the attribute to a controller, disabling or enabling validation for all the methods of that controller. And that’s it for today. Keep tuned for more on the MVC framework!

by luisabreu | with no comments
Filed under: ,
Something bad happened today
Sat, Feb 7 2009 21:50

My HTC Touch phone returned from technical support and the problem wasn’t solved. Even worse, the problem was easily reproduced by me and I didn’t understand how it wasn’t detected by the support guys (simply unbelievable!!!).

Oh well, since it was the third time, I was asked to choose another phone and it was then that something even worse happened: I’ve ended up buying an HTC Pro! (the truth is that it was another cool gift from my super-cool wife!). The experience has been simply great! The interface has really improved and after some getting used to, writing with the keyboard is really super-easy (and way fast than using the letter recognizer)! Lets see how it behaves in the next days…

by luisabreu | with no comments
Filed under:
Snowing again
Sat, Feb 7 2009 0:05

Yep, more snow…which is way too cool! I’ve uploaded some pics to my facebook. Check the snow album here.

by luisabreu | 1 comment(s)
Filed under:
The MVC platform: handling errors
Fri, Feb 6 2009 10:38

Yesterday, we’ve seen how we can handle authorization with the AuthorizeAttribute and how it integrates with the MVC pipeline and with the ASP.NET authentication infrastructure. Today we’re going to keep looking at existing filters and we’ll see how we can use the HandleErrorAttribute for handling exceptions that be raised during the handling of a MVC request.

The HandleErrorAttribute expands the FilterAttribute class and implements the IExceptionfilter interface. This is a really simple interface with only one method:

public interface IExceptionFilter {
       void OnException(ExceptionContext filterContext);
}

As you can guess, this the method that  will be called whenever you have a non-treated exception in an action method. The HandleErrorAttribute implements this method and performs several interesting steps:

  • the first thing it does is check if the current exception has already been handled (probably by some  other filter that has been invoked before) or if custom errors are disabled for the current ASP.NET app (by checking the value of the IsCustomErrorEnabled property of the current ASP.NET context). If any of these is true, then the current filter won’t do anything;
  • after that, it needs to check the “type” of the current exception. If it’s a valid HTTP exception, it won’t do anything (in practice, if the current exception is not convertible to an HttpException with code 500 code, then the filter will simply return);
  • Besides checking the code, it will also see if you have set up the ExceptionType property. You can pass any derived Exception type to this property. Doing that means that the current exception filter will only run for exceptions derived from that type (this  lets you handle only some exceptions or have different views for different exception types);
  • only after doing all those checks will the filter do its “real” work: create a valid ViewResult from its ViewName and MasterName properties and pass that information to the Result property of the ExceptionContext that is passed into the OnException method. It will also change the value of the ExceptionHandled property (which is set to true) and change the status code of the response to 500.

To complete the analysis we still need to answer one question: when are these filters used? If you’ve read this series, then you know that they can only be used from within the ControllerActionInvoker class. What happens is that the InvokeAction method wraps the call to the current action method (which also involves executing authorization filters, action filters and result filters) in a try/catch block. Whenever an exception is triggered (and that exception is not a ThreadAbortException, which should only be triggered by a Response.Redirect call on a web app), it will be caught by that catch block and all the exceptions filters will be give an chance to run.

Even though this post has looked at exception filters, it’s also important to mention  that you don’t need to use this attribute to handle an exception. If  you want, you can also override the OnException method that you inherit from the abstract Controller class. As you’ve seen in the past, the ControllerInvokerAction class will also invoke those methods.

Before ending, there’s still time for an example of how you can use the HandleErrorAttribute. Here’s a snippet that shows how you can redirect the processing of the request to the PrintErrorView of the current controller when you  have and exception of type MyCustomException:

[
    HandleError(
            ExceptionType = typeof(MyCustomException),
            View = "PrintErrorView ")
]
public class HomeController : Controller {
//more code

Notice that you can also specify a master view page by setting the Master property of the HandleErrorAttribute class.

And that’s all for today. Keep tuned for more on the MVC framework.

by luisabreu | 3 comment(s)
Filed under: ,
The MVC framework: wrapping up authorization
Fri, Feb 6 2009 10:38

In the last post we’ve seen how we can use the AuthorizeAttribute for authorizing a specific request. At the time, I’ve forgot to mention one detail regarding authorization. Besides using the AuthorizeAttribute or creating your own custom attribute for deciding who can access a specific action method, you can also create your custom authentication code by overriding the OnAuthorization method that your controller inherits from ControllerBase. This might be a good option when you want to reuse you authorization code through several controllers and their action methods.

by luisabreu | with no comments
Filed under: ,
The MVC platform: integrating authentication and authorization in your apps
Thu, Feb 5 2009 14:06

Today we’ll keep looking at the MVC framework and will see how the you can integrate authentication and authorization in your MVC applications. As we all know, authorization and authentication are different things, but they’re “connected”. I say this because whenever you need to decide if a user can execute a specific operation (ie, whenever you think in authorization), the first thing you need to ensure is that you “know” who the current user is (ie, you have already authenticated the user).

The traditional ASP.NET engine already has some infrastructure in place for performing these operations, but you can’t really reuse the same approaches with MVC. To understand why, you just need to remember that in web forms, you access pages and those are the resources that are protected. With MVC, you’re accessing controller’s actions  and that is what you need to protect.

Despite these differences, you can still reuse the available web forms authentication framework based on the “old” FormAuthentication class for authenticating a user and making that info available for future requests. In fact, if you look at the default code generated by the MVC template, you’ll notice that it already is using that class for authenticating a user.

Ok, now we’re ready to go into authorization. In MVC, you can apply authorization to an action based on username or on group. If you don’t pass any information for those options, then it will only let authenticated users access the protected resource (independent of the its username or associated groups). You use attributes (based on filters) to specify this info, more specifically, instances of AuthorizeAttribute class. If you don’t recall how filters work, probably now is a good time to refresh your memory.

Internally, the class will get the IPrincipal for the user from the current context (recall that MVC apps work over some abstractions which end up delegating to the traditional ASP.NET web forms classes) and then it will see if the user is on the list of users defined and/or if the user belongs to any of the roles passed to the attribute. Here’s an example of how you can use this attribute and apply it to an action:

[Authorize(Users = "luis, john", Roles = "group1, group2")]
public ActionResult Index()
{
   //more code

with the previous snippet, you’ll have to be authenticated as luis or john and you must also belong to group1 or group2 in order to execute the Index action (do notice that if you specify both options, then the current  user needs to satisfy both of them).

Before ending, there’s still time  to mention an interesting detail: in order to guarantee that the action is only executed by authorized users, the class ends up hooking the validation callback performed by the cache. This is an important detail because cache checking is performed before the code on the controller is run and if this hook wasn’t set up, then it would be possible for a non authorized user to get a page that was recently viewed by another authorized user.

And that’s all for today. Keep tuned for more on the MVC framework.

by luisabreu | 5 comment(s)
Filed under: ,
The MVC platform: interacting with the ActionMethodSelectorAttributes
Wed, Feb 4 2009 11:03

In the one of the latest's posts, we’ve seen how we can use the AcceptVerbsAttribute to limit the valid HTTP methods that can be used for requesting the execution of an action method. Today we’ll take a closer look at how these  items are used at runtime (ie, we’ll see how they are used internally by the platform). Lets start by looking at the ActionMethodSelectorAttribute class. In the  RC version, it’s really a simple abstract class with only one method:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public abstract class ActionMethodSelectorAttribute : Attribute {
   public abstract bool IsValidForRequest(
                                 ControllerContext controllerContext, MethodInfo methodInfo);
}

The idea is to insert a base class that you can extend so that you can interact with the runtime and check if some precondition is valid before executing an action method. Now, the real question is when will these classes be called and who is responsible for finding them and using them at runtime.

If you’ve been reading this series, you already know that I’ve written about the IActionInvoker and its default ControllerActionInvoker implementation. In the RC release, there have been some changes (don’t forget that I’ve written that post a long time ago). Internally, ControllerActionInvoker,InvokeAction will defer most of the work into two classes: ControllerDescriptor and ActionDescriptor (which is obtained from the ControllerDescriptor).

In fact, the main responsability of the ControllerDescriptor (by default, you’ll be using the type ReflectedControllerDescriptor) is getting an ActionDescriptor that “abstracts” the action that should be executed for the current request.

Internally, when the ReflectedControllerDescriptor tries to get an ActionDescriptor (btw, you’ll get a ReflectedActionDescriptor),  it ends up running the selection filters that have been applied to the current action method (if any, that is). And that’s how your custom ActionMethodSelectorAttributes end up running. There’s one interesting thing regarding the internal implementation of this feature: if any of the applied ActionMethodSelectorAttributes don’t return true when the IsValidForRequest method is executed, then the FindAction method of the ReflectedControllerDescriptor returns null as if the action you requested didn’t exist. This ends up the current request processing and returns 404 to the client.

The important thing to keep in mind is that if you apply a ActionMethodSelectorAttribute to a method, it will run before all the existing filters and if its IsValidForRequest method returns false, it will end up the processing of the request and none of your filters or action code will ever execute. Keep this in mind when you create your own ActionMethodSelectorAttribute derived classes.

And that’s it for today. Keep tuned for more on the MVC platform.

by luisabreu | 1 comment(s)
Filed under: ,
Karl Seguin on the MVP award
Tue, Feb 3 2009 14:26

Karl has an interesting post with his ideas on the subject. Even though I’m still an MVP, I couldn’t agree more with his thoughts.

by luisabreu | 2 comment(s)
Filed under:
The MVC platform: more on dropdowns and listboxes
Tue, Feb 3 2009 12:41

A few days ago I’ve talked about how you could use the helpers to generate dropdowns and listboxes. As I’ve said, you need to build a collection of SelectListItems in order to build these controls. What I didnt’ mentioned at the time was that there is an easy way to convert a custom collection (ie, something which implements IEnumerable<T> interface) into a collection of SelectListItems. To do that, just instantiate the SelectList (or MultiSelectList, if you’re working with listboxes and want to select several values) class.

Here’s a quick example. Suppose you’ve got a class that looks like this:

public class Item    {
    public Int32 Id { get; set; }
    public String Description { get; set; }
}

And that you’ve also got a collection with several items:

var items = new[] {
      new Item {
                  Id = 1,
                  Description = "first"
          },
      new Item {
                  Id = 2,
                  Description = "second"
          },
      new Item {
                  Id = 3,
                  Description = "third"
          }
};

And that you want to fill a dropdown and select item 2. Here’s  how you can do that (I’m using a non-typed view here since I’m in a hurry :)):

ViewData["optionsDrop"] = new SelectList( items, "Id", "Description", 2 );

As you can see, I’m passing the collection and saying that the Id property should be used for getting the value of the OPTION element and that the Description will return the text for that OPTION element. I’m also saying that element with value should be selected by default. Now, you only need to ensure that your dropdown is named optionsDrop and you’re ready to go:

<%= Html.DropDownList(  "optionsDrop", "Choose an option"   ) %>

And that’s it. More on the MVC platform on future posts.

by luisabreu | with no comments
Filed under: ,
The MVC framework: the AcceptVerbsAttribute class
Tue, Feb 3 2009 10:44

The AcceptVerbsAttribute was introduced in a previous release of the framework and its main objective is to let restrict an action method to certain HTTP method(s) (PUT, POST, etc). So, lets reuse the default web site that is created from the ASP.NET MVC and change the About action method default so that it can only be used through a post request. To achieve this, you only need to add the AcceptVerbsAttribute to the method:

[AcceptVerbs("post")]
public ActionResult About() {
    return View();
}

And now if you try to execute this action from a request that isn’t made through a post you’ll get a 404 error. You’ll trigger this error if you try to execute this action through the About option you’ve got on the top menu.

When you use this class, you have two options:

  • you can specify the allowed verbs though the constructor that accepts a params arrays of strings;
  • You can use the overloaded constructor which receives a value from the HttpVerbs enumeration, which, as you might expect is a flags enumeration.

As a side note, take a look at the code and check the way the HttpVerbs enumeration is implemented…yep, they’re using the left shift operator in order to shift the existing bits in 1 n bits to the left. I find this interesting because most implementations of these enumerations will only use integers (calculated by multiplying the previous value by 2). Ok, back to business…

The AcceptVerbsAttribute expands the abstract ActionMethodSelectorAttribute class which ony has one method:

public abstract bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo);

As you might expect, AcceptVerbsAttribute implements this method by recovering the HTTP method from the current request and by checking if  is is in the allowed list of verbs allowed by the current instance. And that’s it…there’s really nothing more to say about this class. You’re probably wondering on how this class is used by the runtime, but we’ll leave that for a future post. Keep tuned!

by luisabreu | 5 comment(s)
Filed under: ,
MVC platform: filling form’s fields from collection is broken for strongly typed views
Mon, Feb 2 2009 21:24

Problems and workaround described here.

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