Posts de ‘Claudio Figueiredo’

[Claudio Figueiredo] It’s all about people

Monday, November 24th, 2008

Just read the article from James Shore, about The Decline and Fall of Agile.

It reminds me of a statement from a so-called programmer that:

"As every software has a bug, I’m only contributing with the entropy."

I think that’s pretty obvious that even the best Practice, when executed in vain is poisonous and will, almost surely, end with bad results.

Living in a waterfallish environment for so long, helps to see it more clearly.
I had two years, good years, working with Waterfall methodologies with no issue at all.
It was ‘no Agile’ but we had commitment from the teams, common sense, good established design practices, short iteration burst and a strong change management discipline.

Can’t say it was easy or natural as a real Agile methodology would be, but we never had a complaint or unmanageable issue.

I think that Mr. Shore is mistaken on his finger-pointing. It’s not about Agile, XP, SCRUM or anything, it’s all about people and what they do with the tools they’ve been given.

[Claudio Figueiredo] Thought of the Day

Friday, August 1st, 2008

Isn’t loopback a redundancy?

If it’s a loop wouldn’t it be back anyway? :)

[Claudio Figueiredo] ASP.NET MVC Preview 4 Released

Wednesday, July 16th, 2008
  1. Read the Title
  2. Grab while it’s hot

Cheers,

[Claudio Figueiredo] ASP.Net MVC ActionFilters

Sunday, July 13th, 2008

I’m a lame blogger, I know. There’s been more than two years that my friend Heynemann has been teasing me to post more, and it’s starting to happen more naturally these times. The reason that I blog less than I’d wish for is that I’m crazy about coding. That’s where I tend to focus most of my time, but I’ll keep posting more frequently now. The reasoning behind this introduction is to assure all my three readers (you know who you are lol), that my series on .Net MVC will be continuing soon.

Action Filters - Why and How?

Action Filters are .Net MVC native way of adding intercepting capabilities to your application. It’s a non-imperative way of adding some AOP to your Controller’s Actions without resorting to AOP or IoC frameworks.

It’s a sweet move on the part of the development team, and It’s something that makes SoC and extensibility in .Net MVC very easy to implement.

Well, since the first time I’ve read about it, I knew it would be a perfect fit to integrate with ValEver.

ValEver (short for Validation Everywhere) was one of the neatest pieces of code ever produced by Bernardo and I had the pleasure of developing its integration with Windsor Container some months ago.

I’ll try to give some examples here on how to use ActionFilters through implementing integration with ValEver and check on the benefits of this happy union. :D

ActionFilters provide a declarative way to access the executing context prior to, and following, the execution of an action.

It has a simple yet meaningful contract:

public abstract class ActionFilterAttribute : Attribute, IActionFilter
{
 
    // Methods
    protected ActionFilterAttribute();
    public virtual void OnActionExecuted(ActionExecutedContext filterContext);
    public virtual void OnActionExecuting(ActionExecutingContext filterContext);
    public virtual void OnResultExecuted(ResultExecutedContext filterContext);
    public virtual void OnResultExecuting(ResultExecutingContext filterContext);
 
    // Properties
    public int Order { get; set; }
}

Most methods are self explanatory but the important ones in what I’m trying to achieve are OnActionExecuting and the ActionExecutingContext.

That’s the Pre handler of a Controller’s Action call. Through it you can reach the Context and interact with it.

First thing I did, as any good developer should do, was a test. And so it came:

[ValEverActionFilter]
[ValidationShouldThrow]
public ActionResult Index([Required("Supply a valid parameter")]string parameter1) {
    return View();
}

The ValidationShouldThrow and Required(“Supply a valid parameter”)] attributes are native from ValEver. The first being a marker to control behaviour, the second being ‘The’ validation of a parameter.

And from this test came my custom ValEverActionFilter:

public class ValEverActionFilterAttribute : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        base.OnActionExecuting(filterContext);
    }

This small piece of code is all that’s needed. Besides the business logic, which will be added later, all I need are the parameter values . Interestingly we have them. The neat trick here is the context.

The ActionExecutingContext allows us to direct access to info such as …

//The calling Action
public MethodInfo ActionMethod { get; private set; }
 
//The parameters and it's values
public IDictionary<string, object> ActionParameters { get; private  set; }
 
//The request HttpContext 
public HttpContextBase HttpContext { get; internal set; }
 
//Any data regarding the Routing used in the call
public RouteData RouteData { get; internal set; }

… being able to manipulate almost anything inside the call’s context.

Then again, I settled to test. But this time I need an integrated test between the Controller Action and the Validation through the call of ValEverActionFilter.

It happens that only calling the Action is not enough. And it makes sense. The controller is not so special alone after all. The ActionFilter calling is done on the Handler instantiation on ASP.NET.
“- So, no problem. How hard could it be?” TM

After lot of googling I found how hard it was. There’s no out-of-the-box solution for this kind of test. So I set to make mine and it came as:

[Test]
public void ShouldThrowOnInvalidParameters() {
 
    TestingController controller = new TestingController();

 
    Assert.Throws<ValitationFailedException>(() => 
        controller.InvokeActionWithFilters<TestingController>(p 
            => p.Index(string.Empty)));
}

The InvokeActionWithFilters Extension Method mimics what the ASP.NET does. Supplying defaults and calling the ActionFilter’s hooked events in the right time with the right context.

Then I just had to write the business logic to my filter, and make tests go green.

public class ValEverActionFilterAttribute : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
 
        var methodInfo = filterContext.ActionMethod;
 
        AddValidationParameters(filterContext, methodInfo);
 
        bool isValid = ValidationContext.Validate(filterContext.Controller) &&
                                     ValidationContext.ValidateArguments(methodInfo);
 
        ThrowIfRequiredByDecoration(isValid, methodInfo);
 
        base.OnActionExecuting(filterContext);
    }

Nothing more had to be done to have it interacting with the method call.
The filterContext.ActionMethod contains all the information needed. Parameters and it’s values too.

Conclusion

So, despite the little trouble testing the ActionFilters with the call’s context, it was easy extend and interact with one of the core aspect of a MVC framework and, better yet, keeping the concerns apart. Just some other cool things you can do with ActionFilters:

  • Cancel Action Execution
  • Interact with HttpContext
  • Override/fill parameters values
  • Set manually your own ActionResult

This opens so many possibilities that it makes me glad to see development going in this direction and delivering such good feats.

The full code of the sample application can be found here.

Cheers.

[Claudio Figueiredo] Lack of Tests

Wednesday, July 9th, 2008

You might not hear me, nor Mr. Beck or anyone, but certainly you’ll hear Dart Vader:

LackOfTests

[Claudio Figueiredo] When life should imitate fiction :)

Saturday, July 5th, 2008

Somewhere, over the rainbow…

[Claudio Figueiredo] When fiction imitates life…

Saturday, July 5th, 2008

That’s how one feels when he’s reprehended for Unit Testing.

[Claudio Figueiredo] ASP.NET MVC Experiences 2, Overview

Monday, June 30th, 2008

Setting expectations clear

What I’m trying to achieve here is not a "how to use" ASP.NET MVC or a Tutorial. For those I really recommend Scott Hanselman’s videos which were my first source on the subject.

It’s a hands on experience, a spike if you will, with the most prominent features of the framework.
It’s a evaluation on how it works checking it advantages and disadvantages, from my point of view, and trying reducing some friction that I’m encountering on using MonoRail in my new project. Don’t get me wrong, I have nothing against MonoRail, it is still the most mature, featured MVC implementation on .Net world and I would not find any friction on it if not checking on .Net MVC features.

Evaluation procedure

The criterias that I’ll use in my evaluation will be, in the following order of importance:

  • Testability
  • SoC
  • Extensibility
  • Manageability

This analysis might not be linear, but these will be the focused points.

Overview

First time I heard about .Net MVC and checked out it’s features, it looked to me a badly built copy of MonoRail. But I soon realized some very nice differences. Not on the project itself, but the behaviour of P&P conducting it’s development. The way they positioned themselves eager to hear the community feedback led to great improvements over the three released iterations. That made me realize the fact that the similarities between them were not coincidental. Maybe the coincidences lie in the fact that they are both implementations of the same pattern, or more likely intentional (unless Filters and ActionFilters are both Design Patterns affiliated to MVC and I don’t know ).

Anyway, this is good because the transition between them is almost seamless, but that’s another topic.

Application Model

Almost everyone I talked about it, thinks that .Net MVC is sitting onto an Application Model of it’s own. But the fact is that it’s standing over the ASP.NET 2.0 Application model. Just as any other ASP.NET 2.0 application, it inherits from HttpApplication and has it’s events and life cycle. In fact, the new cool routing system is registered just in Application_Start as any global register.

This allows some interesting (and freaking) options as running both WebForm and MVC simultaneously.

Even though I didn’t expect a whole new web platform, I kinda hoped the separation would be a little more clear, not that this clouds the benefits that it provides. What really bother me is finding out that the standard ViewEngine, implemented by the ViewPage, inherits directly from our dear old friend System.Web.UI.Page. This open up even freakier possibilities. The fact that you can do the same funky thing that you do with a WebForm on a MVC View really scares the hell out of me.

First thing a tried when I find that out, was: add a Server form, an asp:button, an event handler and, Voilá: - Back to the same beach we’ve been swimming the past few years. I know that the fact the you could do something doesn’t mean you should or would do it, but it gave me shivers anyway.

This also showed me that you could add any WebControl you like on the Page, and work with it freely as you would on WebForms but in fact you wouldn’t like, more on that later.

Views

As said before, the default ViewEngine is basically a HttpHandler inheriting from the standard Page model. That said, one may conclude that anything you can do on a Page could be done on a ViewPage and most can actually be done. Here a some observations about this cross model that I checked:

  • The layout scheme, as expected is the same MasterPage mechanism used in WebForms.
  • Custom controls can be used the same way if you add a server form to the View.
  • Yes YOU HAVE VIEWSTATE, but only when adding a server form to the View, otherwise you get a nice clean html to work with.
  • You can use UserControls inside a ViewPage, but you’ll end up with the whole ViewState/ServerForm stack polluting to your code.
  • You’ve got tracing enabled just as a WebForm.

The above issues worried me a little. … mixed up model but spaghetti code?

Then again I remembered that’s it’s a Microsoft Product anyway. No rants here, just saying that Microsoft is not a charity and as such can’t avoid cathering for the main customers in their current business model. This is just something I (and you reader) should bear in mind while reading this.

The good thing here, is that the View layer was nicely built. Although they allow more than I would like, what is done here is done in a beautiful way. View testing has been somewhat neglected on implementing MVC applications, but here we get a stronger model which we can test and extend in a natural way.

Some key points on Views:

Convention over Configuration

The first thing I noticed, and one that made very happy is that ASP.Net MVC Views and setting approach follow strictly the CoC principle. It’s is such on MR and should not be changed, so common sense prevailed here for the good.

The rule here is putting your views on /Views/{controller}/{action} and nothing more needs to be done. It can be changed setting a new ViewLocator, which is a resolver for View’s paths.

Even though everything seems the same, one addition that I really liked is the Shared Views concept, which is so obvious that I’ll refrain from explaining.

The introduction of the concept of Typed Views.

Binding a View to a model seems very natural on MVC. And every view is bound to a model indirectly. The introduced change allows you to strongly-type your View’s Data to it’s own Model, thus making it more intuitive than generic views, that most of the time aren’t really generic. Let’s check how’s that works.

That’s the code for a view called List that’ll be rendered by the List Action of the Home Controller.

   1: namespace Stormwind.MVC.Template.Views.Home {
   2:     #region usings
   3:  
   4:     using System.Web.Mvc;
   5:  
   6:     #endregion
   7:  
   8:     public partial class List : Viewpage {
   9:     }
  10: }

And that’s the Template:

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="List.aspx.cs"           Inherits="Stormwind.MVC.Template.Views.Home.List" %>
   2: <ul>
   3:     <%
   4:         foreach (var pair in (IList<string>)ViewData["listItem"]) {
   5:     %><li>
   6:         <%= pair %></li>
   7:     <% } 
   8:     %>
   9: </ul>

There’s two important points here:

  1. The first is ‘public partial class List : ViewUserControl‘, notice that the view inherits from a specific base class. Among other things, this base class contain a property call ViewData. ViewData is nothing more than a KeyValuePair collection that is used to interchange data between the controller and the View. It’s almost exactly the same as a MonoRail property bag.
  2. The second is ‘ var pair in (IList<string>)ViewData["listItem"]‘. Notice the cast here. As an untyped collection, ViewData items should be casted before used in a not so intuitive way. Worst of all making refactoring harder and the view error prone.

The concept of Typed Views, come to solve these issues. Check it out.

   1: public partial class ListTyped : ViewPage<List<string>> {
   2: }

Notice that the view now inherits ‘ViewUserControl<List<string>>‘ allowing us to:

   1: <ul>
   2:     <%
   3:         foreach (var pair in ViewData.Model) {
   4:     %><li>
   5:         <%= pair %></li>
   6:     <% } 
   7:     %>
   8: </ul>

The inherited View sets the Model allowing us working more naturally and refactoring friendly now.

The ability to easily create and change a ViewEngine.

Creating and changing View Engines in MonoRail is not too difficult, but changing them in runtime is a little painful and doing that through Windsor makes it feels makes it feel unnatural and definitely not the expected behaviour, or at least one that requires more configuration than expected.

Creating a new view engine is incredibly easy, since the IViewEngine contract only has one method to implement - The RenderView method.

Of course, this post does not sums everything that the MVC Framework has to offer, but believe me, there’s not much more either. You’ll see soon in another post.

Well, Views are not that different from MonoRail or other MVC implementations, and given you have the ability to implement your own, it’s a very flexible structure.

Next post: Controllers.

Stay tuned.

[Claudio Figueiredo] ASP.NET MVC Experiences - Part 1, The Setup

Thursday, June 26th, 2008

First of all I did what as every developer experienced in the RTFM methodology should do I went to it’s Site and download the installer.

As I didn’t found the binaries and was not in the mood of build the source (oh yeah, there is a source available for a change) I’ve downloaded the Installer just to check it out.

As a I installed the package, the usual NNF*, I was currently happily surprised to find no reference in the GAC. Only changes noticed so far were a new Visual Studio Template called ASP.NET MVC Web Application and a Start Menu Item Microsoft ASP.NET MVC Preview 3 which leads you the a folder containing the set of assemblies needed to run a ASP.NET MVC Application. (Duh!)

Normally I would go my usual way, creating a new structure using a Stormwind Project template and setting the references, but as I’ve been having a nice user experience so far I’ve decided to take the full trip MS induced experience.

Open up Visual Studio, selected New Project, Visual C# / Web and ASP.NET MVC Web Application named my Project , and then the first surprise:

asp_mvn_unit_test_setup

 

 

 

 

 

 

 

 

 

Yes, it’s a nice change see anyone at MS thinking in Test First, but the only test framework supplied is the MS Test. First I got a little angry, but then I realized that it’s a MS product after all. :)

Well I’m a NUnit guy and as such I started digging how to make ASP.NET MVC works with another test framework.

After taking a look at it, and checked out it really works, I decided it was not worth it.

The main issue is exactly the wizard that, for some arcane reason, only is setup to show the Test Framework of your choice, changing a registry key.

Hope you now I didn’t like it a bit, so I decided to make my own template with the basic structure settled.

Thanks to my friend Bernardo cant-wait-till-you-get -home-so-I-did-it Heynemann, we already got Windsor container up and running.

Next Post, working with ASP.MVC and overall feeling so far.

*NNF:Next, Next, Finish.

[Claudio Figueiredo] ASP.NET MVC Experiences

Thursday, June 26th, 2008

There´s sometime now there I´ve been wondering toying with the new ASP.NET MVC. I´ve been really impressed with what I´ve been hearing about it, and specially what I´ve been reading in Scott Guthrie´s blog, but only after the RC3 it got me really impressed.

So I decided to move my fat a$$ a little and do some constructive blogging for a change and create a series of introcdutories and eventually more advanced posts about my experinces with this new toy.

Stay tuned.