I’m a few weeks into a side project that I blogged about in a previous post. I’m having a lot of fun (I’m such a geek) using a bunch of new stuff. Since Visual Studio 11 is at the center of all the work on the project, I thought I’d share my first impressions on it. Of course, I’m using a Beta version of it. Really this post is about my second thoughts since they are much more meaningful. Spoiler alert: First impressions aren’t always the most important.

My first thoughts

My first thoughts were pretty typical and can be summarized with one bullet:

  • Colorless

That is pretty much what most people think when they see it for the first time. People tend to ignore all of the improvements and new features and focus on the lack of color. At first I found this lack of color to be somewhat distracting which is odd because it is meant to have the opposite effect. I’ll be honest, I wasn’t thrilled with the new look but I was quick to point out to some of my peers that we should give it some time and get used to it.

My Second Thoughts

Guess what? I got used to it… quickly. After using Visual Studio 11 for a couple of hours, I quickly got used to the lack of color. It isn’t really that big a deal and I think the VS team was on the right track by moving Visual Studio overall to the background and making the code editor the focal point. Having said that, I still think some color would be helpful. My last point on the overall lack of color is that it isn’t 100% consistent. Some windows within VS11 still have color. And some plugins use color too. That makes things a bit odd. I’m including a screenshot below. That’s all for the color.

image

Some features to note (this is by no means a comprehensive list, just some highlights):

So far, I think VS11 is an awesome development environment. I’ve been doing MVC development within VS11 and the HTML, CSS, and JavaScript support is really nice. VS11 is now providing a lot of help for developers working in these areas. I’ll also point out that I am using ReSharper (v7 EAP for VS11). I love ReSharper! Between VS11 and ReSharper, the web development experience is awesome. I’ll be honest, I don’t always know which tool is providing the various features!

When developing web apps, we typically want to run/debug/test them in a variety of browsers. It seems like Microsoft has figured out the IE is not the only browser in town. So now we can use the Debug Target toolbar button. Just click the typical “play” button or hit F5 to debug in which ever browser is selected: image Or you can use the drop down to chose a different target or change the default:

image

I like the fact that the great features of the Solution Navigator (previously part of the Productivity Power Tools) were combined into the Solution Explorer. Of course, the Add Reference dialog is a huge improvement from the past, that was also a feature from the Power Tools.

I’m also a huge fan in the reduction of items in the toolbars. I think the VS team really nailed that part of the design as well. They took out all but the most commonly used buttons from the toolbar – but only in the default configuration. If there is a button or toolbar you like, just add it back in. That part is easy! More importantly, we should all get used to the Quick Launch feature. With that, we can just type the name of any command we want. No more hunting around in the menus for seldom used actions!

Another great feature is the Preview Tab. I’m surprised more people aren’t talking about this one. This is pretty cool but I don’t think you can get the full value of it until you experience it yourself. Think about all those times you are debugging and you end up stepping into file after file after file. All those files get opened up in the tab well. Eventually you get to the file you want in the debug process. But when you are done you have a ton of open files. Not everyone is like me, but I hate open files. I want my tab well to be as empty as possible. Preview Tab to the rescue! With VS11, all of those files that you step through don’t open up as normal files, they open in the Preview Tab. But Preview Tab only has one file at a time. So each new file you step into replaces the old one and your environment stays clutter free. And Preview Tab is pretty smart too. If you make a change to the file it moves it into the normal tab well. You can also click a button in the tab to “promote” the file to be a normally opened file. In this image you can see the Preview Tab on the right, circled in blue.

image


While it isn’t really new, I want to mention that the extensibility features of VS11 (and 2010 too) are really powerful and work so well and somewhat seamlessly. The Extension Manager is really cool and with it I’m always adding tools to Visual Studio. There are loads of great things to install. With VS2010 I hadn’t gotten to experience Nuget but with the work I’m doing now in VS11 I am all over it. Nuget (or is it NuGet, or nuget?) is providing all kinds of good stuff for my solution. Between VS11, the extensions and nuget packages, I really feel empowered to create great solutions.

There are lots of other great features, these are just the ones that came to mind as I was writing. Download the Beta and check it out for yourself!

A lot of new stuff has been coming out from Microsoft lately. Couple that with all the cool open source projects available for use and a developer can quickly get left behind from all the new technology. I try to stay pretty current but there is some new stuff that I’ve been wanting to use. I also wanted to brush up on some old skills and even use some of the technologies I am experienced with in new ways. I decided it was time to start a little project for myself. I’m often asked by developers about how they can gain experience with new technology (or even old tech that is new to them). My advice is that they should just write an application that uses the technology. As a hiring manager, I’ll give serious consideration to that kind of experience, provided it isn’t “hello world”. When I write an application like this, I treat it like a real world production project. And if you are creating a web application you can have it hosted and then it IS a real product. That should count as experience to a smart hiring manager. So when you write these applications, try to follow all of the best practices, use good standards, etc.

In my case, I am writing an application that I hope will actually get some use. I’m hoping to get some great blogging material out of this as well. I already have, but now I need to find time to write about it. Anyway, figure out what you want to build and then create a list of the things you want to learn. As you write the application, you can just keep adding other technologies, frameworks or patterns in along the way.

Here is my list of things I’m using or will be using in my new pet project. Obviously the beta stuff is brand new. And I’ve already got experience with MVC 2 (pre-Razor), jQuery, HTML, CSS, etc. However, this stuff gets better and better all the time and I like to stay on top of it. Working a few hours here and there for the past 2 weeks, I’ve already included all of the items in blue in my project.

  • Visual Studio 11 (beta)
  • Entity Framework 5 (beta)
  • Entity Framework Code First
  • Entity Framework Migrations
  • ASP.Net MVC 4
  • Razor
  • HTML 5
  • jQuery
  • jQuery UI
  • Git
  • Open Authentication
  • CSS3 & Media Queries
  • HTML/CSS Grid Systems
  • NuGet
  • SEO Toolkit (Microsoft)
  • C# 4.5 (including Async)
  • SignalR
  • Azure
  • ASP.Net Web API
  • BootStrap (from Twitter)
  • Facebook Integration
  • Of course, Dependency Injection, Unit Testing, and all of the other stuff I put into any app I am deploying.

I’m writing this as a web application and creating a mobile version at the same time. In addition, I plan to extend this to additional platforms. So my list continues:

  • Mobile Web
  • WP7
  • Metro (Windows 8)

jQuery rocks.  It makes it really easy to do cool stuff client side with JavaScript, like these cascading DropDowns (aka Select Lists).  But at the end of the day, jQuery is JavaScript, and it can still be tricky to work with.  One of these days, Visual Studio will treat JavaScript like a first class language and life will be much easier.  You’ll see that there isn’t much JavaScript here, but it took me several iterations to get this right.

I’ll start with the UI code and JavaScript.  If you want, you can read further and see the Controller code and more.

In my View, I have two DropDowns (Select Lists) and some JavaScript:

<p>
    Country:
    <%= Html.DropDownList("Countries", ViewData["Countries"] 
             as List<SelectListItem>) %>
</p>
<p>
    Region:
    <%= Html.DropDownList("Regions", new List<SelectListItem>()) %>
</p>

<script src="../../Scripts/jquery-1.3.2.js"></script>

<script type="text/javascript">
    $(function() {
        var countries = $("#Countries");
        var regions = $("#Regions");
        countries.change(function() {
            regions.find('option').remove();
            $.getJSON('/Home/Regions', { countryId: countries.val() }, function(data) {
                $(data).each(function() {
                    $("<option value=" + this.RegionId + ">" + this.RegionName + "</option>").appendTo(regions);
                });
            });
        });
    });
</script>

The Countries DropDown is pre-populated with data passed in ViewData. 

The second DropDown, Regions gets loaded when Countries changes.

Here’s how the JavaScript and jQuery stuff works…

First I get the two Select Lists, using jQuery and the ID as the selector (jQuery makes it easy!):

        var countries = $("#Countries");
        var regions = $("#Regions");

Next I wire up the change event on the Countries list to an anonymous function (jQuery makes it easy!):

        countries.change(function() {
        // ...
            });

Inside that function I do a few things.  First, find all options in the Region Select List and remove them:

            regions.find('option').remove();

Next I need to get the data for the second Select List. Guess what?  jQuery makes this easy too.  Using the getJSON() method, I supply the Controller and Action, as well as the Id of the country so I can get the correct regions.  I also declare a function to call when the JSON result comes back:

        $.getJSON('/Home/Regions', { countryId: countries.val() }, function(data) {
        // ...
        });

The last thing to do is load all of the results into the Select List.  This actually was the hardest thing to do but in the end it is very little code.  I tried using jQuery to create options and adding them to the select list.  I tried creating a list of options and setting the html value of the Select list.  I tried a bunch of stuff.  But this worked great… Iterate over the results with jQuery’s .each function and call a function for each iteration.  The function creates some dynamic html and appends it to the Region list.  I must admit, I was surprised this worked.  I’d assume that appending would put it after the select list (<select id=”Regions” />) but it actually put it inside it!

        $(data).each(function() {
            $("<option value=" + this.RegionId + ">" + this.RegionName + "</option>").appendTo(regions);
        });

That’s it!  It works great.  Of course there are more complex ways to do this, with caching etc.  This is just one way to accomplish the goal.

Here’s some code from the Controller that helps make it work.  Just remember, this is demo code.  I’m not too worried about separation of concerns and similar details. In a production app, I’d be calling more services!

In the Index Action (in this sample the Select Lists are in my Index View) I load the countries list into ViewData.  Again, this is a demo and that may not be the best practice.

    public ActionResult Index()
    {
        ViewData["Countries"] = GetCountries();
        return View();
    }

    private List<SelectListItem> GetCountries()
    {
        List<SelectListItem> countries =
            _countryList.Select(c => new SelectListItem {Text = c.CountryName, Value = c.CountryId.ToString()}).ToList();
        countries.Insert(0, new SelectListItem{ Text="", Value = "0"});
        return countries;
    }

Then I have a Regions Action that returns the JSON result with the values to add to my Regions Select List:

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Regions(int countryId)
    {
        return Json(_regionList.Where(r => r.CountryId == countryId).Select(r =>
                                                                            new
                                                                                {
                                                                                    r.RegionName,
                                                                                    r.RegionId
                                                                                }));
    }

 

That covers most of it.  Happy coding.

Technorati Tags: , ,

When using strongly typed views, don’t name the controller action arguments with the same name as another form value!


I’ve been working with ASP.NET MVC for a couple of months now.  It is really pretty awesome.  It’s worked so well, I haven’t had much to blog about!  The other day I ran into an issue so I’m sharing the solution.   MVC will “automagically” bind the parameters of a controller action based on the values in the form.  And if your View is strongly typed and your controller action has a parameter of that same type, it will bind it too.  But in my case, the parameter was null.  MVC wasn’t loading it. And there was no exception to help me out.


Here’s a simple demo, I’m not showing every line of code…


 


Typical for an MVC application, I have a view that is strongly typed:

<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master”
Inherits=”System.Web.Mvc.ViewPage<OrganizationRole>” %>

 


The View has a simple form which includes two text boxes:

<p>
<label for=”OrganizationName”>OrganizationName:</label>
<%= Html.TextBox(“OrganizationName”) %>
<%= Html.ValidationMessage(“OrganizationName”, “*”) %>
</
p>
<
p>
<label for=”Role”>Role:</label>
<%= Html.TextBox(“Role”) %>
<%= Html.ValidationMessage(“Role”, “*”) %>
</
p>

 


A button on the form posts back to the controller, calling the Create Action.  Here is Action Code:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(OrganizationRole role)
{
// Do Something Here…
return View();
}

In the screenshot below, you can see that when I debug the app, the role parameter has not been loaded.


image


The fix was simple but it took a while to figure it out!  All I had to do was re-name the parameter from “role” to “organizationRole”:


[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(OrganizationRole organizationRole)
{
    // Do Something Here…
    return View();
}


You see, I was being lazy and abbreviated the argument’s name.  That is ok, you can name the parameter almost anything you want.  But I gave the parameter the same name as one of the other form variables!  Notice above that my form has a text box named “Role”!  MVC tried to load the values of my parameters – it takes each of the posted values from the form (“OrganizationName” and “Role”) and tries to match them up with arguments with the same names (it is not case sensitive) if they exist.  It also tries to load the entire form value (strongly typed as the class OrganizationRole) to the argument of type OrganizationRole, if one exists.  But an argument of type OrganizationRole with the name “Role” screws the who thing up!  The only problem is that it doesn’t throw any exceptions.  Anyway, I changed the name and presto, it works.