March 2009 - Posts

SOLID motivational pictures
Mon, Mar 30 2009 21:55

Just take a look.

by luisabreu | with no comments
Filed under:
The MVC framework: the ContentTypeAttribute attribute
Fri, Mar 27 2009 0:07

Another short post on the features available on the MVC futures assembly…today, we’re going to take a look at the ContentTypeAttribute. This attribute is an action filter attribute and you can use it to setup the content type of the current response (ie, you can apply this attribute to an action method to influence the value of the ContentType property of the HttpResponseBase object). The constructor of the this type receives a string which identifies the content type of the response.

Internally, this action filter ends up overriding the OnResultExecuting and OnResultExecuted methods in order to set the HttpResponseBase’s ContentType property to the value you’ve passed to its constructor.

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

by luisabreu | with no comments
Filed under: ,
The MVC framework: pay one take several
Wed, Mar 25 2009 23:12

Ok, not really! It’s still free…today I didn’t really had the time to dig into the stuff I wanted to investigate. So, I’ll just present several interesting topics about the MVC futures assembly:

  • Binders: the MVC future has some offers in this area. Let’s start with the ByteArrayModelBinder. This binder will recover a byte array from an existing field (as you might expect, it will try to interpret the value as a base 64 string). Before using this binder, don’t forget to register it with the ModelBinders.Binders collection. There’s also a SkipBindingAttribute which you can use to skip binding on an action controller’s parameter;
  • Extensions: besides the extensions we’ve seen in the previous posts, there are a couple of other extensions which might be useful to you. Let’s start with the MailToExtensions. As you might expect from the name, these HtmlHelper method extensions let you add mailto links to your web views. There are several overloads which let you specify mail, subject, cc, bcc and body for the message. The ExpressionInputExtensions class adds several helpers which let you add textboxes, hidden fields, dropdowns, textareas and validation messages to a view. The main difference when compared to the ones present on the main MVC assembly is that these methods use Expressions for specifying the association between the generated field and a model property. If you’re looking for radio button helpers, then you’ll be pleased to know that the futures assembly has several helpers that might help you with that. RadioListExtensions is the class you want for this job. Items that are to be rendered should be passed through a collection of SelectListItem;
  • Caching: the futures assembly introduces a class (CacheExtensions) which lets you specify a method that should be called for rendering portions of the page that shouldn’t be cached. Internally, you’ll end up using the WriteSubstitution method of the HttpResponseBase class (which, in practice, means that you’ll end up calling that method over the HttpResponse class).

Since we still haven’t talked about using caching on MVC apps, I though this would be a good time for presenting a small example which illustrates the use to the CacheExtensions’ static methods. Lets suppose we’ve got a view which is cached. However, there’s a section which shouldn’t be cached, ie, there’s a specific portion of the view that should be regenerated for all the requests. Here’s how you might do that with this extension method (I’m just putting the view):

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ OutputCache VaryByParam="None" Duration="60" %>
<%@ Import Namespace="MVCRTM.Controllers"%>
<%@ Import Namespace="Microsoft.Web.Mvc"%>

<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">  
<form>
  <%= Html.SubmitButton( "Message", "hi" ) %>
</form>
<%= DateTime.Now %>

<% Html.Substitute(  ctx => DateTime.Now.ToString() );%>
</asp:Content>

Ok, this is just a really simple (and dumb!) view with a form whose sole objective is to force a refresh of the view. Without caching, you should see both times being refreshed. However, after adding the cache directive, you should notice that only the second date will be updated. Notice that the Substitute method expects a MvcSubsitutionCallback delegate, which looks like this:

public delegate string MvcSubstitutionCallback(HttpContextBase httpContext);

As you can see, you cam access the current context from within the method you’re passing to handle the substitution.

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

by luisabreu | with no comments
Filed under: ,
The MCV framework: view extensions
Tue, Mar 24 2009 23:17

Ok, here we are again for another episode on the inner workings of the MVC futures assembly. Today, we’re going to take a look at the HtmlHelper extension methods defined on the ViewExtension class. The current release of this class introduces two (static extension) methods which you can use to execute an action “in-place” during the current request:

  • RenderRoute: this method lets you pass a RouteValueDictionary which is added to a RouteData object. Then, the method uses an auxiliary handler to execute the new request “in-line”;
  • RenderAction/RenderAction<T>: there are several overloads of these methods. As you might expect, you’ll use them whenever you need to render a specific action of a controller. The main difference (when compared with the previous method) is that in this case you’ll end up getting two more entries on the RouteData’s Value dictionary: action and controller.

These methods end up delegating the execution of the request to a private handler: RenderActionMvcHandler. This handler expands the MvcHandler and the only thing it does is override AddVersionHeader so that it doesn’t set the custom HTTP version header. Ok, so it’s time to see this in action. Here’s a quick example that show how you can use it:

<% Html.RenderAction<HomeController>(c => c.Test()); %>

In this case, we’re rendering the Test action method of the HomeController “in-place” from within the view (yes, that call is made from within a view – not really good, right? more about it below). Do notice that the method tries to “emulate” a new request and things might not work for anything that falls out of the “simple staff” scenario. For instance, here’s a couple of things you should keep in mind if you intend to use this method:

  • it goes against the “spirit” of the pattern. Using this method means that you’re calling an action from a view (and in my opinion, that is not really a good thing);
  • the faked request might not have everything you might need. Since it doesn’t know (beforehand) what you need and what you want to replace you’ll get a predefined default behavior.

Ok, so now that you know that it has some short comes, you’re free to use it at your own risk :)

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

by luisabreu | 1 comment(s)
Filed under: ,
The MVC framework: maintaining TempData on cookies
Mon, Mar 23 2009 23:14

A few months back, we’ve seen how TempData is implemented and how it should be used. Today we’re going to keep looking at the future assembly and we’ll take a look at the CookieTempDataProvider class. The class implements the ITempDataProvider interface and you can use it it you intend to persist the temp data dictionary in cookies instead of relying in the traditional session temp data provider.

Internally, the class will serialize the data using the BinaryFormatter and encode it into a base 64 string which is then set as the value of a cookie which is added to the current response. Then, when the browser asks for a specific controller action and starts a subsequent request to the server, this temp data provider will search the request and see if there’s cookie with the previous persisted temp data dictionary (btw, it will search for a cookie named __ControllerTempData). If it finds one, it will rehydrate the temp data dictionary from that cookie’s value and then it will expire the cookie immediately. It will also search for an existing cookie on the response and will also invalidate it by clearing its content and expiring it (like it did to the one present on the request’s cookie collection).

The only thing you need to do is set the TempDataProvider that your controller class inherits from the Controller class. You have several options here. The important thing is that you shouldn’t set that value from the constructor of your controller because at that time your controller context is still null. A valid option could be overriding the Initialize method and set the TempDataProvider property:

protected override void Initialize(RequestContext requestContext){
  base.Initialize(requestContext);
  TempDataProvider = new CookieTempDataProvider( requestContext.HttpContext );
}

And that’s it for today! Stay tuned for more on the MVC framework.

by luisabreu | 1 comment(s)
Filed under: ,
The MVC framework: more on the future’s helpers
Sun, Mar 22 2009 22:54

Ok, so in the previous posts I kept talking about some of the helpers available on the future assembly. In this short post we’re going to complement that information with some more methods that let you expressions for specifying form actions (yes, this can be seen as form extensions, part III).

The future assembly introduces 2 new extension methods with these signatures:

public static MvcForm BeginForm<TController>(this HtmlHelper helper, Expression<Action<TController>> action) where TController : Controller

public static MvcForm BeginForm<TController>(this HtmlHelper helper, Expression<Action<TController>> action, FormMethod method) where TController : Controller

As you can see, they’re really similar to the ones we have on the MVC assembly; the main difference, is that we’re using Lambdas for setting up the action that ends up deciding the url for the form’s submission. The use of this method follows the same approach we’ve seen for the button helper methods. And that’s it. There’s still more to come. Stay tuned!

by luisabreu | with no comments
Filed under: ,
Impressed with SuperPreview
Sun, Mar 22 2009 18:20

I've started watching MIX sessions and, until now, I can tell you that I’m really impressed with SuperPreview. I’ll be getting the expression tools just to see what it can be done with it (do keep in mind that there’s also a free version for IE).

by luisabreu | with no comments
Filed under: ,
The MVC framework: the Button helper
Sun, Mar 22 2009 15:05

Today we’re going to keep looking at other helps available on the future assembly. The topic for today is: ButtonBuilder and using the available extension methods for adding HTML button type elements to the page. We’re going to start looking at the functionalities available on the ButtonBuilder class (keep in mind that you won’t probably be calling these methods from the pages; generally, you’ll end up using the extension methods we’ll be presenting at the end of the post).

Currently, the ButtonBuilder (static) class exposes 3 (static) methods:

  • SubmitButton: used for inserting a <input type=”submit”> element to a form;
  • SubmitImage: used for generating a <input type=”image”> element on a page;
  • Button: used for adding <button> elements to a page.

Here’s a quick example of how you might use the Button method to add a <button> element and to configure it so that it shows an alert message when someone clicks on that button:

<%= Html.Button( "message", 
                             "H", 
                             HtmlButtonType.Button, 
                             "printHello()") %>

As you can see, we’re using one of the HtmlHelper extension methods defined on the ButtonsAndLinkExtensions static class. Besides this method (and its overloads), the class exposes also several other methods that redirect to the methods presented on the previous list.

One of the things you should keep in mind is that, in this case, the name parameter is used only to set up the HTML name (or id) attributes on the generated HTML control. So, if you need to pass a value from the view data dictionary, you’ll have to do it explicitly.

And that’s it. There’s still more to say about the MVC framework, but I’ll leave it to another day…

by luisabreu | 6 comment(s)
Filed under: ,
The MVC framework: more on links
Sat, Mar 21 2009 23:55

Ok, now that codeplex is up again, I’ve already downloaded the latest bits for the ASP.NET MVC framework. In the past, we’ve already seen that there are several helpers for generating links for specific actions. As we’re going to see today, the future assemblies adds more ActionLink extension method helpers that let you specify the url of an anchor in a strongly typed manner (by using Expression<T> to define the associated action instead of relying on strings).

As you might expect, the first thing we need to do is add a reference to the future assembly in our MVC project. Then, we’ll start by adding a reference to the Microsoft.Web.Mvc namespace on the view by using the Import directive:

<%@ Import Namespace="Microsoft.Web.Mvc" %>

Now, we can start using the new ActionLink extension in the page. Here’s a quick example (supposing we’ve got a ShowMessage action method on the HomeController class that receives a string parameter called msg):

<%= Html.ActionLink<HomeController>(
                             c =>c.ShowMessage(“hi”), “Say hi!” );

As you can see, we’re passing  an Action<T> expression (where T is a controller) which ends up being parsed and transformed into a RouteValueDictionary. In this case, we’re passing a constant value to the ShowMessage. When the expression isn’t a constant, it ends up being converted into a compiled Lambda Func<Object> which is invoked. btw, here’s the HTML generated by the previous snippet:

<a href=”/Home/ShowMessage?msg=hi”>Say hi!</a>

And that’s it: by using this helper, you can build your anchors’ url in a strongly typed way. btw, and since we’re talking about additional link features introduced by the futures assembly, this post wouldn’t be complete without mentioning the BuildUrlFromExtension<T> method (an HtmlHelper extension method). The main difference (when compared with the previous method) is that this method will only return the url (instead of the complete HTML for the anchor).

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

by luisabreu | 3 comment(s)
Filed under: ,
Mix sessions online
Fri, Mar 20 2009 23:50

Just a quick note for those that stayed home: there are several MIX 09 sessions are already available. Go get them!

by luisabreu | with no comments
Filed under:
MIX almost over
Fri, Mar 20 2009 21:46

And I still haven’t finished watching the 1st keynote…oh well, that’s what happens when you have lots of things to do…as you all know, MVC is out (which is great!) and I do intend to continue my posts on  it as soon as I can get my hands on a futures assembly which works with the RTM version…btw, can anyone access the codeplex site?

by luisabreu | with no comments
Filed under:
The MVC framework: working with uploaded files
Tue, Mar 17 2009 11:43

Today we’re going to keep looking at the futures assembly. In a previous post, we’ve seen how we can easily return a file from an action method. Today, we’re going to take a look at how we can use the FileCollectionModelBinder to get access to a group of files that have been uploaded to the server. The first thing you need to do when you want to use this binder is to register it. The FileCollectionModelBinder introduces a static method that registers the binder for all types of collections off HttpPostFileBase items. We can do this from within application start event:

protected void Application_Start() {
   RegisterRoutes(RouteTable.Routes);
   FileCollectionModelBinder.RegisterBinder( ModelBinders.Binders );
}

After doing this, all parameters of type HttpPostedFileBase[], IEnumerable<HttpPostedFileBase>, ICollection<HttpPostedFileBase>, IList<HttpPostedFileBase>, Collection<HttpPostedFileBase> and List<HttpPostedFileBase> will be automatically filled by this custom binder. In order to illustrate its use, we’ll start by adding a form to a view that lets you update files. Here’s the markup we’re using:

<% using( var form = Html.BeginForm(
                                         "ProcessFiles",
                                         "Home",
                                         FormMethod.Post,
                                         new { enctype = "multipart/form-data"}))
{%>
    <input type="file" name="files" />
    <input type="file" name="files" />
    <input type="file" name="files" />
    <input type="file" name="files" />
    <input type="submit" value="Send files" />
<% }%>

As you can see, we need to add the enctype attribute “by hand” to the form tag. If you don’t do that, you’ll end up without no files on the server side. Another interesting thing is that we’re defining several <input type=”file”> elements and we’re giving them the same name. We’re doing this because we want to get them all on the server side. Here’s the code for the ProcessFiles method:

public ActionResult ProcessFiles(IEnumerable<HttpPostedFileBase> files) {
  //do something with the files here
  return GetView();
}

If everything works out, files will give a collection with all the files submitted by the user on the browser. It’s important to keep in mind the rules associated with the binding associations: the parameter name must match the name of the files you want to retrieve form the form (in other words, make sure that the parameter name matches the name attribute you’ve passed to the input elements of type file you want to recover). I haven’t tested it, but this should also work with custom objects with properties that match one of the types handled by this binder.

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

by luisabreu | with no comments
Filed under: ,
Technical debt
Tue, Mar 17 2009 0:36

Technical debt is a cool metaphor introduced by Ward Cunningham. Martin Fowler has a nice post on it here too. In my current job, I see this happening almost every day. The worst thing is that it really seems like there’s nothing that can  be done to correct things. 

It always starts with a tight timeline…here’s a typical scenario: “hey, lets forget the tests for this part…we must have everything ready by the end of the week and tests are just reducing our productivity”…I think we all know this is wrong…at least, that is my opinion…yes, tests will decrease your immediate productivity (remember, you’re writing more code and I’m positive that at least half of it will be in testing – at least, if you want to have good code coverage), but they will improve your long time productivity (especially if you’re looking at it from a team perspective and you’re thinking about the future. btw, Scott Bellware has written about it in the past. If you have the time, go read some of this posts….).

Like Ward and Fowler say, sometimes it’s ok to incur into some “technical debt” to get things out of the door, but I do also think that it’s important not to let it get out of control. This is important, so I’m repeating it here: don’t let it go out of control! Never! Unfortunately, this is almost impossible (at least, this is what I’ve been seeing in all the projects I’ve been working in the last years). After you lose control, it will be extremely difficult to recover. Let me give you an example…in this last week I’ve been rewriting  and refactoring an app which doesn’t have any kind of tests…as you might expect, this is really close to a nightmare! And not good to morale either! Progress is really slow and I seem to be cursing the guy that wrote the app from 30 to 30 mins (when everything goes well…the interval decreases when you find WTF snippets!)

Now, instead of adding more value to that app, I’m just cleaning it up…not really productive, but, in my opinion, this is really necessary so that we can get things under control again. Of course, this would be unnecessary if the original developer had thought about the future and hadn’t incurred in such a high technical debt!

by luisabreu | with no comments
Filed under:
Monodevelop 2.0 looks good
Mon, Mar 16 2009 23:40

Ok, I know…it’s still in beta 2. Anyway, I was reading Miguel’s announcement (yes, I know, I’m late again!) and I’m quite impressed with the new features. And this comes really handy because I’ve just installed Xubuntu on a virtual machine and it seems like now I do have a nice editor for .NET in Linux…

by luisabreu | with no comments
Filed under:
The MVC framework: the Repeater control
Mon, Mar 16 2009 11:25

Today we’re going to look at the last available control on the futures assembly: we’re talking about the Repeater control. If you’ve dealt with web forms server controls in the past, then looking at the code of the Repeater class shouldn’t make you have any “haha moment”. As you might expect, the class expands the MvcControl class and adds a couple of properties to it:

  • ItemTemplate: property of type ITemplate which lets you specify a template that should be applied to all the items;
  • EmptyDataTemplate: lets you sepcify an ITemplate instance that will be rendered when there aren’t any items to render;
  • Name: used for trying to get the collection of items from the view data dictionary that could have been passed to the view.

This class doesn’t really do much in the Render method. It will only try to get an IEnumerable instance from the view data dictionary (by using the Name property as the key) and if it finds data, it will  instantiate its ItemTemplate for each item of the collection. As you might have guessed, when there’s no data, the class will only render the stuff you’ve specified on the EmptyDataTemplate property.

Since we’re looking at the internals, our study wouldn’t be complete without mentioning the RepeaterItem class. This is a simple wrapper class which expands the Control base class and implements the IDataItemContainer and IViewDataContainer interfaces. When you pass a valid collection on the view data dictionary, the Repeater control will instantiate an instance of this type for each existing item on that collection. And that’s all you need to know about the internals. Lets see how we can use this in a web form view…

We’ll start by creating a new collection which is going to be passed to the view. Notice that we can even get away with anonymous objects (which is great for demo code like this):

var collection = new[] {
                                         new {
                                                     Id = 1,
                                                     UserName = "Luis"
                                             },
                                         new {
                                                     Id = 2,
                                                     UserName = "Paulo"
                                             },
                                         new {
                                                     Id = 3,
                                                     UserName = "Jose"
                                             }
                                 };
ViewData["repeaterItems"] = collection;

Now, we only need to setup the repeater. In this code, we’ll only use some simple MVC labels for showing the output:

<mvc:Repeater runat="server" Name="repeaterItems">
     <ItemTemplate>
       <div>
         Id: <mvc:Label runat="server" Name="Id" /><br />
         Name: <mvc:Label runat="server" Name="UserName" /> <br />
      </div>
     </ItemTemplate>
</mvc:Repeater>

And that’s it. If you load the page you should see a list of users passed from the view. Do keep in mind that the “old” binding expressions still work. For instance, you could have used these expressions for getting the same info from the collection:

<%# Eval("Id") %> - <%# Eval("UserName") %>

You can even do more complicated things…For instance, you can render collections of collections, like Eilon shows in this post.

One of the things you will not get in the  current release is the ability to specify an alternating template in markup. For instance, lets say that you wished to specify a different css class for the container div used inside the ItemTemplate of the repeater. You’ll have to write some simple code to make that happen. Here’s an example of how you could do that:

<mvc:Repeater runat="server" Name="repeaterItems" ID="myRepeater">
      <ItemTemplate>
       <div class="<%# GetCss(Container) %>">

As you can see, we can still use our old good *Container* to get a reference to the RepeaterItem instance that is being used for the rendering. Then, we could probably write code like this to get the correct css:

protected String GetCss(object obj) {
      var item = obj as Microsoft.Web.Mvc.Controls.RepeaterItem;
      return ( item.DataItemIndex%2  )== 0 ? "even" : "odd";
}

I say *probably* because the truth is that you can’t. The reason is simple: there’s a bug on the rendering logic and the RepeaterItem is always initialized with index 0. It’s simply to solve this: just increment the index counter and recompile the code.

And I believe there’s not much to talk about on the MVC controls available on the future assembly. We should be getting more stuff when the final version of MVC is out, but the truth is that for now there really isn’t much more than can be said about these controls. On the other hand, there are still lots of stuff to talk about on the MVC futures assembly! So, keep tuned if you want to read more about MVC.

by luisabreu | 3 comment(s)
Filed under: ,
References are not pointers in C#
Sat, Mar 14 2009 12:20

As you know, C# supports the concepts of references and value types. Most of the time, reference types tend to be presented as some sort of synonym for a memory address. I’ve seen it everywhere and I’ve used that analogy too when trying to help others to understand the difference between value types and reference types. Now, this kind of analogy tends to break when you start thinking about the memory model and on how GC works.

Say, if reference type is an address, then why do I need to pin it before saving a reference to that address? If you think about references without the address analogy, things start to make more sense…This is just an example of the kind of questions you might end up being asked when you use this sort of analogy to introduce reference types. Fortunately, we’ve got people like Eric Lippert who really  know their stuff and do have the time (and will!) to explain why that is not a good analogy.

by luisabreu | with no comments
Filed under:
Why can’t we use var on field declaration?
Fri, Mar 13 2009 23:19

This was a question I’d always wanted to see answered… finally, I’ve got my answer..

by luisabreu | with no comments
Filed under:
Consistency vs availability
Fri, Mar 13 2009 22:49

Excellent article by Werner Vogels on how to achieve eventual consistency.

by luisabreu | with no comments
Filed under:
Debugging multithreaded applications
Thu, Mar 12 2009 15:00

Multithreading is one of the topics I’ll have to start looking at with more attention and I’m thinking of adding posts about it in the future. Today I’ve read an interesting article on how to debug multithreaded applications on the site Packt. The author has also written a book on that topic (which I’ve already received). Yes, I’ll be publishing a review about it when I finish reading it.

by luisabreu | 4 comment(s)
Filed under:
The MVC framework: the DropDownList control
Thu, Mar 12 2009 12:28

Today we’re going to keep looking at the futures assembly and we’ll take a peek at the DropDownList control. Currently, the class exposes the following properties:

  • Name: used to identify the control and recover the collection of SelectListitems that might have been added to the view data dictionary;
  • OptionLabel: used for passing the text that is set up as the top option show to the user by default.

As you might expect, the rendering is really similar to what happens in the TextBox: the difference is that in this case you’ll end up having several OPTION elements rendered. If you look at the code, you’ll notice that this is still work in progress (and that’s why it’s still on the futures assembly!): you can only generate DropDownLists but it seems like in the future we’ll have an intermediary class for holding common code and then two specialized classes for rendering DropDownList and ListBoxes. That’s the only reason I can  think of for having code that can generates dropdowns or listboxes and that is always hard coded for generating dropdowns…

Ok, so let’s see how we can use this control to add a drop down to a view. We’ll start with the markup:

<mvc:DropDownList runat="server"
      name="myDrop"
      optionlabel="choose an option" />

Now, we need to ensure that there’s an entry in the view data dictionary with the name myDrop which has a collection of items. Since this is demo code, I’ll just add these lines to the action method that returns the view that contains the markup presented in the previous snippet:

var items = new[]{
                               new SelectListItem
                                   {
                                           Text = "Option 1",
                                           Value = "Opt1"
                                   },
                               new SelectListItem
                                   {
                                           Text = "Option 2",
                                           Value = "Opt2"
                                   }
                       } ;
ViewData["myDrop"] = items;

And that’s all you need to fill the dropdown. btw, don’t forget that you can use the SelectList class for passing a custom collection of items like it was shown here. And that’s all for  today. Keep tuned for more about MVC.

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