Steve Michelotti

A .NET Developer's Toolbox

  Home  |   Contact  |   Syndication    |   Login
  115 Posts | 1 Stories | 458 Comments | 51 Trackbacks

News

View Steve Michelotti's profile on LinkedIn






Google My Blog

What I'm Reading:

Shelfari: Book reviews on your book blog

Tag Cloud


Archives

Post Categories

Image Galleries

Blogs

Code

Publications

Friday, February 05, 2010 #

One of the cool new features of MVC 2 is the ability to automatically pick an editor template based on the meta data of each property. This meta data can be as simple as the data type of the property itself.  Take an example where we have a Contact object that has a DateTime? property for DateOfBirth.

   1:  public partial class Contact
   2:  {
   3:      [DisplayName("First Name")]
   4:      public string FirstName { get; set; }
   5:   
   6:      [DisplayName("Last Name")]
   7:      public string LastName { get; set; }
   8:   
   9:      [DisplayName("Date of Birth")]
  10:      public DateTime? DateOfBirth { get; set; }
  11:  }

We can then display the property using markup like this:

   1:  <%=Html.LabelFor(m => m.Contact.DateOfBirth) %>
   2:  <%=Html.EditorFor(m => m.Contact.DateOfBirth)%>

This results in a view that looks something like this:

This is ugly.  It’s not user friendly for the user to have to type this and in many cases (like date of birth) we don’t care about the time portion – only the date.  With MVC 2 we can now, by convention, change the display for all of our DateTime data types just by adding a partial view called “DateTime.ascx” to a well-known folder called “EditorTemplates”:

Notice the EditorTemplates folder is in the Shared folder of views but you could scope this to a specific view folder as well. Now I can add my own partial view for DateTime. In fact, this will work for a nullable DateTime as well:

   1:  <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
   2:  <%=Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" }) %>

The aspect that I *really* like about this functionality is the rendered HTML:

   1:  <input class="datePicker" id="Contact_DateOfBirth" name="Contact.DateOfBirth" type="text" value="4/1/1975" />

Notice how that “id” and “name” attributes were still correctly set despite that fact this this was in a partial view where we were just referring to the “Value” property of a nullable DateTime. This would have been tricky to do just using partial views with MVC 1 but here the framework is taking care of this for me. This means that the model binders will “just work” when the form is posted.

Another thing to note is that I’ve added a class attribute of “datePicker” because I’m using the jQuery datepicker to give a nice little calendar UI for the end user.

   1:  <script src="../../Scripts/jquery-datepicker.js" type="text/javascript"></script>
   2:  <script type="text/javascript">
   3:      $(function() {
   4:          $(".datePicker").datepicker({ showOn: 'both', buttonImage: "/images/calendar.gif" });
   5:      });
   6:  </script>

This gives a much nicer user experience:

MVC 2 editors result in a much nicer development experience. My call to the EditorFor() HTML helper method remains unchanged. But rather than just rendering a simple HTML text box with no formatting of the DateTime, it will now automatically pick up my DateTime editor template for ALL my DateTime properties and show a nice UI with better formatting.  Also note that if you have a date time that is an exception to this and you want to display a different editor, you can still use the [UIHint] attribute to control the meta data and therefore select a different editor for a DateTime.


Friday, January 22, 2010 #

On February 4th, I will be presenting .NET 4.0 and Visual Studio 2010 at the Microsoft office in Reston as part of my company’s continued efforts to provide education on Microsoft technologies. This presentation will cover a wide breadth of technologies that are being launched by Microsoft this year. The presentation is geared towards technical decision makers including Architects, CTO, CIO, Project Managers, IT Managers, and senior development resources. This a totally free Microsoft sponsored event that is intended to provide a solid foundation on the vast landscape of technologies being released and how best they can be leveraged in your organization.  The topics will include:

  • .NET Framework 4 enhancements
  • Visual Studio 2010
  • Parallel Extensions
  • C# 4.0 & VB10 language enhancements
  • ASP.NET 4
  • Microsoft AJAX Library
  • MVC 2
  • Entity Framework 4
  • WCF Data Services
  • WCF 4 & REST
  • Workflow Foundation 4
  • AppFabric
  • AppFabric Caching
  • Silverlight

This event is free and you can register here. Hope to see you there.


Sunday, January 17, 2010 #

MVC 2 is adding many new features that make views more elegant to write. For example, the new EditorFor() Html helper returns the appropriate HTML input elements for a given property so you don’t have to explicitly specify text box, dropdown, or whatever control you need and can even use the [UIHint] attribute to specify the editor you want to use (either an OOTB or custom editor). This results in view markup that often looks like this:

   1:  <p>
   2:      <%=Html.LabelFor(m => m.FirstName)%>
   3:      <%=Html.EditorFor(m => m.FirstName)%>
   4:      <%=Html.ValidationMessageFor(m => m.FirstName)%>
   5:  </p>
   6:  <p>
   7:      <%=Html.LabelFor(m => m.LastName)%>
   8:      <%=Html.EditorFor(m => m.LastName)%>
   9:      <%=Html.ValidationMessageFor(m => m.LastName)%>
  10:  </p>

This allows us to simply use attributes to specify meta-data on our view models like this:

   1:  public class Person
   2:  {
   3:      [DisplayName("First Name")]
   4:      [Required(ErrorMessage = "First Name is required.")]
   5:      [StringLength(50, ErrorMessage = "Last name must be less than 50 characters.")]
   6:      public string FirstName { get; set; }
   7:   
   8:      [DisplayName("Last Name")]
   9:      [Required(ErrorMessage = "Last Name is required.")]
  10:      [StringLength(50, ErrorMessage = "Last name must be less than 50 characters.")]
  11:      public string LastName { get; set; }
  12:  }

For example, the [DisplayName] attribute used on line #3 and line #8 above will be honored by the LabelFor() html helper method. This new functionality of MVC 2 has been blogged about quite a bit to date and provides great improvements over MVC 1. In summary these improvements are:

  • Display Names with LabelFor() – Ability to specify display name on our view models meta data and not have to worry about specifying it in the views.
  • HTML input with EditorFor() - Ability to simply use EditorFor() in the view and allow MVC to pick the appropriate editor either automatically or by honoring the [UIHint] attribute as part of meta data in our view models.
  • Validation with ValidationFor() - Ability for the validation to honor DataAnnotations attributes and have this all “baked in” including the actual validation execution itself (including client-side valdiation).

While this is not an exhaustive list for the improvements in MVC 2, the common theme in all this is that, in the most typical cases, each view model property has 3 components: 1) the label, 2) the editor, and 3) validation.  Looking at the first code sample above, I’m calling the same three HTML helper methods for every view model property (i.e., LabelFor(), EditorFor(), and ValidationMessageFor()). The only thing different between them is the view model property being used for the lambda expressions.  For a single property, the same lambda expression is being used for all three HTML helpers. This doesn’t make our views very DRY. If we were doing this sort of thing in C#, we’d create a method to encapsulate the repetition and there’s no reason we shouldn’t do same thing for the code in our views. Therefore, we can create a simple HTML helper that encapsulates these like this:

   1:  public static MvcHtmlString ValidatedEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
   2:  {
   3:      var html =
   4:          htmlHelper.LabelFor(expression).ToString() +
   5:          htmlHelper.EditorFor(expression).ToString() +
   6:          htmlHelper.ValidationMessageFor(expression).ToString();
   7:   
   8:      return MvcHtmlString.Create(html);
   9:  }

This allows us to now change our original view code to this while still maintaining the same HTML markup that is generated:

   1:  <p>
   2:      <%=Html.ValidatedEditorFor(m => m.FirstName)%>
   3:  </p>
   4:  <p>
   5:      <%=Html.ValidatedEditorFor(m => m.LastName)%>
   6:  </p>

Also, if you’re using MVC 2 with ASP.NET 4 instead of ASP.NET 3.5, you can take advantage of the new <%: %> syntax rather than the old <%= %> syntax.

   1:  <p>
   2:      <%:Html.ValidatedEditorFor(m => m.FirstName)%>
   3:  </p>
   4:  <p>
   5:      <%:Html.ValidatedEditorFor(m => m.LastName)%>
   6:  </p>

Now the views are *extremely* simple and with a single HTML helper we’ll automatically get a label, an editor, and validation. Also notice that the HTML helper is using MvcHtmlString rather than just a string as all HTML helpers in MVC 2 are now HTML encoded by default.

The snippet above is only showing two view model properties but if your view has 10, 20, or even 100 or more properties, the difference becomes even more dramatic since the code is only one-third the size. Additionally, the trend you see is that more and more of your development paradigm is being moved away from the views and into your C# view models. This allows for dramatically cleaner/simpler views while also enabling the overall code base to be more testable and less error prone.


Friday, January 08, 2010 #

A while back I blogged about creating an MVC Delete Link with the AjaxHelper. This was based on another blog post from Stephen Walther where he explained the drawbacks of using hyperlinks for delete scenarios.  HTTP and REST best practices state that GET requests should never modify a resource. The most “RESTful” implementation is is use a DELETE verb. In Walther’s post he shows two primary examples: 1) using AJAX to issue a true “DELETE” request, and 2) using individual forms to do the delete operations. In my previous post on MVC DeleteLink, I essentially showed a variation of his first example (i.e., the AJAX method). In this post I’ll show a variation on his second example using MVC 2 and the new HttpMethodOverride (i.e., using individual forms for the delete).

An HTML form supports only GET and POST for the form action. It does not support PUT or DELETE verbs. Hence, the typical solution to this is the leverage the form POST to do delete operations as well (in effect, “overloading” the meaning of form POST). MVC 2 introduces a new HTML helper called HttpMethodOverride which allows your form POST to “act like” another verb. This is a common convention that is used by other frameworks (Ruby on Rails does something similar) – sometimes passing “X-HTTP-Method-Override” in an HTTP header and sometimes passing it in a hidden form variable like this. Therefore, if we want a simple delete link, we can now do it like this:

   1:  <%Html.BeginForm("Delete", "Contacts", new { id = workout.Id }); %>
   2:      <input type="image" src="/images/remove-icon.png" alt="Delete" />
   3:      <%=Html.HttpMethodOverride(HttpVerbs.Delete) %>
   4:  <%Html.EndForm(); %>

This will render HTML output like this:

   1:  <form action="/Contacts/Delete/1" method="post">
   2:      <input type="image" src="/images/remove-icon.png" alt="Delete" />
   3:      <input name="X-HTTP-Method-Override" type="hidden" value="DELETE" />
   4:  </form>

The best part about this is the the MVC action method attributes will respect this form variable:

   1:  [HttpDelete]
   2:  public ActionResult Delete(int id)
   3:  {
   4:      this.repository.Delete(id);
   5:      return this.RedirectToAction("Index");
   6:  }

Notice the [HttpDelete] attribute. This is also new in MVC 2 as a more succinct version of [AcceptVerbs(HttpVerbs.Delete)]. This is a much better and cleaner implementation than we had available in MVC 1.  However, needing a delete link is something that is going to be pretty common in your applications and creating a form, an input tag and the HttpMethodOverride() is a lot to go through every time you need it. As always, the best approach to keep things simpler (and more DRY) is to create your own re-usable HTML helper method that will allow you to call it like this:

   1:  <%=Html.DeleteLink("Delete", "Workouts", new { id = workout.Id }, "/images/remove-icon.png") %>

The complete code for that HTML helper method:

   1:  public static MvcHtmlString DeleteLink(this HtmlHelper helper, string actionName, string controllerName, object routeValues, string imageUrlPath)
   2:  {
   3:      var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
   4:      var url = urlHelper.Action(actionName, controllerName, routeValues);
   5:   
   6:      var formTag = new TagBuilder("form");
   7:      formTag.MergeAttribute("action", url);
   8:      formTag.MergeAttribute("method", "post");
   9:   
  10:      var inputTag = new TagBuilder("input");
  11:      inputTag.MergeAttribute("type", "image");
  12:      inputTag.MergeAttribute("src", imageUrlPath);
  13:      inputTag.MergeAttribute("alt", "Delete");
  14:   
  15:      formTag.InnerHtml = inputTag.ToString(TagRenderMode.SelfClosing) + helper.HttpMethodOverride(HttpVerbs.Delete);
  16:   
  17:      return MvcHtmlString.Create(formTag.ToString());
  18:  }

Also notice this is returning the new MvcHtmlString type rather than just a string.

So does this allows us to be more “RESTful”? Yes, it does. But we could still go further.  I really like the approach by Dylan Beattie here in which he introduces route constraints so the URL’s don’t need to contain segments like “/Delete” or “/Edit”. His approach could be further generalized for *all* controllers such that any POST request that came in with and X-HTTP-Method-Override of “DELETE” would automatically be routed to an action method named Delete(). This is a convention that makes a lot of sense and could also be further enforced with a layer supertype controller.


Tuesday, December 29, 2009 #

Recently I had an interesting task to consume a particular XML document and populate a C# object from it.  The structure of the XML document looked roughly like this:

   1:  <root xmlns="http://www.w3.org/2005/Atom">
   2:    <entry>
   3:      <id>1</id>
   4:      <title>abc</title>
   5:      <content>
   6:        <div xmlns="http://www.w3.org/1999/xhtml">
   7:          <table>
   8:            <tr>
   9:              <td>Item1</td>
  10:              <td>111</td>
  11:            </tr>
  12:            <tr>
  13:              <td>Item2</td>
  14:              <td>222</td>
  15:            </tr>
  16:            <tr>
  17:              <td>Item3</td>
  18:              <td>333</td>
  19:            </tr>
  20:          </table>
  21:        </div>
  22:      </content>
  23:    </entry>
  24:    <entry>
  25:      <id>2</id>
  26:      <title>xyz</title>
  27:      <content>
  28:        <div xmlns="http://www.w3.org/1999/xhtml">
  29:          <table>
  30:            <tr>
  31:              <td>Item1</td>
  32:              <td>444</td>
  33:            </tr>
  34:            <tr>
  35:              <td>Item2</td>
  36:              <td>555</td>
  37:            </tr>
  38:          </table>
  39:        </div>
  40:      </content>
  41:    </entry>
  42:  </root>

The C# object to be populated looked like this:

   1:  public class Entry
   2:  {
   3:      public int Id { get; set; }
   4:      public string Title { get; set; }
   5:      public string Item1 { get; set; }
   6:      public string Item2 { get; set; }
   7:      public string Item3 { get; set; }
   8:  }

My initial inclination was that LINQ to XML was the correct approach to do this. I had a few interesting challenges:

  1. The XML was hierarchical and needed to be flattened
  2. The XML had multiple namespaces
  3. Some of the elements were optional (e.g., Item3)
  4. Needed to access sibling elements (e.g., in the first <entry> element, the name “Item1” has a value of “111” on line 9-10 above)

If you’re already experienced with LINQ to XML, this might be a relatively straightforward query to write.  However, if you’re not a expert, it’s often the *approach* that you take that most determines you success.

The first thing I did was to write a unit test so that when I started to code, I could also do a quick red/green check to see if I was getting closer. Although writing a unit test first is typically my default mindset, I realized pretty quickly that I needed even more efficiency (i.e., instantaneous feedback) since I was really just working on a single query.  So my next step was to fire up LinqPad. This is truly an awesome tool and if you’re not already using it, go download it right now (it’s free).  You can work with database connections (LINQ to SQL, EF), LINQ to Objects, WCF Data Services, and LINQ to XML. For LINQ to XML, put LinqPad in “C# Statements” mode rather than the default “C# Expressions.”

My first step was to remove the XML namespaces from the XML. If my query didn’t return any results, I wanted to make sure it was because something was wrong with the query and not a silly namespace issue. For my first iteration of the query, I didn’t want to have to worry about optional elements, so I left Item3 out. Also, I knew that I could get the sibling element with LINQ to XML by using the ElementsAfterSelf() method:

   1:  var entries = from item in xmlList.Descendants("entry")
   2:                select new 
   3:                {
   4:                    Id = item.Element("id").Value,
   5:                    Title = item.Element("title").Value,
   6:                    Item1 = item.Element("content").Element("div").Element("table").Elements("tr").Elements("td").First(x => x.Value == "Item1").ElementsAfterSelf().First().Value,
   7:                    Item2 = item.Element("content").Element("div").Element("table").Elements("tr").Elements("td").First(x => x.Value == "Item2").ElementsAfterSelf().First().Value
   8:                };

While that does work, it certainly was not very pretty (or efficient with the deeply nested xhtml).  A better approach would be to encapsulate each entry’s table rows into a variable via the “let” keyword:

   1:  var entries = from item in xmlList.Descendants("entry")
   2:                let rows = item.Element("content").Element("div").Element("table").Elements("tr").Elements("td")
   3:                select new 
   4:                {
   5:                    Id = item.Element("id").Value,
   6:                    Title = item.Element("title").Value,
   7:                    Item1 = rows.First(x => x.Value == "Item1").ElementsAfterSelf().First().Value,
   8:                    Item2 = rows.First(x => x.Value == "Item2").ElementsAfterSelf().First().Value
   9:                };

That’s a definite improvement since I now have a “rows” variable that encapsulates all of the <td> elements for just that entry.  Now that we’re confident the structure is in good order, we can put the namespaces back in:

   1:  XNamespace atomNs = "http://www.w3.org/2005/Atom";
   2:  XNamespace xhtmlNs = "http://www.w3.org/1999/xhtml";
   3:   
   4:  var entries = from item in xmlList.Descendants(atomNs + "entry")
   5:                let rows = item.Element(atomNs + "content").Element(xhtmlNs + "div").Element(xhtmlNs + "table").Elements(xhtmlNs + "tr").Elements(xhtmlNs + "td")
   6:                select new 
   7:                {
   8:                    Id = item.Element(atomNs + "id").Value,
   9:                    Title = item.Element(atomNs + "title").Value,
  10:                    Item1 = rows.First(x => x.Value == "Item1").ElementsAfterSelf().First().Value,
  11:                    Item2 = rows.First(x => x.Value == "Item2").ElementsAfterSelf().First().Value
  12:                };

At this point, the only thing left is dealing with the optional XML elements. Following this tip by John Papa, we can add the optional check for any item (Item2 and Item3 shown on line 11-12 below) like this:

   1:  XNamespace atomNs = "http://www.w3.org/2005/Atom";
   2:  XNamespace xhtmlNs = "http://www.w3.org/1999/xhtml";
   3:   
   4:  var entries = from item in xmlList.Descendants(atomNs + "entry")
   5:                let rows = item.Element(atomNs + "content").Element(xhtmlNs + "div").Element(xhtmlNs + "table").Elements(xhtmlNs + "tr").Elements(xhtmlNs + "td")
   6:                select new 
   7:                {
   8:                    Id = item.Element(atomNs + "id").Value,
   9:                    Title = item.Element(atomNs + "title").Value,
  10:                    Item1 = rows.First(x => x.Value == "Item1").ElementsAfterSelf().First().Value,
  11:                    Item2 = (rows.FirstOrDefault(x => x.Value == "Item2") == null ? null : rows.First(x => x.Value == "Item2").ElementsAfterSelf().First().Value),
  12:                    Item3 = (rows.FirstOrDefault(x => x.Value == "Item3") == null ? null : rows.First(x => x.Value == "Item3").ElementsAfterSelf().First().Value)
  13:                };

At this point, things are working pretty well, so we can put this back into Visual Studio and execute the original unit test which is now green. But we’re not quite done.  While this code does what we want, it’s not particularly succinct or DRY. It’s also not incredibly efficient given that we’re looking for the items multiple times (first to check for existence and then to get the value).  When you hit situations like this, you can always write your own extension methods quite easily. So we can write an extension method to get a sibling value but only if the item exists (so it can be an optional element):

   1:  public static string FindSiblingValue(this IEnumerable<XElement> elements, string tagName)
   2:  {
   3:      var label = elements.FirstOrDefault(x => x.Value == tagName);
   4:      return (label == null ? null : label.ElementsAfterSelf().First().Value);
   5:  }

Once we have that in place, we can now refactor our LINQ to XML query:

   1:  var entries = from item in xmlList.Descendants(atomNs + "entry")
   2:                let rows = item.Element(atomNs + "content").Element(xhtmlNs + "div").Element(xhtmlNs + "table").Elements(xhtmlNs + "tr").Elements(xhtmlNs + "td")
   3:                select new 
   4:                {
   5:                    Id = item.Element(atomNs + "id").Value,
   6:                    Title = item.Element(atomNs + "title").Value,
   7:                    Item1 = rows.FindSiblingValue("Item1"),
   8:                    Item2 = rows.FindSiblingValue("Item2"),
   9:                    Item3 = rows.FindSiblingValue("Item3")
  10:                };

Now the code is succinct and efficient.

When looking at the final result, it really just boils down to 10 lines of C# code. However, with situations like these where you have to address multiple things at once, the best approach is typically to break it down into the smaller sub-components and attack each one individually. It’s also key to have a good testing strategy up front with unit tests and “scratch pads” like LinqPad since the last thing you want to be doing is wasting your time hitting F5 all the time to see if your code runs correctly.


Wednesday, December 16, 2009 #

The next version of Entity Framework has many new features, many of which are enabling it to catch up with features previously available in other frameworks like LINQ to SQL.  One of these new features is the updated stored procedure support.  In previous versions of EF, working with stored procedures was quite limited and really only usable with CRUD operations that were mapped to already defined entities.  With EF 4, you can start with your stored procedure and have the designer automatically generate return types.  Essentially it will “sense” the shape of the parameters and (if applicable) SELECT statement and generate types that match it or allow you to map it to an already existing type.  This is certainly a great new feature to be adding but, at the same time, these stored procedure features have been in LINQ to SQL since version 1.

Although the features are similar between EF 4 and LINQ to SQL, the implementation isn’t exactly the same.  Suppose we have a typical Contact object that looks like this:

   1:  public class Contact
   2:  {
   3:      public Contact()
   4:      {
   5:          this.Addresses = new List<Address>();
   6:      }
   7:   
   8:      public int ContactId { get; set; }
   9:      public string FirstName { get; set; }
  10:      public string LastName { get; set; }
  11:      public string Email { get; set; }
  12:      public string Title { get; set; }
  13:      public ICollection<Address> Addresses { get; set; }
  14:  }

and stored procedure to insert a new contact that takes all of these properties as parameters (with an output parameter for the ContactID since it’s a PK Identity).  If we use the typical edmx approach, we get generated code for this stored procedures that looks like this:

   1:  public int SaveContact(ObjectParameter contactID, global::System.String firstName, global::System.String lastName, global::System.String company, global::System.String title, global::System.String email)
   2:  {
   3:      ObjectParameter firstNameParameter;
   4:      if (firstName != null)
   5:      {
   6:          firstNameParameter = new ObjectParameter("FirstName", firstName);
   7:      }
   8:      else
   9:      {
  10:          firstNameParameter = new ObjectParameter("FirstName", typeof(global::System.String));
  11:      }
  12:   
  13:      ObjectParameter lastNameParameter;
  14:      if (lastName != null)
  15:      {
  16:          lastNameParameter = new ObjectParameter("LastName", lastName);
  17:      }
  18:      else
  19:      {
  20:          lastNameParameter = new ObjectParameter("LastName", typeof(global::System.String));
  21:      }
  22:   
  23:      ObjectParameter companyParameter;
  24:      if (company != null)
  25:      {
  26:          companyParameter = new ObjectParameter("Company", company);
  27:      }
  28:      else
  29:      {
  30:          companyParameter = new ObjectParameter("Company", typeof(global::System.String));
  31:      }
  32:   
  33:      ObjectParameter titleParameter;
  34:      if (title != null)
  35:      {
  36:          titleParameter = new ObjectParameter("Title", title);
  37:      }
  38:      else
  39:      {
  40:          titleParameter = new ObjectParameter("Title", typeof(global::System.String));
  41:      }
  42:   
  43:      ObjectParameter emailParameter;
  44:      if (email != null)
  45:      {
  46:          emailParameter = new ObjectParameter("Email", email);
  47:      }
  48:      else
  49:      {
  50:          emailParameter = new ObjectParameter("Email", typeof(global::System.String));
  51:      }
  52:   
  53:      return base.ExecuteFunction("SaveContact", contactID, firstNameParameter, lastNameParameter, companyParameter, titleParameter, emailParameter);
  54:  }

It’s good that’s generated code and we don’t have to worry about writing that ourselves but it’s not the prettiest code to look at.  Let’s take a look at the exact same stored procedure call in a LINQ to SQL data context:

   1:  [Function(Name = "dbo.SaveContact")]
   2:  public int SaveContact(ref Nullable<int> contactID, string firstName, string lastName, string company, string title, string email)
   3:  {
   4:      IExecuteResult result = this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod(), contactID, firstName, lastName, company, title, email);
   5:      contactID = (Nullable<int>)result.GetParameterValue(0);
   6:      return (int)result.ReturnValue;
   7:  }

The first most obvious difference is that’s 54 lines of code for EF 4 and 7 lines of code for LINQ to SQL.  Second, LINQ to SQL allows you to just pass in the primitive types to the built-in ExecuteMethodCall() method whereas EF 4 wants a list of ObjectParameter types for its ExecuteFunction() method.  Third, LINQ to SQL can reflect over the parameters to figure out, by name, which parameters map to which stored procedure parameters (LINQ to SQL also provides the [Parameter] attribute if the names or types differ and need to be explicitly mapped). EF, on the other hand, wants the string for the name explicitly set (e.g., “FirstName”, “LastName”, etc.). Also, EF 4 specifies the name of the stored procedure as a parameter to the ExecuteFunction() method, whereas LINQ to SQL specifies it in the [Function] attribute which decorates the method.  Finally, the last interesting difference that I see is in regards to the contact ID property.  That is the PK Identity column that gets assigned from the database on insert.  LINQ to SQL automatically exposes that as a ref parameter (which is an API that makes sense from a C# perspective) and assigns the values after the stored procedure has been invoked via the GetParameterValue() method.  EF 4, on the other hand, exposes that parameter as an actual ObjectParameter (rather than a “ref int”) and all the rest of the parameters as their natural primitives. So the responsibility is on the caller to create the ObjectParameter for the PK property but not for the other ones. This allows the caller to have a reference to the variable so that, in the case of output parameters, it can get at the new value that was just assigned by the database.

Certainly there are pros and cons of each approach. But I doubt I would be putting myself in the minority to say that I prefer the (much) more succinct API that LINQ to SQL provides. So, while I love the fact that EF 4 is now allowing me to call stored procedures in a similar way to what I had with LINQ to SQL, I’m not absolutely thrilled with the API.

But, digging a little deeper, how can I add some re-usable methods to be able to give my EF 4 a more succinct API?

The first thing I want to do is to get an easy way to create all of those ObjectParameters automatically from their primitive types without all the IF statements checking to see if each one is null. If I want to add on to the designer generated code, I can create this method in a partial class. Otherwise, if I’m using the “code only” approach, I can put this method in my own base ObjectContext class xxxxx:

   1:  public class SmartObjectContext : ObjectContext
   2:  {
   3:      protected ObjectParameter[] GetObjectParameters(MethodInfo methodInfo, params object[] parameters)
   4:      {
   5:          var objectParameters = new ObjectParameter[parameters.Length];
   6:   
   7:          var methodParams = methodInfo.GetParameters();
   8:          for (int i = 0; i < parameters.Length; i++)
   9:          {
  10:              var paramName = methodParams[i].Name;
  11:              var paramType = methodParams[i].ParameterType;
  12:              var paramValue = parameters[i];
  13:              if (paramValue == null)
  14:              {
  15:                  objectParameters[i] = new ObjectParameter(paramName, paramType);
  16:              }
  17:              else
  18:              {
  19:                  objectParameters[i] = new ObjectParameter(paramName, parameters[i]);
  20:              }
  21:          }
  22:          return objectParameters;
  23:      }
  24:  }

This method is clearly not as robust as the LINQ to SQL implementation which optionally takes into account parameter attributes if they exist to further customize the mapping, but it gets the job done.  This now allows my (previously 54 lines) SaveContact() method to now look like this:

   1:  public int SaveContact(ref int contactID, string firstName, string lastName, string company, string title, string email)
   2:  {
   3:      var objParams = this.GetObjectParameters((MethodInfo)MethodInfo.GetCurrentMethod(), contactID, firstName, lastName, company, title, email);
   4:      var result = this.ExecuteFunction("SaveContact", objParams);
   5:      contactID = (int)objParams.First(o => o.Name == "contactID").Value;
   6:      return result;
   7:  }

Just by adding this one method to a base class (or current class if you’re using a partial) I was able to reduce my SaveContact() method from 54 lines to 7 lines, and allow the API to be primitives for all parameters including a “ref int” for the PK Identity rather than an ObjectParameter.

I can also simplify this even further if I’m invoking stored procedures that are not assigning output parameters. For example, suppose you have a simple GetContact stored procedure which takes a single integer contactID as the parameter to the stored procedure. The auto-generated EF 4 code looks like this:

   1:  public ObjectResult<Contact> GetContact(Nullable<global::System.Int32> contactID)
   2:  {
   3:      ObjectParameter contactIDParameter;
   4:      if (contactID.HasValue)
   5:      {
   6:          contactIDParameter = new ObjectParameter("ContactID", contactID);
   7:      }
   8:      else
   9:      {
  10:          contactIDParameter = new ObjectParameter("ContactID", typeof(global::System.Int32));
  11:      }
  12:   
  13:      return base.ExecuteFunction<Contact>("GetContact", contactIDParameter);
  14:  }

Notice this is using a different ExecuteFunction() method that is generic and is strongly-typed to the Contact class in this instance.  I can create my own generic ExecuteFunction() method that encapsulates the creation of the ObjectParameter(s) and also put that in my base (or partial) ObjectContext:

   1:  public ObjectResult<T> ExecuteFunction<T>(string functionName, MethodInfo methodInfo, params object[] parameters)
   2:  {
   3:      var objParams = this.GetObjectParameters(methodInfo, parameters);
   4:      return base.ExecuteFunction<T>(functionName, objParams);
   5:  }

What this now allows me to do is to refactor my GetContact() method to now look like this:

   1:  public ObjectResult<Contact> GetContact(Nullable<int> contactID)
   2:  {
   3:      return this.ExecuteFunction<Contact>("GetContact", (MethodInfo)MethodInfo.GetCurrentMethod(), contactID);
   4:  }

Essentially this is now down to 1 meaningful line of code.

A couple of other things to keep in mind – first, the technique of these helper methods can be used regardless of whether you are using EF 4 in “data first”, “model first”, or “code only” scenarios.  Secondly, if you are using edmx files, EF 4 now allows you to customize the generated code that is produced via T4 templates.  So if you don’t like the code that the EF 4 designer is creating for you out of the box, change it!

One final note on EF 4 stored procedure support: apparently it does *not* support stored procedures that have multiple result sets – this also has been available since the first version of LINQ to SQL via IMultipleResults. I’m told this functionality can be added to EF with the EF Extensions library but I have yet to use it myself.

I’m still in the process of exploring all of the new features being added to EF 4. While some of them are quite interesting (e.g., fluent mappings, etc.), many of the other features being added have already been available in other frameworks like LINQ to SQL.  Definitely good to seem them being added to EF 4 now as well.


Friday, November 27, 2009 #

Lately I’ve been working with EF 4.0 and finding that many of the new features are catching up with the features previously available in other framework like LINQ to SQL.  One example of this is the ability to easily attach objects (for example, disconnected objects that come in from another tier).  For example, imagine you had a web service where a consumer submitted an object to get saved – you’d want to instantiate a new context, attach the incoming entity, and save the object.  In previous versions of EF, this was not a trivial thing to do.  However, this was always quite easy to do in LINQ to SQL by doing this:

   1:  using (var dataContext = new MyDataContext())
   2:  {
   3:      dataContext.Contacts.Attach(someEntity, true);
   4:      dataContext.SubmitChanges();
   5:  }

Notice the second Boolean parameters of the Attach() method – this instructs the context that the entity should treated “as modified” so that an UPDATE command should be issued for that entity when SubmitChanges() gets called (LINQ to SQL also provides an AttachAll() method for collections).  You can now do the same thing in EF 4 like this (I’m using POCO and Code Only here):

   1:  using (var dataContext = new MyDataContext())
   2:  {
   3:      dataContext.Contacts.Attach(contact);
   4:      dataContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
   5:      dataContext.SaveChanges();
   6:  }

This is a huge leap forward from previous versions of EF but notice that this actually takes one more line of code than its LINQ to SQL counterpart because an explicit call to the ObjectManager’s ChangeObjectState() method must be called. Although this might appear to be a slight inconvenience, it is possible to write a couple of extension methods to simplify this since the ObjectSet’s all have a reference to the parent Context:

   1:  static class ContextExtensions
   2:  {
   3:      public static void AttachAsModified<T>(this ObjectSet<T> objectSet, T entity) where T : class
   4:      {
   5:          objectSet.Attach(entity);
   6:          objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
   7:      }
   8:   
   9:      public static void AttachAllAsModified<T>(this ObjectSet<T> objectSet, IEnumerable<T> entities) where T : class
  10:      {
  11:          foreach (var item in entities)
  12:          {
  13:              objectSet.Attach(item);
  14:              objectSet.Context.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
  15:          }
  16:      }
  17:  }

This allows you to now save like this:

   1:  using (var dataContext = new MyDataContext())
   2:  {
   3:      dataContext.Contacts.AttachAsModified(contact);
   4:      dataContext.SaveChanges();
   5:  }

This is pretty straight forward and certainly not very complex. However, it is promising that EF is moving in the direction of better enabling these simple scenarios as compared with previous versions.


Wednesday, November 18, 2009 #

Recently my company just released the first version of a new MVC web site: AlbumCredits.com.  This project, led by Oskar Austegard, is was I consider a highly successful real-world implementation of MVC. In a time when most music these days is downloaded, the production and performance engineers, and recording professionals that work on the music don’t always get credit because there is no CD booklet to look through.  Album Credits is almost like a LinkedIn for recording professionals.  From the about page:  AlbumCredits.com is “A fast, easy way to find production and performance credits from more than one million CDs and LPs.”

We leveraged a ton of great technologies during the development of this solution. To name a few:

  • Custom Controller factory based on StructureMap Inversion of Control (IoC) container
  • jQuery for all AJAX needs
  • T4MVC Templates
  • Data Annotations for Validation
  • xVal for client side validation
  • LINQ to SQL with stored procedures (including a few UDFs) for data access
  • SQL Server 2008 with Full Text Search
  • SQL Server Integration Services for the data feed
  • MvcFutures (functionality that will be baked in to MVC2)
  • Numerous custom HTML Helpers
  • Numerous third party jQuery plug ins including:
    • jQuery UI
    • jQuery Tools:
      • Tabs
      • Scrollable
      • Overlay
    • Tablesorter
    • jQuery Form
    • Jcrop
    • jWysiwyg
  • For unit testing – NUnit and NUnitEx
  • For mocking - Moq

Additionally, on the build server we used:

  • Cruise Control .NET
  • MSBuild
  • FxCop
  • StyleCop
  • NUnit

Album Credit starts with a nice AJAX auto-complete search box:

 

The site is then “deep linkable”. Want to see what engineers worked on a particular album?  What other albums did they work on? Which other artists?  You can literally relate any category together in your searching - think Six Degrees of Kevin Bacon but for the music industry.

 

It’s an example of a site that takes a very cool idea and melds it will a solid technical implementation.  Check it out!


Saturday, November 14, 2009 #

If you’re planning on being at Windows 7 Developer Boot Camp (already sold out) at PDC 09 next week come check out the “Lunch with the MVPs” scheduled from 12:00-1:15. We will be having several tables where you can come over and have (informal) conversations on a wide range of topics including: MVC, RIA, Silverlight, XNA, LINQ, and more.  I will be leading the table “MVC in the Real World” so come check us out.  Hope to see you there!


Thursday, November 12, 2009 #

Thanks to everyone who attended my LINQ to SQL presentation at RockNUG last night.  The code samples can be downloaded here: LINQ to SQL demo code.

As a point of clarification from last night’s Q&A session after the presentation regarding using LINQ to SQL with true POCO classes that do not even have [Column] mapping attributes, you can have a class like this:

   1:  public class Contact
   2:  {
   3:      public int ID;
   4:      public string FirstName { get; set; }
   5:      public string LastName { get; set; }
   6:      public string Title { get; set; }
   7:  }

If you’re using LINQ to SQL with stored procedures then this class (even without the [Column] attributes) will work just fine.  The one catch is that you can *not* have the class itself decorated with the [Table] attribute which is what happened during the Q&A at the end of last night when someone asked me to show it work without attributes.  I commented the [Column] attribute but did not also comment the [Table] attribute on the class level. If I had also commented out the [Table] attribute, however, then I would have run into this (different issue) because of the “extra” HomeAddress and BusinessAddress properties I added to the partial class (so bear that in mind if you test).

If you watch my blog in the next couple of days (or just subscribe to the rss feed) I’ll put up a post dedicated strictly to the various mapping options you have with LINQ to SQL and downloadable code examples of each since the only mapping I showed last night was the attributed-based mapping (e.g., mapping with attributes, mapping with XML, mapping differences with auto-generated SQL vs. stored proces, mapping with true POCO, etc.).  Thanks!


Tuesday, November 10, 2009 #

Tomorrow night I’ll be at RockNUG presenting LINQ to SQL. Yes, LINQ to SQL. Again. In the last 2 years I have presented LINQ to SQL numerous times at various user groups and code camps. Why do I keep getting asked to present LINQ to SQL? Isn’t LINQ to SQL dead? Answer: No.  LINQ to SQL is not dead!

This confusion all started back in October 2008 with a seemingly innocuous post on the ADO.NET team blog discussing the emphasis that Microsoft was going to put into the Entity Framework going forward.  The developer community was immediately up in arms about this post for a variety of reasons.  First, many developers and companies had already made a significant investment in developing with LINQ to SQL.  Secondly, LINQ to SQL is great so why de-emphasize it?  Third, the Entity Framework has had its share of challenges getting acceptance in the development community (and I’m being charitable) so the thought of replacing something “good” with something “not as good” was not met with enthusiasm.

This led to a “clarification message” by the ADO.NET team a few days later in which they clearly state: “LINQ to SQL is not dead.” This post may have been a somewhat weak defense of LINQ to SQL but the message was clear nonetheless. We’ve also seen others from Microsoft strongly advocate LINQ to SQL.  For example, in this MVC presentation at MIX 09, Scott Hanselman states he’s using LINQ to SQL in the demo “because it’s awesome and it’s not dead.” This all leads to a somewhat confusing state of affairs because we find ourselves relying on quotes from a respected Microsoft guru like Scott Hanselman and others in an attempt to translate Microsoft’s marketing approach for their latest data access strategy. After all, one of the longest running jokes is that the last thing Microsoft needs is yet another data access framework.

So how do we make this pragmatic decision for ourselves when deciding on a data access strategy/framework? Although there are numerous data access choices, the top three frameworks that are typically examined are: 1) LINQ to SQL, 2) NHibernate, and 3) the Entity Framework (EF).

The Entity Framework vNext that will be released after .NET 4.0 looks very promising.  Model first, POCO code only, foreign key relationships, and more make me enthusiastic to give EF another run next year.  But…that’s next year. If you’re starting development on a new application today, you might think twice.

NHibernate is a great framework. No dispute there. On it’s own it’s solid but then when you add features such as Fluent NHibernate and LINQ to NHibernate it’s becomes an extremely compelling choice. However, there is a steeper learning curve with NHibernate as compared to some other frameworks such as LINQ to SQL.  Additionally, some organizations (unfortunately) have policies against using open source software which disqualifies NHibernate in those environments.

Then you’ve got trusty ol’ LINQ to SQL. In the last year, LINQ to SQL has continued to provide a solid data access choice. I strongly agree with the numerous points that Ian Cooper made in this post showing support for LINQ to SQL. In short, there are numerous reasons to learn and use LINQ to SQL. Among them:

  • LINQ to SQL is a stable release and has withstood the test for 2 years now. You don’t have to wait for the next release (like EF) – you can use it *now*.
  • Open source is not always an option (depending on your environment). LINQ to SQL is good to go here.
  • The skills you learn in LINQ to SQL are transferrable.  In other words, if you learn LINQ to SQL now and later decide to switch to EF next year, you won’t be starting from scratch. Your knowledge will be transferrable.
  • There are also some cool OSS projects for LINQ to SQL such as Fluent LINQ to SQL.

And finally, LINQ to SQL is just flat out *good*. While it may not be perfect (no framework is) the designers of LINQ to SQL inside Microsoft really got far more right than wrong when creating LINQ to SQL. You can use it with a RAD designer or you can hand code all your classes.  You can use it with C# attributes for mapping or external XML mapping files (or fluent mapping with OSS libraries). You can use it with auto-generated SQL or stored procedures. You can use it with POCO classes. You can use it in an N-Tier application without having to worry about serialization of your entities. It supports lazy loading or eager loading. The list goes on.

Having implemented numerous production applications with LINQ to SQL, I’m happy with it. But I’ll continue to learn more about it and other data access technologies as well as they come out.

If you’re in Rockville tomorrow night and have a desire to start learning LINQ to SQL, come on out!


Saturday, November 07, 2009 #

In an effort to continually improve as a developer, one of the things I do is read lots of books. Recently I read ASP.NET MVC in Action by Jeffrey Palermo, Ben Scheirman, and Jimmy Bogard. In short, I consider this a “must read” for anyone who is serious about developing with the ASP.NET MVC framework.

I’ve heard some people say that this should not be your first MVC book because it is more advanced than other MVC books available.  While I can understand that logic to a degree, I think it would be more accurate to say that if you’re literally brand new to MVC, this might not be the best “introductory” book.  However, if I could only own one book on MVC, this book would be it. There are two common themes from this book that I really enjoyed. First, the authors base their content on “real world” concepts rather than just explaining every topic in a mechanical way. This gives a great real world context throughout the book.  Secondly, the authors are not afraid to be “opinionated” in their recommended best practices for the MVC framework. These are aspects that are lacking in many technical books.

The book starts out with a nice introduction to MVC (and it’s not too advanced to follow in the least). One of the things I really liked about this first chapter is that it spent some time discussing the history of web development which gave great context to where and how ASP.NET MVC fits into the discussion. This included many of the reasons as to *why* we have the MVC framework to begin with. The very next chapter dives into the Model of MVC and does a great job explaining the differences between domain models and presentation or view models.  Philosophically, I really agree with their concepts around view models and I have referenced some of them before on this blog. Understanding these view model concepts is essential to building mature MVC applications.

The books then dives into Controllers. The aspect I enjoyed most about this was the emphasis on unit testing. This included mocking and best practices for dependencies. The Controllers chapter ended with a discussion of action filters which was decent but I would have liked if the discussion of action filters had been expanded a little. The Views chapter provided great content covering validation, custom html helpers, partial views, and more. I didn’t find the Views chapter to be very advanced at all – rather, it provided a solid foundation for the type of information developers should know when building views.

I really appreciated the chapter on Routing. It discussed designing the routing topology of your application up front which is often overlooked. It also discussed REST best practices. The examples of Routing constraints were one of the strongest parts of the chapter and they are an area that I’ve observed is often overlooked in MVC applications. My favorite part of the Routing chapter was unit testing routes with the very cool route testing extensions available in the MvcContrib project which makes unit testing routes trivial. For example, it showed how you can test a route in one simple line of code like this: "~/boiseCodeCamp/edit".ShouldMapTo<ConferenceController>(x => x.Edit("boiseCodeCamp"));

Towards the end of the book there was a chapter dedicated to exploring (for the sake of contrasting and understanding historical context) MonoRail and Ruby of Rails.  I always find the comparisons between Ruby on Rails and MVC very interesting and that was true in this book as well.  However, I didn’t find myself as engaged in the MonoRail discussion and I didn’t think it added as much to the book as the Ruby on Rails section.

Probably the best chapter in the book was the one dedicated to Best Practices. Once again the authors were not afraid to be opinionated in their recommendations and this was based on “real world” experience with the framework (for which there is no substitute). One example I really liked from this section was the advocating of the RenderAction() method. This method has not been without its share of controversy because there are some “purists” that believe the existence of this method violates the tenets of the MVC framework because this means the view has some “knowledge” of the controllers. However, the authors point out (correctly, in my opinion) that the method allows for a much more elegant implementation in many cases that is a very pragmatic choice that actually leads to *better* separation of concerns in many instances since the partial gets its own controller.

Learning the mechanics of MVC is important. But even more important is learning best practices and how you can extend the MVC framework to suit your needs when the situation requires it. In my opinion, this is the best book I’ve read that can help get you to that goal.


Thanks to everyone who attended my “MVC in the Real World” presentation at CMAP Code Camp today.  The code as well as the PowerPoint can be downloaded here:

MVC in the Real World Download

I also had a few other requests during the talk.  First, I had a request to post the code as it looked at the very beginning of my talk before I modified anything.  You’ll find that link on the download page above as well (file name: PersonalInfoManager-ReadlWorldMVC-Begin.zip). 

Second, I was asked about a couple of the tools I was using.  You can see the links for all the tools I use (almost all free) on my Developer Tools and Utilities page.

Third, I had a request to post some links that discussed some of the Unit Testing best practices. Brad Wilson (one of the primary developers of xUnit) co-authored this excellent article: Effective Unit Testing. I also really like this slide deck which he also published: Lessons Learned in Programmer Testing. Roy Osherove also has a great post on Naming Standards for Unit Tests. Finally, I love this article by Jeremy Miller in MSDN magazine entitled Designing for Testability. One of his article’s major premises is that “testable” code typically will naturally result in “well designed” code – a concept that I’m a huge fan of.


Wednesday, November 04, 2009 #

Thanks to everyone who attended my C# 4.0 New Languages Features presentation at CMAP last night.  Both the code and PowerPoint are available for download.

C# 4.0 New Language Features Download

After the presentation, I had a few people ask me about some of tools I was using.  They can all be found on my Developer Tools and Utilities page. To create my snippets, I’ve been using a tool called Snippy for years (link included on Developer Tools page).  However, lately I’ve also been using Snippet Designer which is a Visual Studio add-in that is also quite good.


Sunday, November 01, 2009 #

I’ll be giving a presentation on C# 4.0 New Language Features this Tuesday at the CMAP Main Meeting.

Also I’ll be presenting MVC in the Real World this Saturday at CMAP Code Camp.

Hope to see you there!