January 2009 - Posts

The MVC platform: generating textareas
Sat, Jan 31 2009 14:19

This is going to be the last post on the Html extension methods and we’re going to end with TEXTAREAS. If you’ve been following these posts, then you know what to expect: several overloads of a method which let you define the attributes you’d generally set up on a TEXTAREA control.

The simplest of the overloads of the TextArea method will let you define the name of the generated control:

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

By default, you’ll end up with a 20 columns x 2 rows HTML TEXTAREA. If that doesn’t work for you, you can always use the overload which sets those values:

public static string TextArea(this HtmlHelper htmlHelper,
                                                 string name,
                                                 string value,
                                                 int rows,
                                                 int columns,

                                                 object htmlAttributes)

You’ll also be happy to know that all the previous “tricks” work with these helpers too. So, if you’ve got an entry on the ViewData dictionary with the same name as the one  you pass to the name parameter of the methods, then the generated TEXTAREA will automatically render that value as its content.

You can also use validators with these helpers (if you want to know more about validation, please check this post). As you’d expect, you also have an overload which lets you specify the HTML attributes you which to render.

And that’s it. As you can see, the helpers to cut off the work need for generating HTML from the server side and do have similar APIs. So, if you know how to use one, you really know how to use the others. Keep tuned for more MVC stuff!

by luisabreu | with no comments
Filed under: ,
The MVC platform: more form extension methods
Sat, Jan 31 2009 13:43

I’ve already talked about several method extensions helpers for injecting forms in a page. However, the latest release has introduce a couple more methods for doing that and I’ve thought I’d write a quick post on those new methods.

Basically, you’ll have several overloads named BeginRouteForm which let you set the form’s action method from a specific route. As you’d expect, you use it the same way you use the “Old” BeginForm method (check this post to get more info on what I mean). Here’s a quick example of what I mean:

<% using( var frm = Html.BeginRouteForm("DefaultRoute")) {%>
…//control definition
<%}%>

In the previous example, I’m using the simplest of the overloads: it only takes the name of the route that you want to use to build the form’s action url. As I’ve said, there are others (too much to put here so I’ll just redirect you to the FormExtension.cs file.

by luisabreu | with no comments
Filed under: ,
The MVC framework: adding dropdown controls to your view
Fri, Jan 30 2009 14:49

Today we’ll keep looking at the helpers and see how we can add dropdowns and listboxes to our views. As you might expect, there are some helper methods that render the corresponding SELECT HTML element. They’re adequately named DropDownList and ListBox and,as you might expect, you’ll find several overloads of each. The main difference between then is that with the ListBox you’ll be able to select several items simultaneously. Here’s some demo code that shows how to create and fill the lists which will be shown on the page:

<%= Html.DropDownList(
                    "optionsDrop",
                     new []
                         {
                                 new SelectListItem
                                     {
                                             Text = "Option 1",
                                             Value = "opt1"
                                     },
                                  new SelectListItem
                                     {
                                             Text = "Option 2",
                                             Value = "opt2"
                                     },
                                  new SelectListItem
                                     {
                                             Text = "Option 3",
                                             Value = "opt3"
                                     }
                },
               "Choose an option"  
             ) %>
<br />
<%= Html.ListBox(
                    "optionsList",
                     new []
                         {
                                 new SelectListItem
                                     {
                                             Text = "Option 1",
                                             Value = "opt1"
                                     },
                                  new SelectListItem
                                     {
                                             Text = "Option 2",
                                             Value = "opt2"
                                     },
                                  new SelectListItem
                                     {
                                             Text = "Option 3",
                                             Value = "opt3"
                                     }
                },
               "Choose an option"  
             ) %>

Since this is demo code and my main objective is to show you how you can render a dropdown, I’ve just created some dumb SelectListItems to fill the list of items displayed by the HTML SELECT element generated by the helpers. In the “real world” you’d probably have a collection of items that you’d want to show in a dropdow or in a listbox. In those cases, you’d be encouraged to perform the transformation from the custom items in that collection into the SelectListItems in the  controller.

Going back to the example, I’d like to mention that the SelectListItem class is a simple class which exposed three properties:

  • Text: used for setting the text of the OPTION element contained in the dropdown or listbox;
  • Value: used for  defining the value of the OPTION element used for representing a rendered entry;
  • Selected: boolean property that indicates if an item is selected.

Btw, in the previous snippet, we’re using one of the overloads which receives an optional string label. This label is added to the items on the list without a specified value (ie, the string you passed for the label parameter is converted into a SelectListItem with an empty string Value and with the Selected property set to false – oh, and yes, with its Text property set to the text you’ve passed through the label parameter). As you’ve seen in some of the previous posts, you also have overloads that let you specify the html attributes you want to set up on the generated HTML element.

More interestingly, you can make the dropdown or listbox render automatically the items passed from the controller through the ViewData property (which is really what you want when you have a custom collection which the controller converts into SelectListItems as I’ve suggested above). You have 2 options:

  • if you use the dictionary approach without a “strongly typed” view, you’ll need to have an entry on the ViewData dictionary with the same name as the one that is passed to the name parameter of the DropDownList or ListBox  methods you’re calling;
  • if you’re using a “strongly typed” view, then you need to guarantee that the object that is passed to the view has one property with the same name as the name you’ve passed to the DropDownList (or ListBox) method you’re invoking.

So, if you’re using approach 1, you need to have something like this in your action method:

ViewData["optionsDrop"] = new[] {
                new SelectListItem
                    {
                            Text = "Option 1",
                            Value = "opt1"
                    },
                new SelectListItem
                    {
                            Text = "Option 2",
                            Value = "opt2"
                    },
                new SelectListItem
                    {
                            Text = "Option 3",
                            Value = "opt3"
                    }
        };
//the code is similar for the ListBox method

Notice that I’m passing the same name as the one that is passed to the DropDownList/ListBox method in the previous example! In scenario 2, you’d start by having a class. Here’s the quickest one I could build:

public class Dto    {
      public IEnumerable<SelectListItem> optionsDrop {
          get {
              return new[] {
                                                new SelectListItem
                                                    {
                                                            Text = "Option 1",
                                                            Value = "opt1"
                                                    },
                                                new SelectListItem
                                                    {
                                                            Text = "Option 2",
                                                            Value = "opt2"
                                                    },
                                                new SelectListItem
                                                    {
                                                            Text = "Option 3",
                                                            Value = "opt3"
                                                    }
                                        };
          }
      }

      public IEnumerable<SelectListItem> optionsList {
          get {
             //similar to the other property...
          }
      }
}

And then you could reduce the method call in your pages to this:

<%= Html.DropDownList(
                    "optionsDrop",
                     "Choose an option"  
             ) %>
<br />
<%= Html.ListBox(
                    "optionsList" 
             ) %>

And that’s it! The dropdown and listbox controls will automatically get the correct SelectListItem from the ViewState initialized by the controller. Interestingly, there’s not an overload for the ListBox method that lets you pass a name and a value for the label (I don’t know what’s the rationale behind that decision, but if you need that additional entry and you want to pass the SelectListItems from your controller, then you’ll need to add that default entry to the list that is passed from the controller). Do keep in mind that you’ll only get this automatic hookup if you don’t pass a valid collection of SelectListItem elements to the helper methods!

If you’re curious, then you’d probably like to know that the assembly of the HTML returned by each of the methods is done by a private method called SelectInternal. There’s also another important helper called GetSelectData which is called when you don’t pass a collection of SelectListItems explicitly to these methods (ie, this method tries to get the SelectListItem collection from the ViewState passed from the controller). The code for these private methods is really simple, so I’ll leave it to you to explore it.

And that’s all for today. Keep tuned because there’s more to come about MVC.

by luisabreu | 4 comment(s)
Filed under: ,
The MVC framework: working with anchors
Thu, Jan 29 2009 13:55

Today we’ll keep talking about the MVC framework and we’ll see how easy it is to add anchors to our apps. In the past, we’ve already seen that the framework introduces a class called UrlHelper that you can use in order to get the correct url for a specific action. So, adding an anchor to a view could be done through code like this:

<a href="<%= this.Url.RouteUrl( "Default", new { action = "About" } ) %>" title="Navigate to about page">
        Go to About
</a>

(btw, I’m assuming that you’ve created a new default project and the previous code is reusing the routes introduced by that template).

As you can see, we’re writing the complete html for the anchor and using the helper in order to get the correct url for the href attribute. You can achieve the same result by using the ActionLink or RouteLink extension methods “added” to the HtmlHelper class. Here’s a snippet with both of them in action:

<%= Html.ActionLink( "Go to About", "About" ) %>

<%= Html.RouteLink( "Got  to About", new { action = "About"} ) %>

As you can see, in this case the syntax for RouteLink is not as direct as the one you’ll get with ActionLink. And there’s a reason for that. Generally, you’ll use the ActionLink method when you want to specify an action and controller. On the other hand, if you also want to set the name of the route, then you can use the RouteLink method.

Both methods have several overloads which let you specify:

  • the name of the controller;
  • the name of the desired action;
  • the dictionary with values that should be passed to the route parameters (ie, an element of type RouteValueDictionary with values that are passed to the existing route parameters);
  • the HTML attributes that should be applied to the generated anchor;
  • the HTML protocol you want to use;
  • the hostname (if you want to set it explicitly);
  • the fragment used to identify a named anchor (so that you can specify urls a la http://…something#name).

Additionally, the RouteLink method will also let you pass the name of the route (as we’ve seen above). Internally, both methods end up calling the more general GenerateLink method (which is public and static and defined by the HtmlHelper class).

One more note before ending: the more astute readers have already spotted that the 1st example (where we specified the URL through the UrlHelper class) generates slightly different HTML. The difference lays on the HTML title attribute, which isn’t generated when we used the HtmlHelper extension methods. If you need to set that attribute, you’ll have to use one of the overloads that receives the HTML attributes that should be rendered (don’t forget that at least one of the overloads receives an Object parameter, which means that you can use anonymous objects for setting the attributes you need).

And that’s all for today. More about the MVC framework on the next posts.

by luisabreu | 3 comment(s)
Filed under: ,
IQ digest
Wed, Jan 28 2009 21:42

Couldn’t resist putting this here…

by luisabreu | with no comments
Filed under:
ASP.NET RC released
Wed, Jan 28 2009 11:49

Get all the details from Scott Gu.

by luisabreu | with no comments
Filed under: ,
The MVC platform: wrapping up the textbox helper
Mon, Jan 26 2009 10:29

After a long pause, it’s time to go back to the MVC series. Today I’ll wrap up with a last post which mentions a scenario I’ve missed when I talked about the automatic hooking of properties to form fields. In a previous post, we’ve seen how easy it is to associate fields to simple properties of an object. Today, we’re going to see how easy it is to bind complex properties (ie, properties which are classes themselves). We’ll reuse the class presented in one of the previous posts and we’ll change it so that it has a complex property:

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

As you can see, this is really a contrived example, but it will do for now since my only objective is to show you how to hook up the complex property to the control. So, the big question is what must you do so that the MoreInfo subproperty is automatically filled with the control’s value? Easy: just set the name parameter of the helper to the “complete” name of the property. Here’s the code I’ve added to the existing HTML code presented in an earlier example:

<label for="AuxiliaryInformation.MoreInfo">Auxiliary info:</label>
<%=Html.TextBox("AuxiliaryInformation.MoreInfo")%>

And that’s it. If you have a method similar to the one presented in this post, you’ll notice that the AuxiliaryInformation property is correctly filled with the value passed from the HTML input you’ve added to the page. I’ve run some tests and you’ll be happy to know that the property is correctly filled even when you have readonly complex properties (that is, even if AuxiliaryInformation is read-only, you’ll be able to pass a value to the  MoreInfo “sub-property”).

Do notice that you need to pass the same value to the for attribute of the HTML label so that it is associated with the generated textbox. And that it’s it for this post. Keep tuned!

by luisabreu | with no comments
Filed under: ,
Book review: Tribes
Wed, Jan 21 2009 21:56

I’ve just finished reading Godin’s Tribes book. It’s really an interesting, motivational reading which will surely inspire you in leading others and creating “tribes”. Even though you’re free to disagree with his ideas (I didn’t bought them all), it’s undeniable that Seth pin points the main reason why we don’t do what we probably should: fear. Fear of being joked, fear of loosing the job, etc, etc.

It’s really a short book, which, as you might know by now, is really good because as time passes by I’m getting less and less time for leisure (I need to do something about this because it’s really starting to be a problem). Anyway, I did enjoy it and recommend it. I’m giving it 8/10.

by luisabreu | with no comments
Filed under:
Some windows 7 shortcuts
Wed, Jan 21 2009 14:43

Ok, I’m putting this here under windows 7 category, but I really don’t know if some of this stuff didn’t already exist in previous versions of windows (since I’m only running 7 now, I’m not sure if I’ll ever go back to see if it works or not). As you know, you can drag a window to the side of the screen and it will automatically resize to fit that half of the screen. In other words, if you drag a window to the right you’ll notice that when the mouse icon reaches the right border of the screen you’ll have some feedback that indicates that the window will be resized to fill that right half.

What I didn’t know is that you can achieve the same result by using the shortcut win+left/right arrow (depending on which side you which to “anchor” or window). Btw, you make maximize window by using win+up arrow and you can restore or minimize by using the win+down arrow shortcut.

by luisabreu | with no comments
Filed under:
EF first impressions
Tue, Jan 20 2009 11:52

In these last 2 days I’ve been reading several documents on the ADO.NET Entity Framework. My main objective here is see if it is ready for being used in projects based on the DDD philosophy. Even though I still haven’t started writing code, it seems evident to me that EF is still a far away from being my persistence platform of choice. before going on, here’s what I intended to do in my current project:

  • start by building an adequate OO model to my current domain. Even though the model needs to accommodate some info that only matters to the db (ex.: Id and version fields), I would love it to be relatively PI;
  • Introduce the concept of repository and then build several implementations with different technologies in order to compare the final result;
  • keep it really simple. In fact, I kept it so simple that I’m not even using inheritance. Just plain references and collections to other entities and value objects.

With these objectives defined, I started looking at EF. After some searching, it become evident that I’d really have to change my objects (beside adding the ID and Version fields). Ok, so EF does not support POCO, but it does support something they called IPOCO. According to what I’ve seen (and I can be wrong), the idea is that instead of reusing the  EF default base class for entities, you could simply implement some interfaces (according to my research, you should be interested in implementing IEntityWithChangeTracker, IEntityWithKey and IEntityWithRelationships – of course, depending on your current scenario). btw, implementing these interface will also mean that you’ll have to change your properties’ code because you’re supposed to notify a “tracker” whenever one of the properties of your objects changes.

Besides the interfaces, you must also decorate your props/classes (and even the assembly) with some attributes. For example, you should use the EDMScalarPropertyAttribute for a primitive property that should be mapped onto a table column (not related, but isn’t this a violation of one  of the naming rules verified by FxCop? I’m glad that I’m not the only one breaking them :) ). Hum…not looking good, right?

Now, I told you that I wasn’t using inheritance and this is  a pity because it seems like EF supports all forms of inheritance available on ORM mapping. And it even looks like you can configure these options by using the designer (ok, I didn’t checked it but I’ve found at least an example of these mappings which showed how to do that in the designer). Unfortunately, it seems like for adding value type mappings (I believe that the technical term in EF is complex types) you’ll really need to write the CSDL file by hand and then use the command line tool (edmgen.exe) to generate the remaining files.

Now, this (having to do it by hand – and I’m hoping that someone will drop a comment saying that there is a way of doing this in the designer) is really bad. One of the advantages that I thought EF had was providing a good designer (something which NH doesn’t have). Even though this is v1.0, i did expect to be able to do this from the designer as I didn’t really intended to get my hands dirty with the XML (If I really need to understand all those XML dialects they’ve created then I’ll probably use that from within the VS instead of using their designer). So, in the end I guess that this is minus 2 points for EF.

My last complaint of the day is related with references to other instances. You need to use some base class for those scenarios. For instance, if your object has a collection of other objects, each mapped to different tables, then you’re supposed to model that by using an EntityCollection<T> class. Again, I don’t like this.

So, this leaves me with one option: using a translation layer for mapping the entity generated classes into my domain classes .I don’t really see much value in using the entity generated classes as my domain classes and one of my objectives was to have a fixed set of domain classes. I do hope to have better reviews after starting to write some code since my first impressions are really that good.

Now, I’ve also seen a PDC vide which looks promising but i really didn’t find any release with those beta bits, so I’ll just keep using the current version until another more promising version is released.

by luisabreu | 1 comment(s)
Filed under: , ,
S#arp 1.0 beta is out
Tue, Jan 20 2009 10:27

Go get it here.

by luisabreu | with no comments
Filed under: ,
Snowing in Madeira
Fri, Jan 16 2009 20:53

Snowing is something which doesn’t happen that often here (and when it happens, it generally goes away really quickly). However, this year I’ve managed to get some time to go to our beautiful Pico do Arieiro where I took some pics with my wife’s phone (unfortunately the HTC I’ve bought is having problems again, but that’s a story for another day). So, without any more delays, here I am on Pico Arieiro with 0ºC :)

011609165142

btw, I wasn’t sleeping…just looking at the snow :)

by luisabreu | with no comments
Filed under:
Accessing the global namespace
Thu, Jan 15 2009 15:15

Even though it exists for a long time, there are still some guys which are surprised whenever they see something like this:

global::System.Console.WriteLine( “Hello” );

what is that global:: thing over there? Well, it’s there for saying that search for the System.Console class should start at the global namespace. You’ll need this kind of thing whenever you have types/namespaces that hide the global ones. The documentation on MSDN explains all these concepts really well, so I’ll just redirect you there.

btw, it’s possible that you’ll end up seeing this code generated by tools (if I’m not mistaken, you’ll be seeing it whenever you look at the code generated for the classes that are mapped into tables on the EF framework).

by luisabreu | with no comments
Filed under:
Book review: Clean Code
Thu, Jan 15 2009 13:43

Today I’ve finished reading Robert Martin’s Clean Code. I’ve really enjoyed reading the book. It’s really great and what you’d expect from someone with the experience and expertise of Robert Martin. Besides giving lots of advice for some basic scenarios in coding (ex.: variable and function names, formatting, etc), you’ll also find interesting information regarding patterns and recommendations on how to write good OO code.

The second part of the book presents several case studies which show how you can apply the principles explained earlier to improve the quality of existing code. I think this part could have been improved by reducing the number of case studies (in my opinion, one case study would really be enough for illustrating the principles introduced earlier).

The last part of the book resumes the smells and problems introduced earlier by presenting a list and a small description of those problems. The appendix on concurrency is interesting too. This means I’m giving it 8/10.

by luisabreu | with no comments
Filed under:
JQuery 1.3 released
Wed, Jan 14 2009 21:17

Hurray!!!

by luisabreu | with no comments
Filed under:
Windows 7: Action Center
Tue, Jan 13 2009 22:59

Today I had some more time to play with Windows 7 and one of the interesting new things I’ve noticed is the Action Center.  You’ll be able to open  action center by clicking on icon that exists on your notification area (if you haven’t changed it) or by searching it on the items on the control panel. The action center is the place to go to find  all the problems detected in your PC and for getting possible answers to those problems. Here’s snapshot of the problems detected on my pc:

actioncenter

As you can see, I’m missing an antivirus…I really need to take care of that, but I’ll leave it for a future day :)

As you might expect, you can configure the messages that are shown there. Here’s a snapshot of the available configuration options:

configuration

In this tool you can also configure the maintenance settings. Probably, the most important one is system backup (which, as you might have guessed, I still haven’t configured :)).

Now, there really is an important feature here which you’ll love: User Account Control settings. This option gives you access to a slide which lets you configure the notification level you want to get whenever you’re doing administration operations. The current default has been working well for me but I know a couple of guys which will quickly push the slide to “Never notify”.

usercontrol

And that’s all for today.

by luisabreu | with no comments
Filed under:
Windows 7 first impressions
Mon, Jan 12 2009 23:03

It’s been three days since I’ve installed Windows 7 on my Asus 1000h. Until now, the experience has been really good. I’ve managed to install everything I had on my previous OS and everything is working without any compatibility problems. Ok, not everything. The chipset software installation program refuses to install, but everything else worked perfectly. In fact, this time I was able to get the correct definition for my video card (which is in board) without having to install the drivers from Intel.

I do look the new UI and the idea of getting rid of taskbars and merging everything into a single taskbar seems good. I still haven’t tested the new network stuff (where you’re able to configure several networks and save them so that you can automatically get the devices on each network whenever you reconnect) and it looks like I won’t be doing that because it requires Windows 7 on all the pcs.

One thing I’ve noticed is the new calculator program.Besides  the features we’re used to, now you can convert from one unit to another (lots of different things to convert to/from there), make some basic operations between dates (ex.: add/subtract days to a date) and even run some basic calculations on your mortgage or gas mileage! Ok, nothing really astonishing, but at least this time they’ve added something useful (the conversions have just made my day!).

I’ll keep blogging about Windows 7 on future posts. Keep tuned!

P.S.: some guys asked about the rest of my posts on MVC. Well, I’ll finished them in the next days too so if that is important to you, don’t forget to keep an eye on this space.

by luisabreu | 2 comment(s)
Filed under:
Putting controllers into different assembly on MVC project
Mon, Jan 12 2009 19:19

Billy McCafferty, mentor and leader of the S#arp project, has an interesting post where he justifies the separation of the controllers into a different assembly. It’s not that I don’t agree with his reasons and his objectives (I really do!); I just think that this separation isn’t really needed for guarantying that  you get better code for the controllers.

My rule of the thumb regarding physical separation is a simple: I will only separate code into different assemblies if I need to change the implementation of a contract at runtime or if I want to reuse that code on different projects. Will this happen with the controllers of an ASP.NET MVC project? I don’t know. I guess that it depends on the  project and on the controller. If you’re going to reuse the controller code across different MVC projects, then I guess that you should do that and put that code into a different assembly.  On the other hand, if you’re building a specific controller then I think there’s no need in putting it on a different assembly.

Probably you’ll start like me: code  and refactoring along time, which means that you’ll probably start with a single project and then you’ll refactor it into different assemblies. But don’t forget one important thing: keeping it on the same assembly as your MVC project isn’t an excuse for being sloppy and start hard coding your dependencies into  your controllers.

by luisabreu | with no comments
Filed under:
Book review: IWoz
Sun, Jan 11 2009 22:20

I’ve just finished reading Steve Wozniak’s book and I can tell you that it was really an interesting experience. You’ll only be able to enjoy it if you’re into the history of the PC. In about 300 pages you’ll learn about his early inventions (his school calculator project was really interesting) and on how he developed the Apple I/II which ended up conquering the market.

The only thing I didn’t like is seeing the same thing repeated several times (not sure why, but it seems like American books of this gender tend to repeat the ideas contained on it several times, which makes it a little boring). Overall, I’m giving it 7/10

by luisabreu | with no comments
Filed under:
Windows 7 on Asus 1000h
Fri, Jan 9 2009 22:42

I’ve just finished installing Windows 7 on my Asus 1000h. Until now, everything looks really really great! btw, it took around 20 mins to install Windows 7 through the USB pen. Incredible, incredible, incredible…

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

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover