Changes as of January 2010

It’s with a bittersweet feeling that I write this post. As of January, I will no longer be with iMeta Technologies. During my time here, I’ve been involved in some awesome projects, had the privilege of working with some very smart and talented people, and made some great friends. I wish you all the best success in the future.

As of January, I'm starting a new job. I’m going to go back to working from home, something I did for 8 years prior to joining iMeta, so for me it feels like home (pun intended). I have to admit that as much as I liked the office buzz and enjoyed every minute of working with Steve and his eternal ramblings on expression trees, I am happy to not face morning and afternoon commutes.

So what’s my new job? Well it comes as no surprise to many to say that I’ve been a fan of a tool called ReSharper for quite some time. I’ve been a member of the JetBrains Academy for a few years and have collaborated with JetBrains at various conference booths. We’ve now decided to formalize the relationship.

I’m very excited to announce that as of January I will be joining JetBrains. My primary role will be to help promote their products on the .NET side, which include ReSharper, dotTrace, as well as cross-platform tools such as TeamCity, YouTrack or WebIDE. As part of my job, I’ll be doing screen casts, blogging, and not only about using the tools, but also focusing on best practices, boosting productivity, etc. As a company that firmly believes in OSS, it also means that I’ll be increasing my participation in OSS projects and actually get to code on things I enjoy!

I’ll be active in the community, continuing to speak at conferences and events, as well as serve as a liaison for JetBrains. I’ll continue to blog on my own site as well as devlicious.

As far as Twitter, we’ll be pushing the Tool-Specific Twitter accounts for ReSharper and dotTrace, so make sure you follow them! You can contact me via my own twitter feed, and of course, don’t forget Ilya, also known as Orangy, ReSharper PM!

With that, all that’s left to say is Happy New Year and we’ll talk in 2010! And don’t start 2010 without ReSharper!

Dynamic objects and ReSharper

 

As you might have heard by now, C# 4.0 (or is it just 4?…) comes with a new keyword: dynamic. This means that you could do something like the following:

image

Simply put, ExpandoObject is a class that allows you to add and remove members at runtime. This allows us to call methods that are resolved at runtime. As such, the previous code will compile.

Just as you can declare methods, you can also declare properties:

image

This no doubt can come in handy when working with ViewModels and ASP.NET MVC.

However, there is one minor problem with dynamic objects: you lose intellisense, which means that if in your view, instead of typing dynaCustomer.FirstName, you type dynaCustomer.FristName, you won’t get any errors until you run the app.

image

And that’s where ReSharper can help:

image

This is the same code, but with ReSharper activated inside Visual Studio 2010! I typed the FirstName property for the first time. After that, I have full intellisense support for it. The same would apply to methods:

image

That puts dynamic into perspective.

2 Comments Filed Under [ Tools C# ]
Getting your OSS binaries with Horn

Recently Billy McCafferty wrote a post on Horn, a package manager that Paul Cowan and Dave the Ninja have developed, similar to the idea of Ruby’s Gem. Although it’s a step in the right direction, it does have issues. To be able to use it, you need to download Horn and build it. But not only that, you also need to install Subversion, Git, Powershell, Rake, PSake, Cake, Fake…and a whole slew of SCM’s and build tools. Why? Because Horn builds from source. As such, it needs to access the SCM a specific project uses, download the files locally and run the build script. Since OSS projects are free to choose what build script they use, that also adds to the complexity. Some are happy with MSBuild, which isn’t normally an issue since it’s part of every .NET install. However, others use Rake, which in turn requires Ruby. You get the picture…

Although this isn’t necessarily an issue for some people, for others, it is. Forgetting for a moment scenarios such as those imposed by IT departments on corporate networks (permissions to install software, firewall, etc..), there are many that are not too comfortable with building from source, something beyond running an MSBuild file or compiling a VS solution inside the IDE.

 

Welcome to Horn Server-Side

In order to ease some of these concerns, the Horn team developed a server-side solution. A service now takes care of figuring out all dependencies and building packages and since it does this on a scheduled basis, it saves you the time of having to wait for a project to be built. This also saves you from having to install anything on your machine, including SCM’s and build tools. In fact, you don’t need to install anything if you don’t want to. For you to interact with this server, Dave built an ASP.NET MVC application that shows all the OSS packages in their respective categories. For each package there is normally the official released version and the trunk. iMeta has gracefully offered to host the server up in clouds. Go see for yourself.

If you prefer a command line version, I hacked one together in a morning and it’s available from the Horn repository. This allows you to issue commands like:

horn-get –u http://hornget.net –c orm –d nhibernate-2.1

which will download NHibernate 2.1 zip for you with the necessary binaries.

 

Take a look, experiment and provide feedback to the Horn team. There is still room for improvement, but no doubt, Horn is helping remove some of the barriers in the adoption of Open Source.

Add Comment Filed Under [ Tools ]
var improves readability

 

Countless times I’ve heard the argument that you should use the var keyword with caution, that it decreases readability of your code, or how it can be misused.

The example given in the linked post is:

    var Data = GetData(); 

 

According to the blog post, GetData returns a DataTable, something not inherently apparent. The problem however is due to the naming conventions used by the developer.

Firstly, GetData is a method indicating that it returns Data. The problem is, pretty much anything is Data. There has to be a more precise definition of what it is the method is actually doing. By this, I don’t mean you should necessarily rename the method to GetDataTable, since this doesn’t help. This just indicates what type it is returning, not what the method is doing. It would be an appropriate name if the domain of the problem were somehow about types, but in a business scenario, it doesn’t provide much value.

The second issue and just as important, is the variable name, data. Again, it is not descriptive enough. What is data? What kind of information does it hold? Is it a car? Is it many cars?

By using var, you are forcing yourself to think more about how you name methods and variables, instead of relying on the type system to improve readability, something that is more an implementation detail. Using the var keyword is not about being lazy, quite the contrary.

It’s all about the delivery


The Dependency Inversion Principle states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

(Source WikiPedia).

Throw that at a terrible programmer, and all you’ll get is a terrible programmer that is annoyed and hates you. So true!

Take the following method:

        public void PrintHelloMessage()
        {
            Console.WriteLine("Hello");
        }

Now ask a developer to add a new method to print the message ‘Goodbye’. Do you think he would do:

        public void PrintGoodbyeMessage()
{
Console.WriteLine("Goodbye");
}


or:

        public void PrintMessage(string message)
{
Console.WriteLine(message);
}

Most likely, he’d do the latter. Why? Because he realizes he’s gaining a benefit by passing a parameter to a method. He knows that if tomorrow you ask him for a “Good Afternoon” message, he won’t have to write a new method.

What is Dependency Injection? It’s one way of complying with the Dependency Inversion Principle. However, when you think about it, what does it boil down to? Passing a parameter to a method, which happens to be a constructor. It seems simple enough doesn’t it? Yet, it’s hard for people to understand it. Why? because they don’t see the value in it.

Explaining a principle to someone without them understanding the benefits and values they get out of it is useless, and that is why concepts such as Dependency Injection or Inversion of Control seem overly complex to the vast majority of developers (believe it or not, those of us that use these things are still a very big minority). It’s complex because they haven’t been explained the values of it. They’ve just been thrown some definition and they are expected to understand that it’s bad for one class to create an instance of another class it uses.

Present a developer with the following code:

    public class AuthServices
    {
        public void AuthUser(string username, string password)
        {
            var authDAL = new AuthDAL();
 
            var user = authDAL.GetUserByUsername(username);
 
            if (user != null)
            {
                if ...
            }
 
        }
    }

and ask them how they’d go about testing this code without having access to a database. Ask them how they’d go about changing AuthDAL for some fake DAL that doesn’t really connect to a database.

They’ll probably come up with the solution of passing the AuthDAL class in as a parameter, and eventually realizing that multiple methods will use the same class, they’ll pass it in via the constructor and set it as an instance field. As long as their AuthDAL has virtual methods, they can create any fake DAL that overrides those methods and returns some dummy value. They might argue that they don’t want virtual methods. And that’s fine. Tell them to define the parameter as an interface. In fact, they probably have already heard of a principle that says that you should program to an interface and not a class. They’ll eventually end up with this code:

  public class AuthServices
{
IAuthDAL authDAL;

public AuthServices(IAuthDAL authDAL)
{
_authDAL = authDAL;
}

public void AuthUser(string username, string password)
{
var user = _authDAL.GetUserByUsername(username);

if (user != null)
{
if ...
}

}
}

 

And voila! You have Dependency Injection via Constructor.

Once they *get* that, then explain to them other benefits, you know the real benefits they get from doing this: decoupled code, easy maintenance, promotion of SRP, etc.  and then throw the principle in their face:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

And they’ll see how it all makes sense.

It’s not about throwing or not throwing books. It’s about showing people how something can help them, how they get value of it.

Joined the tasty bites

 

Last week I was invited to join devlcio.us, part of codebetter.com blog network. Unfortunately with all the travelling I’ve not had a chance to even do my first blog post or thank both Jak and Brendan for the invitation, and seeing I’m currently stuck at Franfurt Airport on a 5 hour layover, it’s a better time than any.

I’ll still be blogging on my regular sites, and as always, any non-technical off-topic posts will remain exclusively on my own site.

List my controllers for me…

 

Nuff said!

image

Really liking Resharper 5.

Resharper 5 support for MVC

 

Resharper 5 has a couple of new features for MVC that can make your life somewhat easier. Take a look at the following screenshot:

image

That’s inside an ASPX ViewPage. The first thing is the “Abouta” underlined in blue. The hint tells me that this action does not exist. “Home” on the other hand, which corresponds to a controller is underlined, meaning you can navigate to it from there (ctrl+left mouse click).

In the case of the action not existing, if we haven’t spelt it wrong, we can ask Resharper to create it for us:

image

which generates the corresponding action in the controller:

image

Simple, yet very productive!

The Principle of Least Surprise

 

I’m having a discussion on the ASP.NET MVC forums with one of the guys from the ASP.NET team in regard to the Data Annotations in MVC 2 and I’m not sure I agree with him. Here’s an issue Jak and I have run into:

In MVC 2 there’s a new Html Helper named EditorForModel(); that renders out a form based on the properties of your model, along with the validation messages, labels, etc. So something like this:

 

   <% using (Html.BeginForm()) {%>
 
        <%=Html.EditorForModel() %>     
            <p>
                <input type="submit" value="Save" />
            </p>
    <% } %>

 

you’d get something like this:

image

If you want to do individual fields and thus have finer control, you can use the EditorFor helper, passing in a property name. In other words, the previous could be also rendered as:

    <% using (Html.BeginForm()) {%>
 
        
   <%=Html.EditorFor( model => model.FirstName) %> 
   <%=Html.EditorFor( model => model.LastName) %>
   <%=Html.EditorFor( model => model.Email) %>
        
            <p>
                <input type="submit" value="Save" />
            </p>
    <% } %>

but this time you don’t get the labels:

image

The problem however is that you lose something else: the Validation messages. If you have client-side validation enabled, the previous ASPX file generates a pretty much useless call to the EnableClientValidation JS function:

EnableClientValidation({"Fields":[],"FormId":"form0"}, null);

 

as opposed to:

EnableClientValidation({"Fields":[{"FieldName":"FirstName","ValidationRules":[{"ErrorMessage":"First name is required","ValidationParameters":....
 
// rest omitted for brevity

 

The result of course is that client-validation doesn’t work (and from what I’ve heard causes JS errors in some browsers).

The solution to this is to explicitly add a Validation Message, like so:

<%=Html.ValidationMessage("FirstName")%>

Now I understand that EditorFor is for fine-tuning and there is a corresponding LabelFor (although a ValidationFor doesn’t exist yet), but my main concern here is that it’s breaking the principle of least surprise from an API perspective.

For me, the only difference between EditorFor and EditorForModel should be that in the first I specify a property name explicitly whereas in the latter it just assumes the whole model. Nothing is telling me by the name of the method that the second does a whole bunch more of magic.

One solution is for EditorFor to be renamed to something else if it’s ONLY going to provide the input box (be it a text area, checkbox, radio group, etc..).

Thoughts?

Add Comment Filed Under [ ASP.NET MVC ]
Testing Model Validations?

 

ASP.NET MVC 2 allows you to do data validation, either using the de-facto Data Annotations or plugging in your own, much in the same way xVal work. If you’re interested in seeing how that works, take a look at this post.

This post however concerns testing. Here’s some code:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Customer customer)
{
    if (ModelState.IsValid)
    {
    return RedirectToAction("Index");
    }
    return View(customer);
}

This code checks to see if my model is valid. If it is, it then saves it (not in the code) and redirects to the index action, thus producing a RedirectToActionResult. If it is not valid, it will return a ViewResult. Here’s the model:

public class Customer
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
}

Given the previous, what would you expect the following test to do? Pass or fail?

    [Fact]
    public void wont_give_you_any_hints()
    {
    var controller = new CustomerController();
 
    var customer = new Customer();
 
    customer.FirstName = "Jak a.k.a. Casey";
    customer.LastName = String.Empty;
 
    var result = controller.Create(customer);
 
    Assert.IsType(typeof(ViewResult), result);
    }

I’ll give you a hint. It fails. Now I understand why it fails. My problem however is that for me to test my model is valid is going to force me to change the way I have to write my code, and potentially make it less readable.

Problem with Client-Side Validation in MVC 2

 

[Note: This post applies to ASP.NET MVC 2, Preview 2.0]

Today while doing the demo for the previous post, I ran into an issue where the Javascript code for the client-side validation (the call to EnableClientValidation ) was not being output during the form rendering.

Take a look at the following two snippets:

First:

    <% Html.BeginForm();%>
 
        <%=Html.EditorForModel() %>     
            <p>
                <input type="submit" value="Save" />
            </p>
    <% Html.EndForm(); %>

 

Second:

  <% using (Html.BeginForm()) {%>
 
        <%=Html.EditorForModel() %>     
            <p>
                <input type="submit" value="Save" />
            </p>
    <% } %>

 

See the difference? The latter is using the using statement. In my previous post I’m using this option and all works well. However, if you go with the first option, the Javascript call will not be output. The reason for this (after debugging the source) is that the call to make this happen takes place in the Dispose method of the MvcForm. Explicitly calling Html.EndForm won’t cause this to take place.

I’ve talked to Mathew from the QA team, and he’s confirmed it’s a known issue. I think the output of the JS code should ideally be decoupled from the form construction. For instance, If I were to use a manual form tag, this wouldn’t work either [I’ve haven’t given it that much thought either].

In the meantime, if you want client-side validation, make sure you use the second option.

One Comment Filed Under [ ASP.NET MVC ]
Client-Side Validation in MVC 2

 

ASP.NET MVC 2 Preview 2 now ships with client-side validation built into the box. It follows the same idea as the xVal framework whereby you can define validation rules once and have them enforced both on the server and the client.

By default, MVC uses Data Annotations which is available in System.ComponentModel.DataAnnotations on the server and the jQuery Validator plugin on the client. Much like xVal you can customize these to use whatever you want. I’m preparing some demos for next week of how to do client-side validation and since there isn’t much info on it, I’ve decided to post it.

Server-Side Validation

Server-side validation with Data Annotations works without having to take any additional steps. You decorate your model using attributes and the model binder uses this information to set the ModelState.

    public class Customer
    {
        [Required(ErrorMessage = "First name is required")]
        public string FirstName { get; set; }
        [Required(ErrorMessage = "Last name is required")]
        public string LastName { get; set; }
        public string Email { get; set; }
    }

On the server-side you would do the usual to check if the model state is valid and if not display validation messages back to the client:

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, Customer customer)
        {
            if (ModelState.IsValid)
            {
                // TODO: Do whatever...
                return RedirectToAction("Index");
            }
            return View(customer);
        }

The form is:

    <%= Html.ValidationSummary() %>
    <% using (Html.BeginForm()) {%>
 
        <%=Html.EditorForModel() %>     
            <p>
                <input type="submit" value="Save" />
            </p>
    <% } %>
    

(I’m using the EditForModel which will automatically generate an input field for each property of the model. If you want finer control you can spit out individual fields or use templates).

Client-Side Validation

Client-Side validation kicks in only if it is explicitly activated in the view. To do this, you need to call EnableClientValidation as shown below:

 
    <% Html.EnableClientValidation(); %>
    <%= Html.ValidationSummary() %>
    <% using (Html.BeginForm()) {%>
 
        <%=Html.EditorForModel() %>     
            <p>
                <input type="submit" value="Save" />
            </p>
    <% } %>
 
 

 

By doing this, when the form is generated, the MVC framework will add a call to JS function EnableClientValidation passing in the correct parameters based on the data annotation attributes defined on the model. Last but not least, we need to include 3 Javascript files in the View (I normally put them in Site.Master).

    <script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcJQueryValidation.js" type="text/javascript"></script>

Make sure you include the last file, where EnableClientValidation is defined. That’s all there is to it. Once you run this, your app will have both client side and server side validation using the default Data Annotations and jQuery Validator.

Download demo from here

Avoiding an unintentional bottleneck

 

We’re all busy these days and sometimes it’s really hard to get any work done with continuous interruptions. As developers we know that it’s hard to get into the mindset that allows us to concentrate on designing a certain class or fixing that retched bug, and any minor incident can throw us way off and place us back at the starting line.

Now I’m sure that it’s not only developers that have this problem. Any type of work the requires concentration probably has the same issues. It just so happens that most of my life has been spent developing software and I speak from experience. Getting interrupted while working on code is a pain!

Avoiding Interruptions

Interruptions can come in the form of emails, telephone calls, instant messaging and recently the more popular Twittering, which I’m finding is substantially limiting my ability to both read or write more than 140 characters. In fact, I’ve written this post via a Windows Live Writer plug-in that injects 140 chars at a time. 

There are several ways to cope with this problem. For example when using Outlook, you can suspend the Send/Receive for certain periods of time, or just do what I do and shutdown the damn thing, as much the same with Twitter, Skype, etc. I assign myself periods of a minimum of one hour where I just code, and not deal with email, messages or Twitter. I then take a 5-15 minute break, check all correspondence and go back what I was doing. I find it helps me be much more productive. Other people use techniques such as the Pomodoro or Pair Programming, which personally I find very productive on many levels, but in terms of interruptions. While sitting with someone, it feels kind of wrong to be chatting on Skype or replying to emails while making your coding partner wait. As such, you tend to not do it so often, and avoid potentially embarrassing situations

image

Avoid causing bottlenecks for others

Increasing productivity is one of the major benefits of avoiding disruptions. Like anything however, there’s always two sides to every story.

Whether working on a team or solo, you tend to interact with people, be it a team member, someone else in your company, customers or 3rd parties you deal with. These interactions are mostly based on emails, IMS’s or phone calls, you know. the same things that disrupt our productivity. Now it’s great for you to be able to control them to increase your throughput, but you need to also bear in mind that what you’re doing is potentially holding up someone else’s productivity.

If someone sends you an email to ask for information about a certain project, or how something should be done or who to contact for a particular thing, these issues might not be effecting your job directly, but most likely it is interrupting theirs.

That is why it’s important to remember that when responding to someone, especially with emails where there is an inherent delay, to always take into account how important the reply is for them, more than for yourself. Does it hold them up? Is it a potential issue?

Obviously sometimes a response requires a little more work, but it’s also very important to communicate this to the originator. Tell them that you need 2 hours to get back to them and you can’t fit it in for another 2 days. The important thing is to not leave people hanging.

Remember, what’s not important for you, might be critical for others. Sometimes I miss the Urgent flag in Gmail. It’s utterly useless for SMTP servers, but it does communicate intent to the receiver of the mail (albeit abused by many).

Add Comment Filed Under [ Productivity ]
Upcoming talks

 

Start of the “conference season” again and I’ll be doing a tour of a few countries and places. Hope to meet up with some of you at some place and time. This time I’ll try and have all sessions ready so I can spend my time more productively at the bar/restaurant

- 21st to 25th September at BASTA! in Germany. Talks on ASP.NET MVC, jQuery, TDD, Design Principles.

- 27th to 30th September at Entwickler Konferenz in Germany. Talks on ASP.NET MVC, TDD.

- 12th to 13th October at DevReach in Bulgaria. Talks on ASP.NET MVC, Design Principles.

- 16th to 17th October at TTT/CodeCamp in Tarragona. Talks on MEF and Design Principles.

- 18th to 21st October at SDC in The Netherlands. Talks on ASP.NET MVC.

- 29th October at Micrsoft in Madrid. Workshop on Design Principles (Link available soon)

I’ve also pre-recorded 3 sessions for an online virtual conference on ASP.NET MVC, jQuery and Mocks, all in Delphi Prism and it’s happening right now on CodeRage

 

 

-

Spanish Keyboard layout for C# Developers

 

I use a Spanish Keyboard which is kind of a nuisance when developing in C#. It’s mainly due to the key layout for curly braces. Every time you need curly braces, you have to press AltGr (Ctrl+Alt) along with another key. Other annoying keys are the semicolon and the square brackets.

image

(Image licensed under the Creative Commons Attribution ShareAlike 3.0, obtained from Wikimedia Commons)

So after years of frustration, I finally decided to call it a day. Today I ran into the Microsoft Keyboard Layout Creator which allows you to create custom keyboard layouts. It’s pretty simple to use and extremely flexible since it allows you define dead keys also (which was part of the my problem when attempting to do it manually using the Scancode Maps). You can change key mappings or define a whole new keyboard layout from scratch.

My new mapping is based on the original Spanish layout, switching the key combinations required for curly braces and square brackets. Instead of getting a tilde by default, you now get braces and brackets. If you want the original characters, you need to use AltGr. I’ve switched the semicolon and comma around also. You no longer need to use shift to obtain a semicolon. I’ll see how it works out, although I must admit while writing this post, every time I’ve wanted to insert a comma, I’ve ended up with a ;

The tool creates a convenient executable so that you can install the new mapping on any machine without a lot of fuss. I’m including both the executables (x86, 64bit, etc.) along with the project file to this post. Feel free to use it or adjust it to your own needs. Get it here

3 Comments Filed Under [ C# ]
ASP.NET MVC 2 - Preview 1

It's out. You can download it from here. Some of the new things it includes ("extracted" from the readme for your convenience):

 

  • Areas: When creating larger ASP.NET MVC applications, you tend to create controllers and views that might be named the same but belong to different aspects of the application (for example you might have a HomeController for Customers and one for Administration). Areas allows you to create "sub-projects" inside your project to group these.

 

  • [HttpPost]: Shortcut for putting [AcceptVerbs(HttpVerbs.Post)]

 

  • DataAnnotations: The default model binder supports DataAnnotations for validation

 

  • DefaultValueAttribte: For types of Int32, DateTime or Guid's you can now specify a default value on the action declaration to better comply with your routing patterns.

 

  • Supprot for byte[] and Data.Linq.Binary: Default Model binder now supports these types.

 

  • API improvments

  • Templated Helpers: Basically allows you to associate types to certain elements for display/editing.

 

The only breaking changes it seems is introduction of the Area keyword and a signature change in DefaultControllerFactory. That means if you're using a custom controller factory for IoC for example (and if you're not, you should be), you'll need to update your app.

There's nothing in the README regarding the inclusion of the strongly-typed helpers from the Futures assembly or any new strongly-typed Html Helpers for element rendering. Not sure if they are included in this assembly or might come in the next preview.

Now to go play with it a little...

Add Comment Filed Under [ ASP.NET MVC ]
ReSharper's Hidden Gem

During NDC, Eugene, from JetBrains, Technical Lead for ReSharper, showed me some of the cool things that are coming out in the next version, 5.0. But guess what? I'm not going to talk about those now :).

What I am going to talk about is an interesting problem he said they were having and something many of us also experience: building solutions.

Visual Studio takes some time to build solutions when something changes. The reasons for this are two-fold:

 

  1. Sequential Builds. When Visual Studio builds projects, it does them in a sequential order, even if these are completely independent. So let's say you have 20 projects, 15 of which are completely unrelated, Visual Studio will still build these sequentially.
  2. Dependencies. When you have one project that references another, Visual Studio will always re-build the referencing project if referenced project has changed.

 

And being ReSharper quite a large solution, it was taking them approximately five minutes to build, and they needed a fix for this.

One of the not-so-well-known features of MSBuild is the possibility of building projects in parallel. This is a feature that ships with the MSBuild 3.5 Tool set. The following code shows a simple MSBuild project that takes advantage of this feature:

 

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
   3:   <ItemGroup>
   4:     <ProjectReference Include="**\*.csproj"/>
   5:   </ItemGroup>
   6:   <Target Name="BuildProjectSet1">
   7:     <MSBuild Projects="@(ProjectReference)" BuildInParallel="true"/>
   8:   </Target>
   9: </Project>

Combining this with the maxcpucount command line argument, you can specify the number of parallel builds.

Now this solves the first issue, of having independent projects build in parallel as opposed to sequentially, but what about the second problem? Every time you make a change in a project that is referenced in another project, Visual Studio will build the latter, even if none of the public interfaces have changed. Just so we make sure we're on the same page, let's go thru an example:

 

Building NHibernate using Visual Studio

If you've never built NHibernate before, the first time you need to run the NANT script for it to generate the missing AssemblyInfo.cs files, etc. Once you've done that, you can build it inside Visual Studio.

We first do a BUILD ALL and notice how seven projects get built:

 

Solution Window

image

 

Build Output

image

 

Now let's make a change to NHibernate.csproj, which is referenced by the majority of the other projects. We'll add a new public class to it:

image

 

If we now Build the entire solution, all projects that reference NHibernate will get re-built. This is expected behaviour since we've made a change to the public interface of the referenced assembly. However, what would happen if we just added a few lines of comments:

 

image

 

Despite the public interface not changing, all assemblies that reference NHibernate will be re-built (You can verify this by looking at the timestamps of the assemblies).

 

Verifying what has changed on referenced assemblies

Thinking about it though, why would we want to have Visual Studio rebuild all referenced assemblies even if there hadn't been a public interface change? Wouldn't it be great if that wouldn't happen? 

Here's where ReSharper comes into play. What the guys at JetBrains have done is use the assembly metadata to see if there has been a change in the public interface and ONLY if there has been, build!

This has allowed them to reduce their build time drastically, in some instances dropping down to 30-40 seconds (obviously based on the changes).

What they've done is create their own Solution Builder that examines if the metadata for a referenced assembly has changed. If and only if it has changed, then they build it.

Here's some screenshots of it in action:

 

Projects building concurrently when possible:

image

image

image

 

Build Results:

image

 

If we run the same changes steps against NHibernate as we've done above, using ReSharper's solution builder, we'll see that if there is no interface change on the referenced assemblies, those assemblies that use them don't get re-built. When in a large solution, this saves substantial amount of time as you can imagine. Combined with parallel builds of independent projects and we're on to a winner!

 

So when can I play with this?

The bad news is that as it stands right now, there is no guarantee that this feature will make it in 5.0. The good news is that you already have this feature in ReSharper :). However, before we go on, I have to put in a few words (I promised Eugene I would).

 

DISCLAIMER

WHAT I'M ABOUT TO SHOW YOU IS NOT OFFICIALLY, UNOFFICIALLY OR EVEN REMOTELY SUPPORTED BY JETBRAINS. THEY WILL NOT BE RESPONSIBLE IF YOUR PROJECT GETS CORRUPTED, DELETED, BUILDS SOMEONE ELSE'S PROJECT REMOTELY OVER THE INTERNET OR EVEN BLOWS UP BY ENABLING THE FOLLOWING FEATURES OF RESHARPER. USE PURELY AT YOUR OWN RISK. YOU, YOURSELF, AND POSSIBLY YOUR MOTHER WILL BE RESPONSIBLE FOR ANYTHING THAT HAPPENS FROM NOW ON. YOU CAN'T HOLD ME RESPONSIBLE EITHER, IN CASE THAT IS NOT BLATANTLY OBVIOUS. OH, BTW, THIS MIGHT NOT ALWAYS WORK.

 

 

To enable these features, close down Visual Studio and then start it up with the following command line option: /ReSharper.Internal. If all goes well, you'll have some new options enabled in the ReSharper menu (see image below). If you've got something named wrong, you'll get an error. Shut down and try again.

 

image

 

Obviously, apart from the Solution Builder, you'll see a whole slew of new features pop up under the ReSharper menu. I've not played with a lot of them yet, but plan to when I get a chance. 

 

Building using the Solution Builder

When you first open a project after launching Visual Studio with these features enabled, and try and Build, you'll get a screen asking you if you want to use Visual Studio solution builder or ReSharper's Solution Builder. You need to click MSBuild for the latter:

 

image

 

You can also enable this via the ReSharper options:

 

Choose Internals under Options:

image

 

Set options as below:

image

 

 

This works for Jetbrains and it works for me, but you use it at your own risk. It might not give you the desired results, but then again, that's why it's not released.

Have fun!

If you’re going to provide RAD for ASP.NET MVC, change your thinking hat

 

ASP.NET MVC is not new. Ignoring the pattern for a moment, the way things work dates back to the days of CGI’s and ISAPI’s, where you had to role out pretty much everything by hand. You would get your data, format it and send it back to the browser, producing HTML. It wasn’t easy, but you did have one advantage. You had full control.

Gradually, tools starting to emerge to bring some sort of “RADness” to this kind of development. I in particular, used a technology called WebBroker from Delphi; we had Actions, PageProducers (replaced tags at runtime in an HTML template) and our data. Same concept as ASP.NET MVC, same concept as MonoRail, and other frameworks. Despite still having to do a lot of things manually, it did prevent us from having to write repetitive and tedious code in many cases.

Up to then, you had one requisite to develop web applications: you had to understand the web and the technology behind it.

Traditional ASP.NET or ASP.NET WebForms came around, among other things, to solve this problem: allow the non-web developer to leverage their existing knowledge to port their applications to the web. This meant not having to know much about web technology and at the same time. ASP.NET WebForms provided a powerful approach to web development: the concept of drag-n-drop that existed in WinForm applications. You could now take a control, drag it across to a form, set some properties and away you go: in minutes you had a web interface without having to even know what HTML meant.

Now, I’m no fan of ASP.NET WebForms. Actually that’s not entirely true. I hate it, but I still admit that for some it has it’s attractiveness and has solved problems for many people and put food on the table for many developers. So it has it’s place and will continue to live on.

I’m also not alone. There are others like me that don’t like ASP.NET WebForms. As such, when ASP.NET MVC came out, it gave us another technology, based on the ASP.NET stack, to  develop web applications.  Ignoring many of the differences and advantages it has over traditional ASP.NET, above all, it gave us control. As I always say, it put the web back into web development.

As developers started to embrace this technology, questions started to arise about what kind of support there would be in terms of controls. Naturally, third party component vendors, those same ones that were providing support for traditional ASP.NET components, were being asked about this too. All those that I spoke to pretty much said the same thing, let’s wait and see. And it’s completely the right approach. There’s no point in investing a large amount of time and resources into supporting a new framework if you don’t know what the success of the framework will be, both in adoption, as well as commitment from the company behind it, in this case Microsoft.

Now that ASP.NET MVC has been released, and there is a growing number of developers moving over from traditional ASP.NET, some companies are starting to develop a limited number of controls for ASP.NET MVC. I’m guessing that some of these companies are dipping their feet into the MVC waters to see what kind of success their components might have, before taking the big plunge.

I’ve examined a few of these components. I’m not going to mention any names or give an examples, but suffice to say, that up to now, I don’t like what I see. And the reason is simple. Most of them are taking the wrong approach. They are thinking with their WebForms hat on. However, since there is no visual designer, they are using an immense amount of markup with custom tags to define their components. And many are mixing data, behavior and appearance in these markups. The problem with this approach is that it’s going down the same route that many ASP.NET MVC developers left behind from by moving away from traditional WebForms: rich-intelligent-know-it-all controls. I’m not going to show any code since I don’t want to single-out any specific control/company, but sample applications for many of these exist and you’re free to examine them for yourself.

To summarize, trying to bring the same RAD controls that exist in WebForms over to ASP.NET MVC might not necessarily be correct thing to do. This is a different way to doing web development, a different mentality. And in my humble opinion, I think that this might backfire, since MVC developers mostly will not be too keen on this type of solution, the adoption rate for the components will be low and the component vendors behind them will throw in the towel.

26 Comments Filed Under [ ASP.NET MVC ]
Second Part of ASP.NET MVC Alt.NET Hispano Talk available

 

The guys from Alt.NET Hispano have put up the second part of my talk on MVC. You can view the video and download the code from here

Add Comment Filed Under [ ASP.NET MVC Speaking ]
Second part of ASP.NET MVC on VAN Hispano: Same time, Same Place

I'll be doing the second part of the ASP.NET MVC talk on VAN Hispano (Virtual Alt.NET) on Saturday 8th of May, at 20:00 CET (Central European Time). The URL for the meeting is http://snipr.com/virtualaltnet. This weeks pre-requisites is Spanish + knowledge of ASP.NET MVC.

Add Comment Filed Under [ ASP.NET MVC Speaking ]
ASP.NET MVC "Models": The lonesome folder!

ASP.NET MVC comes with a Models folder but no Model. Although some see this as a shortcoming, I'm actually delighted that the framework does not bind me to a specific data technology or pattern. If I want to use Active Record I can use Castle's ActiveRecord. If I want to use a Repository Pattern, I can use NHibernate. If I want to throw something together for a quick prototype, I can use Linq 2 Sql. The advantage of not being tied to a specific data access pattern for me is a win situation.

In many a demo, it's been indicated that the  "Models" folder contains your model, whatever that happens to be. It could be your Domain Model, your L2S entities, etc.  Now there are obvious reasons that whatever model you have, you wouldn't include it into your ASP.NET MVC application directly. You would probably reference it as an external assembly, and not directly place it in the Models folder.

 

image

 

So this begs the question. Do we just remove the Models folder? Well before I answer that, let me dig into something else.

 

Binding in ASP.NET MVC

We've seen many demos and tutorials where our model is directly passed in into our actions. We would have something along the lines of:

 

image

 

ASP.NET MVC's binding is pretty powerful. It can reflect on the properties of your class (even if they contain complex types) and match these up to the properties that come through over the wire, via the request POST. As long as you name the properties the same, it works like a charm. One issue that this introduces, as outlined by Justine in his post, as well as many others, is that the binding can come back to bite you. If you Customer entity has a field that you don't want the user to be able to update, you'll need to explicitly specify this by using attributes:

 

image

 

However, as simple as it might seem, it's error prone and violates DRY. Alternatives to this approach include creating custom model binders or using interfaces to specify the properties that you want to be databound. But let's hold that thought for a moment.

 

A typical update scenario for a typical entity

The following screen has a sample form to fill in the details for a customer

image

It's pretty standard. A bunch of fields and some dropdowns. But how is the dropdown values set? You could set them in the controller action just before displaying the view, using ViewData:

 

image

 

Now I don't know about you, but for me, using ViewData is a smell. If we don't use ViewData to pass information about our model, why should we be using it to pass information that our model indirectly consumes? And of course, being a dictionary that it is, it's prone to errors.

 

One plus one makes habitants for Models folder

We have two problems to solve:

  • Binding to only those properties that we need
  • Passing additional information to our views in a strongly-typed manner

Well this just cries out for a new class to encapsulate this information, i.e. a view model. Instead of binding directly to entities, you can bind to a new class that exposes only the information that is allowed to be updated. You can also use this class to provide other information required for a particular view. In the case of Customer, we could end up with something along the lines of:

 

image

 

In this case, we are using CustomerData as a DTO to hold the customer data (Name, Email, etc.) and the CustomerCreateViewModel as the View Model to hold other pertinent information for that particular view, for instance a list of countries. The action would now pass in this model as opposed to Customer:

 

image

 

We now have a strongly-typed model to represent all the information we need for a particular view, and since it pertains to the current MVC application and specific Views, what better place to hold this than the Models folder.  Obviously based on your needs, you could provide a flattened version of this ViewModel but it does provide a cleaner approach to separate the actual DTO of your entity from the surrounding auxiliary requirements for a view.

Note: you need to make sure that you always provide a default parameter-less constructor for your view models since the framework requires this on binding.

 

Summary

By using strongly-typed views, you get the best of all worlds. You are able to make use of the binding provided by the MVC framework and it also provides a clean approach to providing specific data for views. And if that still doesn't cut it for you, think that you're making a home out of your Models folder!

Virtual Alt.Net Hispano ASP.NET MVC Meeting

I've uploaded the presentation and demos for the VAN Alt.Net Hispano last night. I'd like to thank Jorge and Fabián for organizing the event. And to Zachariah Young for access to the Live Meeting account. I thoroughly enjoyed it and it was great to see so much participation from everyone, despite going on for over 2'30 hours.

You can download the material from here, and from what I'm told it will be available on the Alt.Net Hispano web site also.

You can download the video from here

23 Comments Filed Under [ ASP.NET MVC Speaking ]
Saving keystrokes with LiveTemplates

One of the cool features Resharper has is to allow you to define live code templates, i.e. snippets that you can interact with. Say for example you continuously type:

 

   1: var customerServices = new Mock<ICustomerServices>();

 

each time you want to mock out a service. You could shorten this to only typing:

 

mock<TAB>customerServices<TAB><ENTER>

and here's how:

1. Resharper -> Live Templates

2. Under User Templates, create a new one

3. Type in: var $name$ = var Mock<I$interface$>();

image

4. Give it the ShortCut name of "mock" (or whatever you please)

5. On the right-side of the Window, click on the Choose Macro on the name entry

image

6. Pick Constant Value and close the dialog

image

7. Click on the Constant Value again on the right-hand side

image

8. Enter a value, for example mockObject

image

9. Repeat the same process (Choose Macro) for the interface entry, but this type choose the following option:

image

10. Set the variable by clicking on another variable link:

image

11. Choose the variable name

image

12. Close the editor and you're done. Now watch how it works

 

Obviously this is just a simple example, but you can see how powerful Live Templates can be.

And since it's 2:15...I'm heading to bed.

Add Comment Filed Under [ Tools Productivity ]
Strict use of strict mocks

Having a chat with a colleague the other, brought up the issue of strict mocks. I commented that strict mocks should be used sparingly and only in certain circumstance, and this led to a series of discussions on why that is.

Strict and loose Mocks

Usually mocking frameworks provide two types of mocks: strict and loose. If you're using RhinoMocks, these are called StrictMock and DynamicMock. If you're using Moq, you set the behaviour (Loose = Dynamic = Default or Strict) in the mock creation.

RhinoMocks

RhinoMock has a static mock repository that you can use to create mocks, called MockRepository. This saves you on having to explicitly create a mock repository. Thus, instead of doing:

 

   1: MockRepository mocks = new MockRepository();
   2:  
   3: IDependency dependency = mocks.DynamicMock<IDependency>();

you could write this:

 

   1: IDependency dependency = MockRepository.GenerateMock<IDependency>();

Using the static repository, you cannot pick between dynamic and strict mocks. All mocks are dynamic. This somehow promotes the usage of dynamic mocks over strict ones.

 

Moq

With Moq, as with RhinoMocks, the default behaviour is of loose mocks. Thus, writing:

 

   1: var dependency = new Mock<IDependency>();

is equivalent to:

 

   1: var dependency = new Mock<IDependency>(MockBehavior.Loose);

which in turn is the same as:

 

   1: var dependency = new Mock<IDependency>(MockBehavior.Default);

If you want to use strict mocks:

 

   1: var dependency = new Mock<IDependency>(MockBehavior.Strict);

(Note that with Moq, to access the actual Mocked object, you need to access the .Object property. RhinoMocks doesn't require this because it uses extension methods).

 

Using Strict Mocks

So, now that we know how to create the two different types of mocks depending on the framework, let's take a look at a SUT and see where the problem with strict mocks lie. To make the post shorter, I'll use RhinoMocks, but you can accomplish the same with Moq.

Suppose we have the following class:

   1: public class ServiceClass 
   2:    {
   3:        private readonly IDependency _dependency;
   4:  
   5:        public ServiceClass(IDependency dependency)
   6:        {
   7:            _dependency = dependency;
   8:        }
   9:  
  10:        public void FirstMethod()
  11:        {
  12:            _dependency.FirstMethod();
  13:            Console.WriteLine("Called ServiceClass.FirstMethod");
  14:        }
  15:  
  16:        public void SecondMethod()
  17:        {
  18:            _dependency.SecondMethod();
  19:            Console.WriteLine("Called ServiceClass.SecondMethod");
  20:        }
  21:    }

 

and we want to test that when calling ServiceClass.FirstMethod, the corresponding call Dependency.FirstMethod is called, we could be tempted to do something like the following:

   1:        [Fact]
   2:        public void ServiceClass_FirstMethod_calls_dependency_FirstMethod_Strict()
   3:        {
   4:            MockRepository mocks = new MockRepository();
   5:  
   6:            IDependency dependency = mocks.StrictMock<IDependency>();
   7:            
   8:            using (mocks.Record())
   9:            {
  10:                dependency.Expect(m => m.FirstMethod()); 
  11:            }
  12:  
  13:            using (mocks.Playback())
  14:            {
  15:                ServiceClass serviceClass = new ServiceClass(dependency);
  16:  
  17:                serviceClass.FirstMethod();
  18:            }
  19:  
  20:            // Note that in the Record/Replay, VerifyAll is implicitly called
  21:        }

 

We've verified that Dependency.FirstMethod is called, everything passes, all is fine.

 

Welcome to BrittleVille

Two days later we get a change of request, that requires us to adjust the code for ServiceClass.FirstMethod. In particular, we need to call Dependency.ThirdMethod:

   1: public void FirstMethod()
   2: {
   3:     _dependency.FirstMethod();
   4:     _dependency.ThirdMethod();
   5:     Console.WriteLine("Called ServiceClass.FirstMethod");
   6: }

We check in the changes, run our tests, and boom! Test failed:

 

XunitException: Rhino.Mocks.Exceptions.ExpectationViolationException : IDependency.ThirdMethod(); Expected #0, Actual #1.

With strict mocks EVERY single call to the mocked object has to have expectations set on it. If we make an additional call and we don't set the expectation, our test will fail. Our test was to verify the FirstMethod was being called, and it still is. Our test failed because we wrote it using strict mocks, it failed for the wrong reason, and made our code very brittle.

However, if we were to have written the test using Dynamic mocks, this wouldn't happen:

   1: [Fact]
   2: public void ServiceClass_FirstMethod_calls_dependency_FirstMethod_Dynamic()
   3: {
   4:     MockRepository mocks = new MockRepository();
   5:  
   6:     IDependency dependency = mocks.DynamicMock<IDependency>();
   7:     
   8:     using (mocks.Record())
   9:     {
  10:         dependency.Expect(m => m.FirstMethod()); 
  11:     }
  12:  
  13:     using (mocks.Playback())
  14:     {
  15:         ServiceClass serviceClass = new ServiceClass(dependency);
  16:  
  17:         serviceClass.FirstMethod();
  18:     }
  19:  
  20:     // Note that in the Record/Replay, VerifyAll is implicitly called
  21: }

 

Note that out test is still valid. If we remove the call to Dependency.FirstMethod the test will fail as it should. However, it won't fail if we add additional calls.

An added bonus to using loose mocks with RhinoMocks, is that you can use the AAA (Arrange-Act-Assert) syntax and also call individual expectations. Thus the previous code could be written like so:

   1: [Fact]
   2: public void ServiceClass_FirstMethod_calls_dependency_FirstMethod_AAA() {
   3:  
   4:     // Arrange
   5:     IDependency dependency = MockRepository.GenerateMock<IDependency>();
   6:  
   7:     dependency.Expect(m => m.FirstMethod());
   8:  
   9:  
  10:     // Act
  11:      ServiceClass serviceClass = new ServiceClass(dependency);
  12:  
  13:     serviceClass.FirstMethod();
  14:  
  15:     // Assert
  16:     dependency.VerifyAllExpectations();
  17:     
  18: }

 

Alternatively, if you don't need expectations to return values, you can just call AssertWasCalled on them:

 

   1: [Fact]
   2: public void ServiceClass_FirstMethod_calls_dependency_FirstMethod_AAA() {
   3:  
   4:     // Arrange
   5:     IDependency dependency = MockRepository.GenerateMock<IDependency>();
   6:  
   7:     // Act
   8:      ServiceClass serviceClass = new ServiceClass(dependency);
   9:  
  10:     serviceClass.FirstMethod();
  11:  
  12:     // Assert
  13:     dependency.AssertWasCalled( m => m.FirstMethod());
  14:     
  15: }

 

Summary

Mocks are a great thing to test behaviour between different components. However, make sure you use them correctly if you don't want to end up with brittle code that any minor change breaks a whole bunch of tests. Strict and ordered mocking should only be used in exceptional cases.

17 Comments Filed Under [ Unit Tests ]
ASP.NET MVC is now Open Source. Will it effect you?

During sessions/workshops on MVC, I would say that 90%-95% of the attendees (yes I do "poll" the crowd, so it's based on facts), walk out liking MVC and realizing it's potential. However, there is one frequent question that I'm asked:

How do we know if Microsoft is going to continue to support ASP.NET MVC?

Personally I think that they will continue to support it, but I can't read the future (If I could, trust me, I wouldn't be blogging about it). However, yesterday's announcement changes things. Even, for the sake of argument, if Microsoft decide to discontinue MVC, who cares. They've made it Open Source. So tomorrow, any company (including your own) could pick it up and continue to support it. This should add extra guarantee for those in doubt of whether to invest or not into ASP.NET MVC.

On the other hand, if you're the kind of developer/shop that doesn't buy into Open Source, move right along, nothing to see here, business as usual. Or wait, maybe it's about time you realize that Open Source is not such a bad thing after all...

Congratulations Microsoft, Phil Haack & Co. Good move!

Add Comment Filed Under [ ASP.NET MVC ]