Steve Michelotti

C#, ASP.NET, and other stuff

  Home  |   Contact  |   Syndication    |   Login
  75 Posts | 1 Stories | 271 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

Thursday, June 25, 2009 #

ADO.NET Data Services provides a robust REST API over top of a data source. That data source could be 1) the Entity Framework (EF), 2) LINQ to SQL, or 3) your own custom data source that implements IQueryable and/or IUpdatable.  However, it should be noted that in v1, EF is really the “first class” data source for ADO.NET Data Services because it supports both IQueryable and IUpdatable out of the box.  In this post I’ll discuss the scenario where you have inheritance in your entity object model and the pros and cons of the implementation. As a stand-alone ORM tool, EF has not always been extremely well received by the developer community especially in comparison to other tools such as LINQ to SQL and NHibernate.  While I generally share many of the frustrations of my fellow developers with EF, the 2 reasons I find it compelling enough to investigate further are: 1) it’s first class support for ADO.NET Data Services (and data services is great), and 2) the enhancements that are coming in EF vNext including Code Only with POCO which will bring EF much more in line with other ORM tools that already enable these POCO scenarios as well as Model First development.

EF supports 3 types of inheritance: 1) Table per Hierarchy (aka Single Table Inheritance), 2) Table per Type, and 3) Table per Concrete Type.  In this example, I’ll be using the Table per Type (TPT) inheritance. I won’t cover every detail as to how I set up the TPT inheritance with EF but if you haven’t done it before then you should check out this post here that covers step by step how to do it. In my scenario, suppose I have an EF model that looks like this:

 

Notice that I have a base class of Client which both Person and Business inherit from.  Additionally, a Person and a Business will have ClientAddresses (they inherit the addresses from the base Client class).  I add a new ADO.NET Data Service to my project which looks like this:

   1:  public class ClientDataService : DataService<ClientEntities>
   2:  {
   3:      public static void InitializeService(IDataServiceConfiguration config)
   4:      {
   5:          config.SetEntitySetAccessRule("*", EntitySetRights.All);
   6:      }
   7:  }

Note that I named my EF object context “ClientEntities” so the DataService can be strongly-typed as shown above. Also note that I’m completely opening up my permissions to all entities by using the * wildcard in the SetEntitySetAccessRule() call above but in production you’d want to think through your permissions a little more than shown in my demo code above.

Now at this point, if we fire up our data service we’ll see the default meta-data screen:

 

This screen shows the entity sets I have available to query but interestingly it does not show that I have a Person or Business entity set available (more on that later).  So how do I get a Person or a Business object?  I just so happen to know that in my database, the ClientID of 1 is a Person and the ClientID of 2 is a Business.  If I do a query for a Client with these respective ClientID’s, it actually figures it out for you.

Here is my query for a Client who is a Person:

 

And here is my query for Client who is a Business:

 

Data Services in conjunction with EF will correctly instantiate the correct concrete type. In one regard, this is great.  But on the other hand, this isn’t very explicit.  The URI I used was: /Clients(2).  Wouldn’t it have been more explicit if I could have used the URI of /Persons(2)?  After all, that is the name of my EntitySet.  But *actually* it’s not the name of my EntitySet.  In these inheritance situations, EF allows you to specify the Entity Set Name for the base type, but it does not allow you the set the Entity Set Name for the sub-class – that just takes the same Entity Set Name as it’s base class. One way for us to use a more intuitive URI would be to create a Service Operation like this:

   1:  [WebGet]
   2:  public IQueryable<Person> Persons()
   3:  {
   4:      var results = from c in this.CurrentDataSource.Clients
   5:                    where c.ClientType == "PERSON"
   6:                    select c;
   7:      return results.ToList().Cast<Person>().AsQueryable();
   8:  }

Note you must also enable permissions to this new service operation by adding this line of code your your InitializeService() method:

   1:  config.SetServiceOperationAccessRule("Persons", ServiceOperationRights.All);

So now you are able to get a Person object with a more explicit and “strongly-typed” URI like this:

 

This is all well and good but it does have some drawbacks.  For one thing, this service operation does not appear on the default page that shows all the meta data for the data service so the discoverability for something like this is not great.  Additionally, on the client side, the consuming developer will also have to understand these implementation details and handle the casting on their end if they’re consuming data services in the default fashion with the data services proxy.  Therefore, while I’ve found this scenario to be *possible* with Data Services and EF, I don’t really put it in the category of extremely user friendly.  However, these drawbacks seem to be more of a function of the implementation of EF than ADO.NET Data Services so I’m still a fan of data services.  It will be interesting to see how the enhancements in EF 4.0 (especially with the renewed emphasis on POCO) will change the game with scenarios like these.


Wednesday, June 03, 2009 #

Often when creating web applications, it’s common for us to want to submit or post forms to the server by using a hyperlink rather than an HTML submit button.  It might be visually more appealing/consistent or whatever your reason might be to have your buttons look like this:

The Cancel button is easy because we can just use a normal Hmtl.ActionLink helper to redirect to whatever our cancel page is.  But what to do for the Save link given that we don’t have anything in MVC out of the box that is analogous to the LinkButton in ASP.NET web forms?  One solution might be to just use JavaScript like this:

   1:  <a href="javascript:document.mainForm.submit();">Save</a>
   2:  <%=Html.ActionLink("Cancel", "Index") %>

But that is somewhat ugly and the paradigm is inconsistent with the Cancel button where we’re using a normal ActionLink.  An alternative for this scenario is to just create a simple SubmitLink HTML helper that will allow you’re code to look like this:

   1:  <%=Html.SubmitLink("Save", "mainForm") %>
   2:  <%=Html.ActionLink("Cancel", "Index") %>

You can see this allows us to have a consistent coding paradigm.  The first argument is the link text and the second is the form name.  The implementation looks like this:

   1:  public static string SubmitLink(this HtmlHelper htmlHelper, string linkText, string formName, object htmlAttributes)
   2:  {
   3:      TagBuilder tagBuilder = new TagBuilder("a");
   4:      tagBuilder.MergeAttribute("href", string.Format("javascript:document.{0}.submit();", formName));
   5:      tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
   6:      tagBuilder.InnerHtml = linkText;
   7:   
   8:      return tagBuilder.ToString();
   9:  }
  10:   
  11:  public static string SubmitLink(this HtmlHelper htmlHelper, string linkText, string formName)
  12:  {
  13:      return htmlHelper.SubmitLink(linkText, formName, null);
  14:  }

Notice there is an overload to takes htmlAttributes so that you can apply any arbitrary attributes you might want.  For example, you might want to apply a CSS class that looks like this:

   1:  <%=Html.SubmitLink("Save", "mainForm", new { @class = "foo" }) %>

These types of little HTML helpers are so easy to build with MVC, especially given that we can use the TagBuilder class, that it really enables a lot of re-use across your applications.


Friday, May 08, 2009 #

Often when I give presentations, I’m asked afterwards what Visual Studio add-ins I was using. The fact is that most of what you’re seeing are not expensive add-ins at all but either built-in Visual Studio functionality or custom Visual Studio macros that I have written and bound to keyboard shortcuts which give the appearance that they’re “built in” to Visual Studio.  The following 4 minute video shows how I use these shortcuts to maintain a fast pace during my presentations and not bore the audience with a whole bunch of repetitive typing.  The code for these visual studio macros can be found here.  The complete list of developer tools that I use on a daily basis can be found here.

 


Wednesday, May 06, 2009 #

Thanks to everyone who attended my presentation last night at CMAP.  The link to download both the code and power point is here.  It also includes the SQL script for creating the database.

I was asked what tool I was using for zooming – it was ZoomIt (which is free).  The link to ZoomIt (plus other tools) can be found here.


Friday, May 01, 2009 #

Next Tuesday (May 5), I will be presenting WCF 3.5 REST Services at CMAP.  Details here: http://www.cmap-online.org/Meetings/Details/2009-05-05.aspx .


Monday, April 27, 2009 #

For those of you who attended my presentation this past weekend at the Richmond Code Camp, you can download the code samples that I used during my presentation here.


Monday, April 06, 2009 #

Relatively recently it was discovered that the MVC framework was inadvertently leading to some bad practices around deleting resources with HTTP GET requests.  Specifically, HTTP best practices (and RESTful best practices) state that GET requests should never modify resources. Some people consider this a “security” hole and, while that may be true, I consider it more of a “best practices” hole.  Stephen Walther has a great post on this topic here. In his post, Walther demonstrates two different alternatives to using a normal HtmlHelper ActionLink: 1) Ajax Deletes and 2) nested forms with image buttons.

In this post, I’m simply going to show an alternative implementation to his first option of the Ajax Delete.

Let’s say you have a list of contacts in a grid like this:

with markup that looks like this:

   1:  <%=Html.ActionLink("Add New Contact", "Create") %>
   2:   
   3:  <table cellspacing="0" cellpadding="4" border="1">
   4:      <tr>
   5:          <th scope="col">First Name</th>
   6:          <th scope="col">Last Name</th>
   7:          <th scope="col">Email</th>
   8:          <th scope="col">&nbsp;</th>
   9:          <th scope="col">&nbsp;</th>
  10:      </tr>
  11:   
  12:      <%foreach (GetContactListResult contact in this.Model) { %>
  13:          <tr>
  14:              <td><%=contact.FirstName %></td>
  15:              <td><%=contact.LastName %></td>
  16:              <td><%=contact.Email %></td>
  17:              <td>
  18:                  <%=Html.ActionLink("Edit", "Create", new { id = contact.ContactID }) %>
  19:              </td>
  20:              <td>
  21:                  <%=Html.ActionLink("Delete", "Delete", new { id = contact.ContactID }) %>
  22:              </td>
  23:          </tr>
  24:      <% } %>
  25:  </table>

On line #21 you will see the line that is the common offender – a hyperlink which will result in a GET request to delete a record to this corresponding Action Method:

   1:  public RedirectToRouteResult Delete(int id)
   2:  {
   3:      this.contactManager.DeleteContact(id);
   4:      return RedirectToAction("Index");
   5:  }

In Walther’s post, he uses the raw Sys.Net.WebRequest object to perform his Ajax operations.  Here I’m going to start out an alternative implementation but using an AjaxHelper. First off, we can change line #21 above to this:

   1:  <%=Ajax.ActionLink("Delete", "Delete", new { id = contact.ContactID }, new AjaxOptions
   2:                                                                          {
   3:                                                                              Confirm = "Are you sure you want to delete?",
   4:                                                                              OnComplete = "deleteComplete",
   5:                                                                              HttpMethod = "DELETE"
   6:                                                                          })%>

The first three arguments (link text, action name, and route values) match the original implementation exactly but note the AjaxOptions in the fourth parameter. We have a nice little confirm message that will be displayed in a JavaScript prompt. You also see that the OnComplete property is pointing to a function delegate called “deleteComplete” to invoke after the Ajax call has completed.  Finally, we’re specifying “DELETE” for the HTTP verb.  There are a couple of additional items that you have to do to make this work.  Specifically, we need to add this script block to the head section of our page:

   1:  <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
   2:  <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
   3:   
   4:  <script type="text/javascript">
   5:      function deleteComplete() {
   6:          window.location.reload();
   7:      }
   8:  </script>

Notice we have to include the Microsoft javascript libraries to ensure the the AjaxHelper methods will work correctly. Also, I’m defining a simple callback to reload the page. If you refer back to my original Delete() action method, it is returning a RedirectToRouteResult.  Additionally, we now need to make a couple of changes to our Delete() action method like this:

   1:  [AcceptVerbs(HttpVerbs.Delete)]
   2:  public ContentResult Delete(int id)
   3:  {
   4:      this.contactManager.DeleteContact(id);
   5:      return this.Content(string.Empty);
   6:  }

Notice it is now allowing *only* requests for the DELETE verb. If a GET request for this URI is issued, it will result in a 404. I also have to return an empty ContentResult since the javascript is now going to do my redirect client side.  So this will be an incredibly lightweight Ajax server call.

As another alternative, you could even write your action method using an EmptyResult type like this:

   1:  [AcceptVerbs(HttpVerbs.Delete)]
   2:  public EmptyResult Delete(int id)
   3:  {
   4:      this.contactManager.DeleteContact(id);
   5:      return null;
   6:  }

Now when we click the delete link, we can see the request via the Web Development Helper IE add-in:

You’ll see we’re now issuing the request with a DELETE verb and the server is returning a 200. Behind the scenes, the AjaxHelper is using the XMLHttpRequest object.  One little side note, it order to make the request show up correctly in the web dev helper add-in, I had to change line #5 of my Action method to this:

   1:  return this.Content(" ");

I’m considering this a bug in the web dev helper because both an empty string and a space work just fine at run-time.

This is all well and good but the one thing is that our AjaxHelper ActionLink is a little verbose.  If I’m going to be having Delete links in multiple places in my app, I sure don’t want to have to repeat this same thing all over the place. I also don’t want to have to put in the same 1-line javascript callback function every time just to do a little redirect. In order to accomplish this, I can write my own little AjaxHelper method called “DeleteLink” that will allow me to change my mark-up to the much simpler version *and* avoid having to include an inline javascript callback like this:

   1:  <%=Ajax.DeleteLink("Delete", "Delete", new { id = contact.ContactID }) %>

Creating your own Html or Ajax Helper in MVC is typically a pretty straightforward process (*much* easier than creating ASP.NET server controls for example). The complete implementation for my DeleteLink helper method is:

   1:  public static string DeleteLink(this AjaxHelper ajaxHelper, string linkText, string actionName, object routeValues)
   2:  {
   3:      return ajaxHelper.ActionLink(linkText, actionName, routeValues, new AjaxOptions
   4:      {
   5:          Confirm = "Are you sure you want to delete this item?",
   6:          HttpMethod = "DELETE",
   7:          OnSuccess = "function() { window.location.reload(); }"
   8:      });
   9:  }

Notice that I’ve inlined the javascript function to reload the page.  Other than that, everything has just been moved into this method to encapsulate it here.  This method could be further customized to include overloads for htmlAttributes, alternative link text, or more. You could also extend this sample by making it more robust by adding a callback for the OnFailure property.


Wednesday, April 01, 2009 #

Thanks to everyone who attended my session today on ASP.NET MVC at Microsoft Tech Days.  You can download the code sample that was build here.  Let me know if any questions.  Thanks.


Monday, March 16, 2009 #

A while back, I blogged about using the Enterprise Library Validation Application Block (VAB) with ASP.NET MVC. As MVC has matured as a framework, this scenario has becoming simpler.  In early releases of MVC, I implemented the execution of the VAB validation in the controller methods.  However, I now prefer to put that logic in the binders themselves.  In earlier versions of the framework, the model binders that came out of the box dealt well with simple objects but if you had more complex View Models (as described in this post) then you had to roll your own binder.  With the latest releases of MVC, the DefaultModelBinder that comes OOTB with MVC is now quite robust and is even capable of dealing with those more complex binding scenarios.  Hence, my preferred method for performing the valiation is best described in this post by David Hayden here.

However, the one issue with that method is that, although the binder deals well with the complex object, you’ll still run into the same issue with the VAB when it comes to the Key property of the validation messages.  That is, the key is the name of the business object property itself which does not always match the property of the view model.  For example, let’s revisit the example from my previous post and update it to use this new method.  We have our Model passed to our view defined as:

   1:  public class ContactViewData
   2:  {
   3:      public Contact Contact { get; set; }
   4:      public IEnumerable<State> StateList { get; set; }
   5:  }

We bind to our textbox like this:

   1:  <%=Html.TextBox("Contact.FirstName")%>

Or, if you prefer the MVC Futures approach, like this:

   1:  <%=Html.TextBoxFor(m => m.Contact.FirstName) %>

So our mismatch is that when the FirstName is invalid, the key for the validation result will be “FirstName” but we were binding to “Contact.FirstName”.  You have two basic options to tackle this type of situation:

Option 1 – Prepend appropriate prefix with your binder

This is basically a re-write of my original method by utilizing a custom model binder that derives from the DefaultModelBinder.  This is also a hybrid of Hayden’s approach:

   1:  public class ContactModelBinder : DefaultModelBinder
   2:  {
   3:      protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
   4:      {
   5:          var validator = ValidationFactory.CreateValidator(bindingContext.ModelType);
   6:          var validationResults = validator.Validate(bindingContext.Model);
   7:   
   8:          foreach (var result in validationResults)
   9:          {
  10:              string mvcKey = GetMvcKey(result);
  11:              bindingContext.ModelState.AddModelError(mvcKey, result.Message);
  12:          }
  13:      }
  14:   
  15:      static Dictionary<Type, string> propertyPrefixMap = new Dictionary<Type, string>()
  16:      {
  17:          { typeof(Contact), "Contact" },
  18:          { typeof(Address), "Contact.Address" }
  19:      };
  20:   
  21:      /// <summary>
  22:      /// Converts an Enterprise Library ValidationResult into the correct "key" to be used by MVC Views.
  23:      /// </summary>
  24:      /// <param name="validationResult"></param>
  25:      /// <returns></returns>
  26:      static string GetMvcKey(ValidationResult validationResult)
  27:      {
  28:          string result;
  29:          propertyPrefixMap.TryGetValue(validationResult.Target.GetType(), out result);
  30:   
  31:          if (string.IsNullOrEmpty(result))
  32:          {
  33:              return validationResult.Key;
  34:          }
  35:          else
  36:          {
  37:              return result + "." + validationResult.Key;
  38:          }
  39:      }
  40:  }

This upside is that you enable you model and validations to match precisely.  The downside is that this model binder does not have a lot of re-use if you’re not using this model in multiple views.

 

Option 2 – Set your Html.ValidationMessage() differently

In this typical scenario, you’d set up your view like this:

   1:  <%=Html.TextBox("Contact.FirstName")%>
   2:  <%=Html.ValidationMessage("Contact.FirstName") %>

Of course, this leads to the issue described above. As an alternative, you could use different name parameters like this:

   1:  <%=Html.TextBox("Contact.FirstName")%>
   2:  <%=Html.ValidationMessage("FirstName") %>

The upside is that you could leverage a more re-usable binder as described in Hayden’s post.  The downside is that it seems a little counter-intuitive to be using different parameters on the TextBox() and ValiationMessage() extension methods to represent the same business object property.  Perhaps this mis-match “feels” a little better with the MvcFutures syntax:

   1:  <%=Html.TextBoxFor(m => m.Contact.FirstName) %>
   2:  <%=Html.ValidationMessage("FirstName") %>

 

Whichever way you end up choosing, you certainly have a couple of decent options.  The fact that MVC was designed in such a flexible way to be able to give you these options in the first place speaks volumes.


Saturday, March 14, 2009 #

On April 1 I will be presenting ASP.NET MVC at Microsoft Tech Days.  This is a totally free 24-hour virtual event.  You can register right now at: http://www.msfttechdays.com. Hope to see you there!


Sunday, March 08, 2009 #

Tomorrow I’ll be giving a presentation at Southern Maryland .NET User Group on LINQ to SQL.  Details of the event can be found here:  http://www.communitymegaphone.com/ShowEvent.aspx?EventID=1022.


Friday, February 06, 2009 #

The System.Core assembly in .NET 3.5 contains the main LINQ methods for dealing with objects such as the Max() extension method. Like many of the LINQ extension methods, the Max() method has many overloads that allow you to do things like this:

   1:  List<int> list = new List<int> { 1, 2, 17, 14, 21, 4 };
   2:  Console.WriteLine("Max: " + list.Max()); //<- "Max: 21"

This is all well and good but what if you need to do something a little more interesting?  There are endless examples to think of but for the sake of this discussion, let’s say we have a directory and we want to find the latest/newest file in that directory.  This isn’t very complicated and there are several ways to do it but one simple example might be this:

   1:  private string GetNewestFileInDirectory(string directory)
   2:  {
   3:      FileInfo latestFile = null;
   4:      foreach (var fileName in Directory.GetFiles(directory))
   5:      {
   6:          FileInfo currentFile = new FileInfo(fileName);
   7:          if (latestFile == null || currentFile.LastWriteTimeUtc > latestFile.LastWriteTimeUtc)
   8:          {
   9:              latestFile = currentFile;
  10:          }
  11:      }
  12:      return latestFile.Name;
  13:  }

For each file in the directory, we’re comparing the last write time and, if it’s greater than any other file timestamp, we store it in the temporary latestFile variable which will eventually be returned.  But wouldn’t it be nicer to be able to use some sort of Max() method in this scenario where we’re considering that the “max” is based on the file’s timestamp?  The FileInfo object doesn’t support any type of IComparable interface so that’s no help – and even if it did, it wouldn’t be much help because there’s no clear idea what it would be based on (e.g., file size? file name? file date?).

Let’s first see what we can do with the OOB Max() extension method. We could do something like this:

   1:  IEnumerable<FileInfo> fileList = Directory.GetFiles(directory).Select(f => new FileInfo(f));
   2:  var result = fileList.Max(f => f.LastAccessTimeUtc);
   3:  Console.WriteLine("Result is: " + result); //<- "Result is: Result is: 2/6/2009 8:10:54 PM"

Notice on line 1 I’m creating an IEnumerable<FileInfo> in a single line of code by leveraging the Select() extension method. The Directory.GetFiles() method just returns an array of strings, but I need a collection of the actual FileInfo objects so i can get at the file properties.  Being able to do this on 1 line of code is much more succinct than having to instantiate and object, loop over the source, and continually call the Add() method of the collection.

Line 2 gives of the Max date which is, in fact, the latest date that we’re looking for.  However, the problem is that I am trying to get the *actual* file that is the latest – just knowing the latest date by itself doesn’t do me a whole lot of good. What I really want to be able to do is the have a Max() method that will determine a “max” of any arbitrary object based on a simple expression that I can specify on-demand. In other words, I want to be able to write the code above but have the result be of type FileInfo so that I can get a reference to the actual FileInfo object that happens to have the maximum date in my collection. This can be done by writing your own customized extension method in roughly a dozen lines of code like this:

   1:  public static T Max<T, TCompare>(this IEnumerable<T> collection, Func<T, TCompare> func) where TCompare : IComparable<TCompare>
   2:  {
   3:      T maxItem = default(T);
   4:      TCompare maxValue = default(TCompare);
   5:      foreach (var item in collection)
   6:      {
   7:          TCompare temp = func(item);
   8:          if (maxItem == null || temp.CompareTo(maxValue) > 0)
   9:          {
  10:              maxValue = temp;
  11:              maxItem = item;
  12:          }
  13:      }
  14:      return maxItem;
  15:  }

This extension method has 2 generic type arguments. The first – T – in this case will be the FileInfo object. The second – TCompare – in this case will be the DateTime representing the result of the LastAccessTimeUtc property. In order to make this work correctly, you must have the “where TCompare : IComparable<TCompare>” generic constraint to ensure that whatever value specified implements IComparable. The rest of the algorithm is pretty similar conceptually to the original code.

Now you have a Max() extension method that can be generalized to limitless scenarios. Do you want to find the file with maximum size? Maximum name (alphabetically)? Maximum creation timestamp? Instead of a FileInfo object, you could use it against a collection of Person objects to find the person with the max age or max last name or max date of birth or max date hired, etc., etc. You could also do the same thing for other extension methods (e.g., Min(), etc.).


Thursday, February 05, 2009 #

One of the new language features coming in C# 4.0 is Optional Parameters. In large part, this is due to Microsoft’s plan of co-evolution with C# and VB.NET since VB.NET has had this feature for a while.  Personally, I’m still somewhat undecided about this feature and there has been much written about method overloads versus optional parameters. For example, Considerations in Overloading Procedures.  Ultimately, I do think there will be some scenarios where this will be useful to make code more concise.

Consider a standard scenario with method overloading or constructor chaining.  In C# we’d have several methods with different signatures where, in effect, we’re really just after default values. Let’s take the scenario where we’ve got a little helper class to send emails in our application. In some cases we want to CC the administrator to troubleshoot issues; in some cases we want rich HTML emails rather than plain text. We might set up our methods like this:

   1:  public void SendMail(string toAddress, string bodyText)
   2:  {
   3:      this.SendMail(toAddress, bodyText, true);
   4:  }
   5:   
   6:  public void SendMail(string toAddress, string bodyText, bool ccAdministrator)
   7:  {
   8:      this.SendMail(toAddress, bodyText, ccAdministrator, false);
   9:  }
  10:   
  11:  public void SendMail(string toAddress, string bodyText, bool ccAdministrator, bool isBodyHtml)
  12:  {
  13:      // Full implementation here
  14:  }

This is pretty standard method overloading and we essentially are setting default values (true for CC the Admin, and false for HTML emails). With C# 4.0 we can now make the code more concise by only having to implement 1 method:

   1:  public void SendMail(string toAddress, string bodyText, bool ccAdministrator = true, bool isBodyHtml = false)
   2:  {
   3:      // Full implementation here
   4:  }

However, you do have to take into account your scenario.  If you have a situation where you actually need to know if the consuming code provided a value then this isn’t a good option because if “true” comes in for the 3rd parameter, you don’t know if the consuming code actually set this explicitly or if it was simply the result of the default value.  But in typical scenarios like this, it’s not a big deal.  Cracking open Reflector and looking at the IL that the C# compiler is generating:

   1:  .method public hidebysig instance void SendMail(string toAddress, string bodyText, [opt] bool ccAdministrator, [opt] bool isBodyHtml) cil managed
   2:  {
   3:      .param [3] = bool(true)
   4:      .param [4] = bool(false)
   5:      .maxstack 8
   6:      L_0000: nop 
   7:      L_0001: ret 
   8:  }

Which Reflectors translates to a C# equivalent of:

   1:  public void SendMail(string toAddress, string bodyText, [Optional, DefaultParameterValue(true)] bool ccAdministrator, [Optional, DefaultParameterValue(false)] bool isBodyHtml)
   2:  {
   3:  }

So if consuming code is written using the least specified “overload” like this:

   1:  email.SendMail("bob@foo.com", "Hello World");

The IL that the C# compiler will generate will actually be the equivalent of this:

   1:  email.SendMail("bob@foo.com", "Hello World", true, false);

What’s more interesting is that, unlike traditional method overloading, you have the ability to omit only the 3rd parameter in conjunction with the new Named Parameters language feature and write your code like this:

   1:  email.SendMail("bob@foo.com", "Hello World", isBodyHtml: true);

This will allow consuming code to only pass 3 arguments for succinctness but still invoke the appropriate overload since the IL generated in that instance will be equivalent to this:

   1:  email.SendMail("bob@foo.com", "Hello World", true, true);

Overall, it’s by no means an earth shattering feature that is being added to the language in stand-alone scenarios (though it will be have a *much* bigger impact in COM Interop).  Used in the correct scenarios, it can improve your code.


Tuesday, February 03, 2009 #

These days it is absolutely essential to have solid communication and presentation skills as a developer. This will serve you well whether you are presenting at conferences and users groups or professionally on a day-to-day basis communicating with managers and colleagues. I’ve given many presentations at developer user groups and code camps and I’m always looking for little ways to improve my presentations. Recently I picked up a copy of The Exceptional Presenter by Timothy Koegel and it was a great book and a fast read. One of the sections in the book is entitled “Eliminate Verbal Graffiti” where Koegel discusses the importance of eliminating fillers such as “um”, “like”, “you know”, “I mean”, “so”, “uh”, etc. Among his recommendations for eliminating these are to pay attention to other people’s fillers, practice eliminating fillers during every day conversation, and to record yourself during a presentation and listen to the play back of yourself (yikes!).

Recently I recorded a developer screen cast on C# 3.0 so I figured I would use the opportunity to listen to myself in an attempt to identify (and eliminate) my own personal verbal graffiti.  While I was dreading the thought of having to listen to my own voice recorded, I figured it wouldn’t be too bad because I’m generally *ok* with not using “um” all over the place. OH, the misery! The only good news in the ordeal was that yes, in fact, I did a decent job not using “um” a ton of times.  Unfortunately, the rest didn’t go as smoothly.  Within the first 2 minutes I heard myself use the word “so” multiple times. Once you’re really paying attention to yourself, it can become a little brutal.

The most helpful suggestion for deadening the pain came from my wife who suggested inventing the “so” drinking game.  My wife: “Just take a drink every time you hear yourself say that word “so” – it will be fun!”  Hmm, sounds to me like there wouldn’t be too fine a line between “fun” and inappropriately fast inebriation.  So she moved to her next suggestion: “OK, next time you give a presentation at a user group, I’ll come and sit in the audience. You can wear the electric dog collar and every time I hear you say “so” I’ll give you an electric shock so that you can eliminate this from your lexicon.”  Hmm, again.  Some nagging feeling in the back of my mind is telling me my wife might take pleasure in “helping” me get over my issue just a little too much.

I think I’ll stick to the suggestions that Koegel puts forth in his book – I highly recommend this book to anyone looking to improve their presentation skills.


Tuesday, January 27, 2009 #

The Enterprise Library Validation Application Block (VAB) is a great library for putting your validation in your business layer where it belongs rather than in the UI. It allows us to apply attributes to the properties of our business objects like this:

   1:  public class Person
   2:  {
   3:      [StringLengthValidator(1, 20, MessageTemplate="First Name must be between 1-20 characters.")]
   4:      public string FirstName { get; set; }
   5:   
   6:      [StringLengthValidator(1, 20, MessageTemplate="Last Name must be between 1-20 characters.")]
   7:      public string LastName { get; set; }
   8:  }

But are you unit testing your validation code properly? Consider this test method:

   1:  [TestMethod]
   2:  public void Person_Validation_Test()
   3:  {
   4:      var person = new Person();
   5:      person.FirstName = "Bill";
   6:      person.LastName = "Gates";
   7:   
   8:      // Verify person is valid
   9:      var validationResults = Validation.Validate(person);
  10:      Assert.IsTrue(validationResults.IsValid, "Person should be valid.");
  11:   
  12:      // Now make first name invalid
  13:      person.FirstName = string.Empty;
  14:      validationResults = Validation.Validate(person);
  15:      Assert.IsFalse(validationResults.IsValid, "Validation failed. FirstName should have been invalid.");
  16:   
  17:      // Now make last name invalid
  18:      person.FirstName = "Bill";
  19:      person.LastName = string.Empty;
  20:      validationResults = Validation.Validate(person);
  21:      Assert.IsFalse(validationResults.IsValid, "Validation failed. LastName should have been invalid.");
  22:  }

At first glance, this test method might look ok. It tests the person to make sure it’s valid; it then makes FirstName invalid and then tests it; it then makes LastName invalid (while setting FirstName back to normal) and then tests it, etc.  But actually, there is a long list of things that are *wrong* with that test method – do *not* unit test this way. 

First off, a good unit test should only test ONE thing at a time.  In other words, you should have a test method for the FirstName property, another for the LastName property, etc.  In fact, you could have a test method for FirstName being string.Empty, another test method proving that FirstName is invalid when it is over 20 characters, etc.  Additionally, trying to “reset” the FirstName property back to normal before testing the LastName validation is just asking for trouble.  A test method constructed in this way is going to get monolithic and ultimately you’re going to forget to “reset” properly.  Additionally, you want to strive for DRY (Don’t Repeat Yourself) in your unit tests and how many times do you want to “reset” various properties back to “normal”?

If that wasn’t enough, there is something even more harrowing with this test.  That is: after FirstName is set to string.Empty and validity checked for, how do we *know* that the FirstName property is the thing that is causing this object to be invalid?  Sure, it looks obvious from the method but it’s not explicit and it’s uncertain. What if setting the FirstName property actually made some composite validator invalid but the FirstName itself was perfectly valid?  What if, when we got to the LastName validation, we didn’t remember to properly “reset” the FirstName property and we’re asserting LastName is invalid where it was really the FirstName test that came before it that was making it invalid? There are just too many opportunities to make mistakes.  To simplify all of this, the unit tests can be re-written like this:

   1:  [TestMethod]
   2:  public void Person_FirstName_Is_Invalid()
   3:  {
   4:      var person = CreateValidPerson();
   5:      person.FirstName = string.Empty;
   6:      person.AssertWithKey("FirstName");
   7:  }
   8:   
   9:  [TestMethod]
  10:  public void Person_LastName_Is_Invalid()
  11:  {
  12:      var person = CreateValidPerson();
  13:      person.LastName = string.Empty;
  14:      person.AssertWithKey("LastName");
  15:  }
  16:   
  17:  public static Person CreateValidPerson()
  18:  {
  19:      var person = new Person();
  20:      person.FirstName = "Bill";
  21:      person.LastName = "Gates";
  22:   
  23:      ValidationResults validationResults = Validation.Validate(person);
  24:      Assert.IsTrue(validationResults.IsValid, "Person should be valid.");
  25:      return person;
  26:  }

Notice that each test method is testing only one property (you can fill in additional test methods to ensure it’s invalid when over 20 characters, etc.).  Additionally, each test starts from a known, valid state by re-using the static CreateValidPerson() method (which, inside, Asserts that it is, in fact, valid).  Most importantly, for each test, it uses the AssertWithKey() method to ensure that the *reason* it is invalid is, in fact, the property we’re interested in.  This AssertWithKey() is a simple extension method:

   1:  public static void AssertWithKey<T>(this T target, string keyToCheck)
   2:  {
   3:      ValidationResults validationResults = Validation.Validate(target);
   4:      ValidationResult result = validationResults.FirstOrDefault(r => r.Key == keyToCheck);
   5:      Assert.IsNotNull(result, "Validation Failed. {0} should have been invalid.", keyToCheck);
   6:  }

Notice the use of the FirstOrDefault() extension method.  The ValidationResults returned from the Validate() method is a collection which we can inspect to ensure that the key (the key is the property name) is tied to the validation result we are looking for and expecting – thus, ensuring that the test is in fact invalid *because* of the specific property we’re testing.

The above code was written for MSTest but can be easily adapted to NUnit, xUnit, or your unit testing framework of choice.