December 2008 - Posts

Happy New Year!
Tue, Dec 30 2008 20:40

I’m still recovering from Christmas but New Year’s already here. So what can I say? The only thing I can think ok is wish everyone a Happy New Year!

by luisabreu | with no comments
Filed under:
The MVC platform – Forms extensions
Fri, Dec 26 2008 23:02

In the lasts posts, we’ve started looking at some of the HtmlHelper extension methods that you can use to render controls on your forms (we’ve looked at several methods you can use to render HTML INPUT controls). Today we’re going to keep looking  at the extenders, but we’ll concentrate on how to generate forms on your views.

The FormExtensions.cs file contains several extension methods that you can use to create forms. You’ll find several overloads of the BeginForm and EndForm methods. The BeginForm method lets you set up the attributes you’d normally apply to an HTML form (ie, action and method). There are overloads of this method that will let you fill those attributes automatically or you can use any of the overloads that lets you specify the value of each of those attributes. As you might expect, some of the overloads let you pass the name of the controller/action for specifying the action (ie, the url from where your form will post its data).

The BeginForm methods render the <form> begin tag into the response stream and returns an instance of type MvcForm. This simple class implements the IDisposable method. Its Dispose method implementation is responsible for closing the end form tag. So, you could generate a form by writing something like this (I’ll be rewriting the form I’ve presented in one of my previous examples):

<% using( var frm = Html.BeginForm("HandleFormData", "Home")) {%>
<label for="name">Name:</label><%=Html.TextBox("name")%>
  <%=Html.ValidationMessage("name", "*")%>
  <br />
  <label for="Password">Password:</label><%=Html.Password("Password")%>
  <%=Html.ValidationMessage("name", "*")%>
  <br />
  <label for="male">Male:</label>
  <%=Html.RadioButton("sex", "male", new {id = "male"})%>
  <label for="female">Female:</label>
  <%=Html.RadioButton("sex", "female", new {id = "female"})%>
  <input type="submit" id="myBt" value="Try to submit" /> <br />
  <%=Html.ValidationSummary()%>
<%}%>

If you don’t really enjoy the using syntax, then you can use the BeginForm/EndForm pair:

<%Html.BeginForm("HandleFormData", "Home"); %>
     <label for="name">Name:</label><%=Html.TextBox("name")%>
      <%=Html.ValidationMessage("name", "*")%>
      <br />
      <label for="Password">Password:</label><%=Html.Password("Password")%>
      <%=Html.ValidationMessage("name", "*")%>
      <br />
      <label for="male">Male:</label>
      <%=Html.RadioButton("sex", "male", new {id = "male"})%>
      <label for="female">Female:</label>
      <%=Html.RadioButton("sex", "female", new {id = "female"})%>
      <input type="submit" id="myBt" value="Try to submit" /> <br />
      <%=Html.ValidationSummary()%>
<%Html.EndForm();%>

Notice that since the BeginForm doesn’t return a string, you must not use the Response.Write “shortcut” (ie, <%= %>) and you must end up the statement with a ;. So, now you’ve got at least three ways of generating a form:

  • you can use the classic approach, where you write the HTML directly (as we’ve seen in the oldest examples);
  • you can use the disposable syntax (based on the using helper);
  • you can use the BeginForm/EndForm pair of methods.

Any of these options works well, so choose the one you prefer (in most of the examples I’ve built, I did use the first approach, where I explicitly write the FORM tag). On the next post, we’ll keep up looking at the HtmlHelper extension methods. Keep tuned!

by luisabreu | with no comments
Filed under: ,
New features in ASP.NET 3.5
Wed, Dec 24 2008 18:31

I’ve just noticed that there’s a Wrox Blox by Wally which presents the new ASP.NET features introduced by .NET 3.5 Service Pack 1. If you want to know more about these features, then go ahead and read the blox.

by luisabreu | with no comments
Filed under:
Merry Christmas to you all!
Tue, Dec 23 2008 22:55

Yep, it’s that time of the year again… I’d like to wish you all a Merry Christmas and a Happy New Year!

And don’t forget to have fun, ok? :)

by luisabreu | with no comments
Filed under:
Nightwish – a study case on how not to treat “stars”
Mon, Dec 22 2008 22:22

Yesterday I was watching the last “decent” concert from Nightwish (ok, I really should have said their last concert where Tarja was the main singer). There is a good chance that you don’t know Nightwish. So, a quick recap is in order. Nightwish is a Finnish band which combines strong vocals (especially when they had Tarja) with symphonic power metal. Well, after the End of an Era concert, they decided to dismiss the vocalist because (according to them) she was starting to behave like a start, missing rehearsals, thinking only in money, etc. Bottom line: they felt that they she was overrated.

Ok, so, why do I listen to Nightwish? It’s not really because of their lyrics or music only…I mean, the final result (music + vocals) is really good, but what made the difference was Tarja. Period. And that gives her the  right for special treatment. Get over it!

Don’t believe me? ok, then compare their actual singer (Anette) with Tarja and then let me know what you think. Don’t get me wrong: Anette is a  great singer. The problem is that before her, there was Tarja. I mean, if you start listening to Nightwish now, you’d be saying: ok, she (Anette) is great. what’s all this fuss about? but then you’ll just have to listen to a music with Tarja and you’ll have the “aha” moment.

I guess that if they’ve read Peopleware then they would have some ideas on how to make their team (ie, band) jell. It’s true  that you need a strong team and that making everyone work together is really hard. However, don’t forget the individual. You can have a good team, but a great team will only be possible whenever you have the right “starts” and when you manage to make them all work towards an objective!

Look at Nightwish as a case study of how not to treat “starts”. Remember: they do make a difference and when you find one, make it hard for them to want to leave.

by luisabreu | 10 comment(s)
Filed under:
MVC Design Gallery announced
Fri, Dec 19 2008 14:57

Scott Gu announced the new MVC Design Gallery today. He also talked about several changes that will be presented on the RC version of ASP.NET MVC.

by luisabreu | 1 comment(s)
Filed under: ,
The MVC framework – refactoring the previous example
Thu, Dec 18 2008 14:28

In the last post we’ve seen a really simple example of how to use the existing HtmlHelper methods for building a simple form. We’ve also seen how to validate those results and how to pass them for further processing. to achieve that, we used all “low-level” methods provided by the framework (ie, we’ve resorted to using the Request.Form collection to get all the submitted values from the form).

At the time, I said that there was an easier way to do the same with less code. In this post I’ll show you how! We’ll start by creating a new class for keeping the info introduced by the user. I’m calling it UserInfo:

public class UserInfo    {
        public String Name { get; set; }
        public String Password { get; set; }
        public String Sex { get; set; }
}

Now, the idea is to use the binding helpers to get an instance of type UserInfo automatically from the data that is submitted by the form which should be passed to our action method. Here’s the code for the HandleFormData:

public ActionResult HandleFormData([Bind(Prefix = "")]UserInfo user) {
   if (user == null ||
        String.IsNullOrEmpty(user.Name) ||
         user.Name.Length < 4) {
                ViewData.ModelState["name"].Errors.Add(
                      "name must have more than 4 chars");
                return View("Index");
    }
    return View("UntypedUserInfo",user);
}

If you compare this code with the previous example, you’ll notice that we’ve improved its readability while simultaneously reducing the number of lines of code. Lets take a deeper look at what’s going on here:

  • We’ve changed the HandleFormData method so that it receives an instance of UserInfo. The idea is to delegate the creation and initialization of that instance to the framework;
  • The BindAttribute instructs the framework to create and set the values of user from the values submitted by the form. The user of Prefix is necessary in this case. Without it, and by default, the framework would search for fields named user.name, user.sex, etc. (the  name user. comes from the name of the parameter). Another thing to keep in mind is that the framework will use the DefaultModelBinder class for initializing the class. I’ve already written about the binding model in the past, so now might be a good time to review that info. btw, Scott Gu has also a good post on how to use this feature.
  • Instead of using an untyped view, we’re now using type view so that we have compilation verification and intellisense when filling the info on our view. That’s why we’re forwarding the UserInfo to the View call.

I’m not sure on what you think about this, but I do like the end result. Yes, during the first time you might think that there’s simply too much magic going on here, but after understanding the basics and understanding what’s going on, it’s undeniable that we do really get better results (cleaner code which is really more expressive, right?).

We still need to change the view. The first thing to do is to change its codebehind file:

public partial class UntypedUserInfo: ViewPage<Data> {
}

And now, we can simply change the code on the aspx file to this:

<asp:Content ID="Content1"
         ContentPlaceHolderID="MainContent" runat="server">
         name: <%= Html.Encode( ViewData.Model.Name ) %><br />
         password: <%= Html.Encode(ViewData.Model.Password)%><br />
         sex: <%= Html.Encode(ViewData.Model.Sex)%><br />
</asp:Content>

Ok, to me this looks much  better. What do you think?

We’ll keep going on the next posts. Stay tunned!

by luisabreu | with no comments
Filed under: ,
The MVC platform – the HtmlHelper class (part III)
Thu, Dec 18 2008 12:17

After the slight detour for introducing validation support, it’s time to go back to the helpers which you can use for generating HTML controls from your views. I think that the second post on the HtmlHelper class should have been more than enough for understanding how things work, so in this post I’ll just jump into a description of the remaining methods exposed by the InputExtensions static class.

Besides the TextBox method (which, as we’ve seen, is  used for generating simple textboxes), you’ll also find:

  • CheckBox: used fore generating checkboxes (ie, HTML elements similar to <input type=”checkbox”>);
  • Hidden: used for inserting hidden textboxes (ie, HTML INPUT elements with the type set to hidden);
  • Password: ok, you’ve guessed it! It’s used for generating input fields that will be used for entering passwords (ie, this method inserts <input type=”password”> elements on the page);
  • RadioButton: used for inserting radio buttons elements on the page (ie, this method inserts <input type=”radio”> on the page).

Lets build a form that shows how to use some of these methods. To do that, I’ll just change the code that exists in the Index view you get whenever you create a new MVC project form the VS template. Here’s what I’ve added:

<form method="post" action="<%= Url.Action("HandleFormData", "Home") %>">
      <label for="name">Name:</label><%= Html.TextBox( "name" ) %>
      <%= Html.ValidationMessage("name","*")%>
      <br />
      <label for="password">Password:</label><%= Html.Password( "password" ) %>
      <%= Html.ValidationMessage("name","*")%>
      <br />
      <label for="male">Male:</label>
      <%= Html.RadioButton("sex", "male",  new {id = "male"}) %>
      <label for="female">Female:</label>
      <%= Html.RadioButton("sex", "female",  new { id = "female" })%>
      <input type="submit" id="myBt" value="Try to submit" /> <br />
      <%= Html.ValidationSummary() %>
</form>

So, what do we have here:

  • we’re using labels that are associated to each of the controls;
  • we’re setting the ID of each radio button explicitly so that we can associate a label to each option. Btw, and since we’re talking about radio buttons, notice that the previous snippet won’t select any option by default. If you need that you can use one of the overloads that sets the checked property of the control or, way better, add code that sets the ViewData dictionary of the control to the value you want (for instance, lets say you want to select male by default. Then you’d add this to the method that renders the initial form: ViewData["sex"] = "male";). Notice that the second option is better because it will let you maintain the value introduced by the user if there’s an error on the form (the first will always set the option to the predefined value and the value selected by the user will be lost). More about this on the next paragraphs;
  • we’re using yesterday’s ideas and we’re reusing the logic for validation;
  • the form ends up calling the HandleFormData action method on the Home controller.

The HandleFormData action method is responsible for performing validation on the incoming data. If everything is OK, it will simply redirect that info to another view which, in this case, will only display that info on a aspx page. Here’s the code for HandleFormData:

public ActionResult HandleFormData() {
    var name = Request.Form["name"];
    ViewData["name"] = name;
    ViewData["password"] = Request.Form["password"];
    ViewData["sex"] = Request.Form["sex"]; 

    if (String.IsNullOrEmpty(name) || name.Length < 4) {
        var state = new ModelState()
                        {
                            AttemptedValue = name
                        };
        state.Errors.Add("name must have more than 4 chars.");
        ViewData.ModelState.Add("name", state);
        return View("Index");
    } 
       return View("UntypedUserInfo");
}

Ok, not really the best code in the world, but it will do for this short demo. As you can see, I start by filling the view data dictionary so that the controls on the form will have the values entered by the user if there’s an error.The same view data will also be used by the UntypeduserInfo view which is only responsible for showing the info introduced by the user. here’s the code on that page:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="UntypedUserInfo.aspx.cs" Inherits="MvcDemo.Views.Home.UntypedUserInfo" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    name: <%= Html.Encode( ViewData["Name"] ) %><br />
    password: <%= Html.Encode( ViewData["Password"] ) %><br />
    sex: <%= Html.Encode( ViewData["Sex"] ) %><br />
</asp:Content>

If you’re an “experienced” ASP.NET MVC developer, you’ll be thinking that there must be a better way of doing this (and yes, I believe there is and we’ll show it in a future post), but this small sample should be more than enough to give you an idea of what you can do with the helpers.

And I believe that’s all for today. We’ll keep looking at the MVC framework on the next posts. Keep tuned!

by luisabreu | with no comments
Filed under: ,
The MVC platform – validation support
Wed, Dec 17 2008 15:32

Today we’re going to look at the validation support introduced by the framework. Do keep in mind that we’re not talking about using validators like the one you have in the ASP.NET web forms world. Nop! here validators are only responsible for showing an error message to the user. In practice, this means that you have to signal that a control has an incorrect value and the MVC framework will pick that info and show the appropriate error message where you’ve  dropped the “validator”.

The best way to understand this is to give a simple example. Let’s reuse yesterday’s form:

<form method="post" action="">
  <%= Html.TextBox( "name”) %>
  <input type="submit" id="myBt" value="Try to submit" />
</form>

We’ll also assume that we can only accept non-empty names with more than 4 characters on the name textbox. When that doesn’t happen, we will want to add a message saying that. In order to show a message next to the control, we can simply call the ValidationMessage method where we’d like to show the error message:

<form method="post" action="">
  <%= Html.TextBox( "name", "hallo", new { @class = "myInput"} ) %>
  <%= Html.ValidationMessage("name")%>
  <input type="submit" id="myBt" value="Try to submit" />
</form>

Notice that the ValidationMessage extension method will only be responsible for showing a specific error message. We still need to define that message and signal when there’s an error with the value passed to the control. As I’ve said, we’re only accepting non-null names with more than 4 characters. To signal that there’s something wrong with the value of a control we will need to add an error message to the  ModelState instance associated with that control. The simplest way to do this is to write the following code on the controller’s method that is responsible for handling the request:

var name = Request.Form["name"];
if( String.IsNullOrEmpty(name) || name.Length < 4 ) {
   ViewData.ModelState.AddModelError("name", 
                                                 "name must have more than 4 chars.");
}

If we run the page and write “la”, then this is what we’ll see:

validation1

The AddModelError method will end up creating a ModelState instance and it will associate it to an existing control named “name” (that is, if there isn’t any associated with the control identified by the first parameter) . Note that there’s also an overloaded version of this method which receives an exception.

There’s an interesting gotcha here which I must mention. The ViewDataDictionary.ModelState property presented in the previous snippet isn’t really of type ModelState. The fact is that it’s a property of type ModelStateDictionary which  is a dictionary of pairs string/ModelState (where the string identifies the control’s name on the page).

Now is probably a good time to look at the ModelState class. It’s really a simple class with only two properties: Attempted Value and Errors (i’m only showing its public API).

public class ModelState {
    public string AttemptedValue {
        get;
        set;
    }
    public ModelErrorCollection Errors {
        get {
            return _errors;
        }
    }
}

As you have probably guessed by now, calling the AddModelError method results in the instantiation of a new ModelError object which is added the to ModelState instance. The ModelError class is really simple and it has only two properties: Exception and ErrorMessage. One thing I didn’t mention is that you can add several error messages by calling AddModelError several times.

The AttemptedValue property of the ModelState class isn’t set up when you call the AddModelError method. This property is important and you can use it to pass a value that will be shown by the control. For instance, when you look at the previous figure, you’ll notice that the textbox is empty when there’s an error with the input. A better option would be to show the wrong value entered by the user. Here’s how you could do that:

var name = Request.Form["name"];
if( String.IsNullOrEmpty(name) || name.Length < 4 ) {
   var state = new ModelState() {
                    AttemptedValue = name
   };
   state.Errors.Add("name must have more than 4 chars.");
   ViewData.ModelState.Add("name", state);
}

If you load the page and pass it an incorrect value, you’ll notice that you’ll get the error message and that the textbox won’t loose the last introduced value.

Even though you can pass several error messages to a control, the truth is that with the current API, you’ll only see one error per validator associated to a specific control. You can easily change this behaviour (I’ll probably show an easy way in the next post) if you require.

Before ending this post, there’s still time to present the ValidationSummary method extension. As you’ve probably guessed, this method will show you all the error messages associated with the controls shown by the current view. It will generate an unordered list with all the errors maintained by all the ModelState instances that have been registered with the ViewDataDictionary instance.

When you use a summary, you probably will not want to repeat the error message in front  of the control. In those cases, you could probably identify the control that has an error with a special symbol (ex.: *) and just put the error message on the summary. To achieve this, you’ll need to specify the error message presented by the validator by calling one of the overloads of the ValidationMessage method that receives a validation message. Changing the view so that it looks like the following snippet is all that it takes to get this behaviour:

<form method="post" action="">
     <%= Html.TextBox( "name" ) %>
     <%= Html.ValidationMessage("name","*")%>
     <input type="submit" id="myBt" value="Try to submit" /> <br />
     <%= Html.ValidationSummary() %>
</form>

Finally, there’s still time to talk about the options you have to customize the style of the errors presented by the “validator” and the validation summary. The easiest way to customize them is to use the overloads that receive the attributes rendered by the control. Both methods have two overloads that will let you specify the values of the attributes: one uses the anonymous object approach; the other ends up using a dictionary. By default, the framework ends up using some predefined css style classes. You can always create your own too and then pass that info through one of the overload methods. Here’s a quick example:

<%= Html.ValidationMessage("name","*", new { @class="test"})%>

In this case, the predefined css class will be applied as an alternative css class, which means that the “test” css class will be applied to the span that holds the validation message. Notice that the textbox will still have a red border and in the current release I’m not sure that you’ll be able to change the applied css easily (I think there’s a bug on the code, but I’ll confirm it before talking about it).

And that’s all for today. Keep tuned!

by luisabreu | with no comments
Filed under: ,
The MVC platform – the HtmlHelper class (part II)
Tue, Dec 16 2008 20:27

Today we’re going to keep talking about the methods associated with the HtmlHelper classes. In this post, we’ll concentrate on the extension methods defined on the InputExtensions.cs file that allow us to introduce several textboxes on a page (ie, HTML Input elements if you really want to  be picky). We’ll end up analyzing the three overloads of the TextBox method:

public string TextBox(string name)
public string TextBox(string name, object value)
public string TextBox(this string name, object value, object htmlAttributes)
public string TextBox(string name, object value, IDictionary<string, object> htmlAttributes)

The first overload lets you specify the name/id of the control. You can use that overload when you don’t want to explicitly specify the value of the textbox. The remaining overloads will let you set the value and attribute pairs you can define on the INPUT control (do notice that you can use the anonymous method approach or the dictionary approach).

The easiest way to use these helpers is illustrated on the next snippet (dropped on the aspx page):

<%= Html.TextBox( "name" ) %>

The previous line is responsible for injecting the following HTML on the page shown on the browser:

<input  id="name" name="name" type="text"  />

Lets suppose that you want to set the class to a predefined CSS style called myInput. Here’s one way of doing that:

<%=
          Html.TextBox( "name", //name/id of the textbo
                              null, //value shown
                              new { @class = "myInput"} ) //other attributes

%>

with the corresponding HTML:

<input class="myInput" id="name" name="name" type="text"  />

If you wanted, you could also use the overload which receives a dictionary (for this short illustration, using the anonymous object was more than enough, right?). As you can see, we didn’t pass anything to the value attribute. Nothing prevented us from passing a value to it, but it’s important to keep in mind that if you do that, you’ll loose the “automatic filling behavior”. “Auto what?” you’re asking? well, never mind the name. It’s just something I invented to explain what happens when you have an element whose key is the same as the id of a textbox and that doesn’t have an explicit value set.

To illustrate this approach, lets suppose that we have a simple form:

<form method="post" action="">
  <%= Html.TextBox( "name”) %>
  <input type="submit" id="myBt" value="Try to submit" />
</form>

It’s just a simple textbox and a submit button which will only refresh the current form  (ie, it will start a new request to the current url which will then instantiate the controller and will call the right method to handle the request and return a response back to the client). Yes,there are some helpers for generating forms too but we’ll leave that for future posts…

Now, if you have something like this in your controller’s method that handles the request and “calls” the view that had the previous snippet:

ViewData["name"] = Request.Form["name"];

You’ll always end up initializing the control with the last value that the user entered before submitting the form. Yes, you don’t need to do anything else (besides calling the TextBox method from the aspx page and passing it the same id as the key of the item that was passed into the view data dictionary). Interestingly, this behaviour will also work when you have strongly typed view. For instance, if you had a class that looked like this:

public class Data    {
        public String name { get; set; }
}

and the previous TextBox method call (<%= Html.TextBox( "name”) %>) then you could expect the textbox to have the value of the name property of that class with the following code:

return View( new Data{name = "Hooo"});

In other words, the value of the input HTML control will always be set to Hooo.

Do notice that this behaviour is slightly modified when you use validation. If you add a “model state” to your form and associate it with a control, then that value will always “overwrite” the other values you try to pass to the control. We’ll talk about simple validation on the next post (ie, we’ll interrupt the HtmlHelper analysis for introducing the validation classes introduced by ASP.NET MVC).

And that’s all for today. Keep tuned!

by luisabreu | with no comments
Filed under: ,
The MVC platform – the HtmlHelper class (part I)
Mon, Dec 15 2008 15:29

After a long break, it’s time to go back to the MVC framework study. And today I’ll start from where I’ve stopped last time: the helpers. Today, I’m going to start talking about the HtmlHelper class which has lots of methods that you can use on your views for generating HTML. If you’ve downloaded the source code and then look at the HtmlHelper.cs file, you’ll be able to see that most of the methods you’ll discover through intellisense are defined by extension methods. Today I won’t talk about these methods. Instead, I’m going to concentrate on the methods defined directly on the class (ie, on the methods that are defined on the body of the class).

By default, the HtmlHelper exposes only a handful of properties for giving you access to:

  • the data dictionary that is passed to the view (ViewData property);
  • to the current route collection (RouteCollection property);
  • to the current context (ViewContext property);
  • to the current IViewDataContainer element (see more about this  interface in this post).~

Besides these properties, the class exposes several utility methods. Many of these could be exposed as static methods but the team decided to expose them as instance methods in order to maintain consistency across the API. Here’s a summary of the instance methods you’ll find  in the class:

  • AttributeEncode: used for encoding the values that you intend to pass to an attribute. There are two overloads of this method (the one that receives an Object will call the Convert.ToString method before  passing the value to the  HttpUtility.HtmlAttributeEncode method);
  • Encode: similar to the previous method, but in this case you’ll end up using the HttpUtility.Encode method (remember that the  HttpUtility.HttpAttributeEncode should only be used for double quoted attribute values);
  • EvalString/EvalBoolean: as you can see from their names, these methods are responsible for receiving a string that identifies an item on the ViewDataDictionary and for returning it to you (already casted to string or boolean).

Besides these instance methods, you’ll also find several static methods. For instance, there’s a GetFormMethodString which transforms a value from the FormMethod enumerations into a string (I’m not sure on why this method is here or why it is needed at all since you’re only using it from the Form method helper – more about this on future posts).

There are also another couple of internal methods:

  • GetModelAttemptedValue: method used for getting a value from the ModelState dictionary available from the ViewData property (if I recall it correctly, ModelState was introduced in preview 5 for helping in validation of form items – more  about this on a future post);
  • FindPartialView: auxiliary method used for getting a reference to a view (used by the RenderPartialinternal method for getting a reference to an IView object that is responsible for rendering the HTML sent back to the client);
  • RenderPartialInternal: used internally by the views for rendering partial views (check this post for more info).

And that’s all you have defined on the body of the class. There’s a lot more (under the form of extension methods), but we’ll leave it for a future post. Keep tuned!

by luisabreu | with no comments
Filed under: ,
Asus Eee 1000h
Mon, Dec 15 2008 8:59

The unthinkable happened: my wife’s laptop decided to retire itself ahead of time. So, I was left with the task of finding her a replace laptop for the cheapest price I could get. What happened? I’ve ended up buying a new laptop for me, which means that she is now a proud user of a Toshiba Laptop. But this post is not about Toshiba…it’s about my new Asus EEE PC 1000h!

I’ve added more memory (upgraded it from the default 1 to 2 GB of RAM) and I’ve installed Vista 32 bits on it. It’s been running smoothly until now (at least, it’s way better than I had anticipated). Ok, it has limitations, but after installing the drivers, I managed to get 2.7 on the Vista Score (which is not bad for the price I’ve paid  for it – a total of 400 euros for the PC + memory + 8GB USB stick for installing Vista). I’ve only had time to install some applications so I still don’t have any feedback on how it will react to more heavy weight use. For now, the only thing I can say is that it’s working ok and I’m really enjoying the battery lifetime and its weight!

On the negative side, I’m still not used to the right shift and the touchpad sucks (you need to go to a gym just for pushing the touchpad buttons!). I guess I’ll have more to say about this computer on the next days…

by luisabreu | 1 comment(s)
Filed under:
Another cool interview with Medina Carreira
Thu, Dec 11 2008 20:20

In Portuguese only.

by luisabreu | with no comments
Filed under:
Book review: Practical .NET for the Financial Market
Thu, Dec 11 2008 9:46

A few months ago I was interested in learning more about the financial market and I’ve found this book at Amazon. The reviewers gave it a really good score, so I bought the book. What a waste of money! For starters, I was expecting (at a minimum) .NET 2.0 code. Unfortunately, everything is written in .NET 1.X (which is really bad, specially since the book was initially released in August 2006!). I don’t like their coding style either, but I won’t go through that route…

The main problem I see with this book is that it tries to show several areas on the .NET framework and end ups being short on all of them. Then there are lots and lots of pages full of boilerplate code which should be only available on a separate download. The way I see it, the book should have concentrated on key things that are specific to the financial market and then introduce several options you have to implement that in .NET (always redirecting to a code download to get more info).

Have I complained about the code? I guess I have, so I’ll just give it my final note: 3/10. It’s probably the lowest score I ever gave to a book. Does anyone want to buy my copy? :)

by luisabreu | with no comments
Filed under:
Is DDD for me?
Wed, Dec 10 2008 10:38

I think it’s really hard to present a definitive definition for Domain Driven Design. In my opinion, Domain Driven Design can be seen as a philosophy for developing applications based on specific domains and their logic where an ubiquitous language use is probably one of its most important features. If you’ve read Eric Evan’s book, then you’d probably agree that Eric hasn’t really introduced (or invented) anything new. On the other hand, you’ll surely noticed that his book (which is responsible for introducing DDD concepts to many!) presents several good design practices, techniques and principles which you can apply to solve problems associated with complex domains. So, in a way, you can see DDD as something that has grouped several known principles for domain modeling.

Now, do pay attention to the term complex! Yes, DDD really shines when you have complex (or complicated) domains. If you don’t have a complicated or complex domain, then probably you won’t be gaining much from DDD. Why? well, because the truth is that you’ll end up paying a penalty for using DDD (it’s really great for expressing relations between domain objects, but not so good for building objects that should be directly consumed by data bound applications). Don’t get me wrong: I do love DDD and I think it has helped me a lot in solving some complex problems. Following its recommendations has led me to deliver some pretty good models that express what’s going on in the “real” world.

However, it might be too much for several applications. Whenever you have a “data” bound application, you’ll probably end up hurting yourself if you try to apply all the principles advocated by Eric in his book. In theses cases, what you should do is follow what is now know as “DDD-lite”. But what is “DDD-lite”? Well, you can think of it as subset of good OO techniques which you can reuse in your projects without going all the “DDD way”. I’ve found this post which talks about several principles that lead to “DDD-lite” and I do agree with the author in most of the topics he presents.

For instance, in my projects (even in those where I don’t go full DDD), I’ll always use concepts like repositories, factories and services. These concepts aren’t enough for saying that you’re using DDD but they sure are reusable across different projects and will improve the final product. So, is DDD for you? The truth is that you’re the only one that can answer this question, but don’t forget that the subset of principles now know as “DDD-lite” can (and should!) be applied to all good OO projects.

by luisabreu | 2 comment(s)
Filed under:
S#arp core overview
Mon, Dec 8 2008 23:07

One of the open source projects I’ve been following in these last months is the S#arp project (pronounced Sharp Architecture) started and coordinated by Billy McCafferty. According to the homepage, this framework “is a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC framework with NHibernate”.  The framework adheres to the following principles (again, taken from their homepage):

  • Focused on Domain Driven Design
  • Loosely Coupled
  • Preconfigured Infrastructure
  • Open Ended Presentation

The current release (which is stable) introduces several reusable assemblies with many classes and interfaces that can be reused in your apps. You’ll also find some samples that show how to use the framework and a VS template that will automatically build you a solution with everything set up for using this framework in your apps! As you can see, there’s already lots of stuff to look at. Today, I’ll concentrate on the SharpArch.Core assembly (to me, this is probably the most important project).

In this project, you’ll find several interfaces and base classes for your domain objects. Lets start with the interfaces…

The IPersistentObjectWithTypeId is the base interface for database interaction. It looks like this:

public interface IPersistentObjectWithTypedId<IdT> {
        IdT ID { get; }
        bool IsTransient();
}

As you can see, it’s a generic interface which only introduces the ID (mapped to your ID on the database table) and a method which indicates if the current object is transient (a transient object is an object which hasn’t still been persisted on the database). As we’ll see, you don’t really have to implement this interface; instead, you can inherit from one of the base classes that already do all that work for you (this is the recommended approach, because those base classes already do some extra work which might be hard to get done right). More about this on the next paragraphs…

The IHasAssignedId generic interface is there for letting you set the ID of a domain object. It has only one method: SetAssignedIdTo. Here’s its signature:

public interface IHasAssignedId<IdT> {
        void SetAssignedIdTo(IdT assignedId);
}

Your objects will have to implement this interface if you want to explicitly set the ID of your object (at least, that’s the idea).

There’s also a IRepository interface which extends the IRepositoryWithTypeId interface by setting the ID type to an integer (System.Int32). Here are their signatures:

public interface IRepository<T> : IRepositoryWithTypedId<T, int> { } public interface IRepositoryWithTypedId<T, IdT>    {
     T Get(IdT id);      
     List<T> GetAll();
     List<T> GetByProperties(IDictionary<string, object>
                           propertyValuePairs); 
     T GetUniqueByProperties(IDictionary<string, object>
                                             propertyValuePairs); 
     T SaveOrUpdate(T entity); 
     void Delete(T entity);

     IDbContext DbContext { get; }
}

As you can see, IRepositoryWithTypeId defines the public methods that the repositories will implement. To be honest, I’m not really a fan of having the GetByProperties, GetUniqueByProperties and GetAll methods on this interface since I’d really prefer to have a separate context for querying (ie, I’d like to maintain my domain model as a transactional/write model).

There are also more specifics NHibernate interfaces, appropriately called INHibernateRepository and INHibernateRepositoryWithTypeId. This last interface extends the IRepositoryWithTypeId interface with several methods which let you interact explicitly with the NH API:

public interface INHibernateRepositoryWithTypedId<T, IdT> :
                IRepositoryWithTypedId<T, IdT>    {
    T Get(IdT id, Enums.LockMode lockMode); 
    T Load(IdT id); 
    T Load(IdT id, Enums.LockMode lockMode); 
    List<T> GetByExample(T exampleInstance, params string[] propertiesToExclude); 
    T GetUniqueByExample(T exampleInstance, params string[] propertiesToExclude);

      T Save(T entity); 
      T Update(T entity); 
      void Evict(T entity);
}

If it depended on me, and since the framework has a DDD focus, I wouldn’t add these interfaces to the core project.

There’s also one more thing that keeps bothering me when I look at these interfaces: the List<T> types that are returned from the GetXXX methods. I don’t really like it and I have changed my customized version of the assembly so that all those members return an IEnumerable<T> instead (just think about it: why do we need List<T> when we aren’t really allowed to add elements to those collections? And even if we needed to to that, wouldn’t it be better to return ICollection<T> or IList<T>?).

Before delving into the classes, I’d like to mention the IDomainObject interface:

public interface IDomainObject {
        bool IsValid();
        InvalidValue[] ValidationMessages { get; }
}

This interface lets you check for validity. Unfortunately, it’s tied up with the NHibernate Validator framework and, again, this is something that I don’t really like. I’d really prefer to have a validation framework based on the concept of domain rule, but this is what we have and we’ll have to live with it…

Now, the main thing you’ll get from the SharpArch.Core assembly are the classes that implement the previous interfaces and that you can reuse in your code. With these classes you’ll automatically get code for checking for equality and code that implements the hash code in a correct way (do notice that implementing the GetHashCode method is really hard work!). We’ll start with the DomainObject class. This class implements the IDomainObject interface and overrides the Equal and GetHashCode methods inherited from the System.Object class.

Before looking at the code, we need to understand the concept of Domain Signature. The domain signature is a value (or combination of values) that doesn’t change during the lifetime of a domain object and that uniquely identify an object (do notice that domain objects do have longer lifetimes than “programming” objects). Do notice that domain signatures aren’t good database keys !

SharpArch introduces the DomainSignatureAttribute for annotating properties of classes that are used in its domain signature. The DomainObject class will look at these attributes when it needs to check for equality or to calculate the hash code of an object. For instance, lets assume that you have a Person class where you’ve reached the conclusion that each instance is uniquely identified by its name (this is just an example!). Here’s how you’d write the code when you’re reusing this framework:

class Person:DomainObject{
   public Person(String name){
      Name = name;
   }
   [DomainSignature]
   public String Name{ get; private set; }
}

As you can see, you just need to annotate the property (or properties) that define the domain signature with the attribute and the base class will automatically add code for checking for equality and for calculating the hash code. Lets start by looking at the code used for checking for equality (defined by the DomainObject class):

public override bool Equals(object obj) {
            IDomainObject compareTo = obj as IDomainObject;

            if (ReferenceEquals(this, compareTo))
                return true;

            return compareTo != null && GetType().Equals(compareTo.GetType()) &&
                HasSameDomainObjectSignatureAs(compareTo);
}

Several interesting things are happening here. First, the method uses the static Object.ReferenceEquals to see if we’re comparing two objects that point to the same object reference. When that doesn’t happen, the method sees if the object that has been passed implements the IDomainObject interface (personally, I’d prefer that it would check for DomainObject instead of the interface, but…) and if it does (and if the object has the same type as the current instance over which the Equals method is called), it’ll will defer the equality calculation to the helper HasSomeDomainObjectSignatureAs method.

protected virtual bool HasSameDomainObjectSignatureAs(IDomainObject compareTo) {
    foreach (PropertyInfo property in DomainSignatureProperties) {
      object valueOfThisObject = property.GetValue(this, null);
      object valueToCompareTo = property.GetValue(compareTo, null);

      if (valueOfThisObject == null && valueToCompareTo == null)
                    continue;

      if ((valueOfThisObject == null ^ valueToCompareTo == null) ||
         (!valueOfThisObject.Equals(valueToCompareTo))) {
                    return false;
       }
   }

   return DomainSignatureProperties.Any() || base.Equals(compareTo);
}

As you can see, equality is calculated by checking the properties annotated with the DomainSignatureAttribute (the DomainSignatureProperties uses LINQ to get the collection of PropertyInfo objects for the properties annotated with the DomainSignatureAttribute). Notice that we can get to the last line of the method in two cases: when there aren’t any properties signed with the DomainSignatureAttribute or when there are and their values match. In the first scenario, we simply redirect to the base class (System.Object) and will let it do its work. In the latter, we’ll just return true (notice the clever use of the Enumerable.Any extension method on the last line of the Equals method).

The GetHashCode method follows the same principles introduced by the Equals method: use the domain signature properties and redirect to the base whenever there aren’t any properties annotated with DomainSignatureAttribute. The method will also use the type and a random number for making sure that you get a good hash code.

public override int GetHashCode() {
    unchecked {
        int hashCode = GetType().GetHashCode();

        foreach (PropertyInfo property in DomainSignatureProperties) {
          object value = property.GetValue(this, null); 
          if (value != null)
             hashCode = (hashCode * RANDOM_PRIME_NUMBER) ^
                                 value.GetHashCode();
         }

         if (DomainSignatureProperties.Any())
                    return hashCode;

         return base.GetHashCode();
   }
}

One thing you might be tempted to do is using the hash for checking for equality. Don’t do that! The only guarantee that hash codes give you is that the equal instances will return the same hash code. It doesn’t say anything about different instances. In practice, you might have two different instances produce the same hash code and that’s ok (really!)

Since the DomainObject class implements the IDomainObject interface, it will also add code for checking for the validity of an object. Currently, these checks are performed by the NHibernator Validator. So, if you’re a fan, reusing this class as a base will let you use their attributes for validation…

The last important class introduced by the core assembly is the PersistentObjectWithTypeId class (there’s also a PersistentObject  class that inherits from the previous class and sets the TypeId to System.Int32). The class expands the DomainObject class and implements the IPersistendObjectWithTypeId interface that was presented earlier.

The most important thing the class does is override the Equals method. Here’s the code:

public override bool Equals(object obj) {
   PersistentObjectWithTypedId<IdT> compareTo = obj as PersistentObjectWithTypedId<IdT>;

   if (ReferenceEquals(this, compareTo))
                return true;

   if (compareTo == null || !GetType().Equals(compareTo.GetType()))
                return false;

   if (HasSameNonDefaultIdAs(compareTo))
                return true;

   return IsTransient() && compareTo.IsTransient() &&
                HasSameDomainObjectSignatureAs(compareTo);
}

As you can see, if we’re talking about non transient objects of the same type, then equality will be performed by checking the value of the ID property (remember that this ID is the one that is used as a primary key on the database table). Domain signature comparison will only be used if both of the objects are transient (if only one of them is transient, then the instances are different).

As you can see, the framework introduces two important base classes: DomainObject and PersistentObject. If you’re doing DDD, then I recommend that you use the DomainObject class, especially if you’re following the domain signature concept. If you’re also using NHibernate, then do reuse the PersistentObject(XXX) class.

As you can see, the S#arp Architecture project is still young, but it’s also interesting and it might be a good framework for supporting your code. I’m already using several of its ideas (not all, because I still don’t agree with some of the options that have been taken) and I’ve been pleased with the overall results.

In the next posts I’ll dig into the repository implementation code.

by luisabreu | 4 comment(s)
Filed under: ,
Re-throwing exceptions
Tue, Dec 2 2008 10:33

While I was reading the Essential Windows Communication Foundation book (from Addision Wesley), I found the following code (on a transaction required for a WCF service context):

[OperationBehavior(TransactionScopeRequired = true,
   TransactionAutoComplete = true)]
public void Transfer( String from, String to, double amount){
  try {
    Withdraw(from, amount);
    Deposit( to, amount);
  }
  catch(Exception ex){
    throw ex;
  }
}

Lets not even talk about why using the Exception type in a try/catch is bad (though I accept its usage in a book, but only after seeing a justification of why you should not use it in production code)…instead, lets concentrate on what is happening inside the catch block…see anything wrong there? I hope so! You should never re-throw an exception like that. In my opinion, you’ve got 2 options here:

1. You’re “important” in the stack chain and then you’ll want to wrap that exception with your own specific  exception type (for isntance, NHibernate does something like this and wraps ADO.NET exceptions with its own exception type). Here’s what I mean:

catch(Exception ex ) { //btw, don’t catch the Exception type
  //do something here…probably log it
   throw new MyException(ex);
}

2. You’re not significant, so you can just rethrow that exception after logging:

catch(Exception ex ) { //btw, don’t catch the Exception type
  //do something here…probably log it
   throw; //see? no ex here!
}

Ok, so why is this important? Because when you re-throw the exception by using technique shown in point 2, you will be preserving the stack trace. When you do it like in the original code, the stack trace that the client will see ends up in your catch block. Probably not what you’ll want in most scenarios!

Do notice that technique 1 will also preserve the stack chain since you’re passing the exception as the inner exception of the new exception you’re throwing. Both of these options are really better than the one shown on the initial code.

I’m only writing this here because I was under the impression that this info should be well know by now, but it seems like I’m wrong…Do keep in mind that it’s not my intent to trash on this book (I’m still on page 211, but I’m liking it so far), but I was a little but surprised by seeing this code there (as always, I’ll put a review after ending it).

by luisabreu | 2 comment(s)
Filed under: ,
Velocity looks good
Mon, Dec 1 2008 19:19

So, I’ll probably get it and write some rambles about it in the next days…

by luisabreu | with no comments
Filed under: