Steve Michelotti

A .NET Developer's Toolbox

  Home  |   Contact  |   Syndication    |   Login
  146 Posts | 1 Stories | 634 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, August 26, 2010 #

Thanks to everyone who attended my MVC 2 presentation last night at DC DNUG. I was very impressed with this new user group. We had a good turn out and got good questions from the participants. The code and PowerPoint from the presentation can be downloaded here.


Monday, August 23, 2010 #

Wednesday night (8/25/2010) I will be presenting Top 10 Ways MVC 2 Will Boost Your Productivity at DC DNUG. This is a brand new user group that just started a couple of months ago and it will be my first time there. I hope to see you there!


Saturday, August 21, 2010 #

While Microsoft continues to add features to WCF with each version, they are also adding features that simplify working with WCF services as well. Historically WCF has been somewhat intimidating to the uninitiated because of the non-trivial configuration for endpoints including behaviors, bindings, and much more. For this reason, a lot of people stayed with “old school” asmx web services. With the new features of WCF 4, you can build powerful web services with *no* svc file and *no* endpoint configuration.

Building a RESTful WCF service in this way is quite easy and you don’t need rely on any item templates.  Just start with a blank asp.net web application project in Visual Studio. The web.config file is virtually empty:

   1:  <configuration>
   2:      <system.web>
   3:          <compilation debug="true" targetFramework="4.0" />
   4:      </system.web>
   5:  </configuration>

Next just add a regular C# class - for this example, I call mine PersonService and it will have basic CRUD operations. Typically we create interfaces in WCF to define our ServiceContract and operations like this:

   1:  [ServiceContract]
   2:  interface IPersonService
   3:  {
   4:      [OperationContract]
   5:      Person GetPerson(string id);
   6:   
   7:      [OperationContract]
   8:      Person InsertPerson(Person person);
   9:   
  10:      [OperationContract]
  11:      Person UpdatePerson(string id, Person person);
  12:   
  13:      [OperationContract]
  14:      void DeletePerson(string id);
  15:  }

Keep in mind, this step is *not* required. You *could* decorate your service class directly with these attributes and not even have the interface at all. However, in this case, it’s a nice convenience to encapsulate all the WCF attributes on the interface rather than your implementation class. The implementation of our PersonService class looks like this (I’ve removed the code that access the data store for brevity):

   1:  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
   2:  public class PersonService : IPersonService
   3:  {
   4:      [WebGet(UriTemplate = "Person({id})")]
   5:      public Person GetPerson(string id)
   6:      {
   7:      }
   8:   
   9:      [WebInvoke(UriTemplate = "Person", Method = "POST")]
  10:      public Person InsertPerson(Person person)
  11:      {
  12:      }
  13:   
  14:      [WebInvoke(UriTemplate = "Person({id})", Method = "PUT")]
  15:      public Person UpdatePerson(string id, Person person)
  16:      {
  17:      }
  18:   
  19:      [WebInvoke(UriTemplate = "Person({id})", Method = "DELETE")]
  20:      public void DeletePerson(string id)
  21:      {
  22:      }
  23:  }

This is just a normal C# class that implement an interface. It’s also decorated with the typical WebGet/WebInvoke attributes (in the System.ServiceModel.Web namespace) that we use for RESTful services. Also notice that 3 of the 4 methods have the same UriTemplate but they are differentiated by the HTTP method (i.e., GET/PUT/DELETE). Also notice the AspNetCompatibilityRequirements attribute – this is needed for RESTful services that are processed in the ASP.NET pipeline as described here. You also have to add this to the config file (I know, I know – I said “no config” but I meant “no ugly WCF endpoint config”!):

   1:  <system.serviceModel>
   2:    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   3:  </system.serviceModel>

So how do we take this regular C# class and make it into a service without an *.svc file?  The System.Web.Routing infrastructure has now been incorporated into WCF 4 to make this possible.  Just add the line of code (line #5) to your global.asax:

   1:  public class Global : System.Web.HttpApplication
   2:  {
   3:      protected void Application_Start(object sender, EventArgs e)
   4:      {
   5:          RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(PersonService)));
   6:      }
   7:  }

The WebServiceHostFactory makes RESTful services possible in WCF. The first parameter of my ServiceRoute constructor is an empty string which means that my URI of my service will hang right off of the root – this get combined with the UriTemplate defined in the WebGet/WebInvoke attributes.  So to get a person from my service, a URI would look like this:  http://mydomain.com/Person(21).  If I had specified “foo” instead of an empty string in the first parameters of the ServiceRoute constructor, then my URI would look like this:  http://mydomain.cmo/foo/Person(21).

That’s it!  You now have a fully functioning RESTful WCF service that you can fully test with Fidder for all HTTP verbs.

One interesting aspect to all this is that you can do all this in MVC as well. In fact, I typically do use MVC to return JSON to views for AJAX calls in my MVC apps. However, if you were building stand-alone services for this, would MVC be easier than the example of above? Keep in mind, we could simplify the example above even further by eliminating the IPersonService interface all together. I daresay that setting up RESTful routes like the ones shown above is easier with WCF than MVC (this, coming from an “MVC guy”) because we can apply the UriTemplates directly to the methods. To accomplish the same in MVC, you have to create custom route constraints to avoid the name of the C# methods from showing up in the URL (and honoring the REST HTTP verbs).  If you are going to do this, I really like the approach shown here. It’s a cool approach, but it’s *more* work than just doing it with RESTful WCF – no svc file and no configuration.

In fact, using the WCF infrastructure gets you even more features for free.  For example, if we add 1 more line of configuration (check out line #5 below) we get a help page and automatic format selection for free! Now our entire configuration just looks like this (and still no WCF endpoint configuration needed):

   1:  <system.serviceModel>
   2:    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   3:    <standardEndpoints>
   4:      <webHttpEndpoint>
   5:        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
   6:      </webHttpEndpoint>
   7:    </standardEndpoints>
   8:  </system.serviceModel>

Notice all we had to do to get the help page was the request “/help”:

wcf help page

The automatic format selection in WCF will honor the Accept header and/or the Content-type header and return XML, JSON, etc. to the caller based on the value specified in the header. Again, that takes custom code in MVC which you get for free in WCF.


Friday, August 06, 2010 #

Generics are nothing new and have been part of .NET for over 5 years. Reference types and value types are core concepts in the CLR type system and these concepts have been the same since .NET was released – they are also nothing new. However, when I ask about these concepts during interviews, I often get a wide range in quality of the answers to these questions. If you get asked about these topics in an interview, be prepared to give great answers! You don’t have to give a textbook perfect memorized definition – but make sure you show that you fully understand and can apply the concepts to real-world development.

Question: why are generics such a big deal? I typically get answers discussing greater type safety and better performance. OK, the type safety one is pretty easy and straightforward. We had the ArrayList in .NET 1:

   1:  ArrayList list = new ArrayList();
   2:  list.Add(1);
   3:  list.Add(2);
   4:  list.Add("hello"); // compiler doesn't help me avoid!

When generics were introduced, we could declare a strongly-typed list of int’s to avoid this:

   1:  List<int> list = new List<int>();
   2:  list.Add(1);
   3:  list.Add(2);
   4:  list.Add("hello"); // compiler error!

So drilling into the second answer a little - *why* is performance better with generics? Often I hear, “you can avoid boxing and unboxing.”  OK great!  So what *specifically* is boxing and unboxing? (This is where people often start to struggle.)  Boxing is the act of converting a value type to a reference type. If we look at line #2 of the first code sample above, we’re putting an Int32 (a value type) into an ArrayList which stores everything as System.Object (a reference type). Therefore, unboxing is the act of converting a reference type to a value type (e.g., if we were taking an item out of the ArrayList and having to cast: int num = (int)list[0];). So with boxing/unboxing, don’t focus on casting or sub-classes (they’re not directly relevant!) – focus on converting from reference types and values types.

Question: what’s the difference between a reference type and a value type? Just focus on the basics: Reference types are stored in the heap (which means they are garbage collected) and value types are stored in the stack (cannot be allocated on the GC heap). Reference types can be null; value types cannot be null. Reference type variables do not contain the value – it has a pointer to its value. A value type variable contains the value itself.

Question: how do you know if a type is a reference type or a value type? Is a DateTime a reference type or a value type? A String? If you’re creating your own Person data structure, how can you control whether it’s a value type or a reference type? The short answer: a “class” is a reference type and a “struct” is a value type. If you “View Definition” in Visual Studio on a DateTime, for example, you’ll see:

datetime

DateTime is a struct so it’s a value type. System.String is a class so it’s a reference type (plus, the fact that it can be null is also a tip off that it’s a reference type). So if you create your own data structure as a class, it will be a reference type (as a struct, a value type).

For further reading on reference types, value types, and boxing/unboxing, have a look at this article by Jeffrey Richter written in December 2000. These are core concepts in the .NET type system that are still just as relevant today as they were 10 years ago.

Let’s circle back to our original generics performance question. So far we have 3 assertions:

  • Generics result in better performance because you can avoid boxing/unboxing
  • Boxing/unboxing is the act of converting between reference types and value types
  • A “struct” is a value type (e.g., DateTime); a “class” is a reference type (e.g., String)

Question: given all three of these assertions, is performance *really* better with a generic List<string> (string being a reference type) versus a non-generic list of strings? Answer: NO! Generics still provide *plenty* of benefit for these situations in terms of type-safety and allowing us to reduce noise in our code by avoiding having to cast objects (or code-gen objects if we want strongly-typed objects) – but a performance benefit is *not* on the list. However, if we’re talking about List<int> or List<DateTime> (value types) then here is a significant performance improvement. Not only is the run-time performance benefit significantly better because we can avoid the expensive boxing/unboxing operations, but we also avoid making the GC do extra work by having to collect these boxed objects that were just heap-based wrappers around what were originally value types.

In fact, let’s say you use 5 different generic List<T> in your application: List<string>, List<int>, List<DateTime>, List<Foo>, List<Bar> (where Foo and Bar are both reference types).  What happens behind the scenes is that the JIT will actually produce 3 versions of the generic list.  For each value type it will generate a totally strongly-typed version (so we’ll have 1 for List<int> and 1 for List<DateTime>). Then it will generate a single generic List<T> whose type gets re-used for all reference types behind the scenes (so it will get used for List<string>, List<Foo>, List<Bar>). But it is providing you the type-safety features along with allowing you to avoid all of the ugly casting in your code.

New .NET technologies come and go and as professional developers we are constantly working to learn and stay up-to-date on these new technologies. However, we also have to make sure we stay grounded in the fundamentals that .NET is based on. If you ever end up in an interview with me, I trust that you’ll ace these questions. :)  And, by the way, my company is hiring so if you’re interested, please contact me!


Wednesday, July 07, 2010 #

When MVC 2 was released, there was a last minute change to use Model Validation instead of Input Validation. Essentially, Model validation means that your entire view model will be validated regardless of which values actually got posted to the server. On the other hand, with Input validation, only the values that get posted to the server will get validated. While this was the right decision by the MVC team for the most mainstream cases, there are still some cases where the previous behavior of Input validation would be more convenient. A workaround to enable Input validation-like behavior is presented in this post by Steve Sanderson. Keep in mind that this is just validation on view models and not on domain models. For domain models you still want model validation so that there is no security risk by a user bypassing your validations by tampering with what gets posted back to the server – but validation for view models is facilitating a good end-user experience.

My team is currently developing a UI that has many dynamic controls depending on the user’s previous answers and could benefit from Input validation. We found that, while Sanderson’s solution worked great for the server-side, we were still left with no client-side validation. My team’s initial solution is presented here by Sajad Deyargaroo. In my post here I will walkthrough an end to end scenario. First, let’s consider this scenario – a user is filling out an interview to purchase insurance for their car and one of the questions they get asked is how they will be using the vehicle:

 int1

Based on the answer to that question, they would get presented with other controls that are relevant to the answer they just gave. For example, if the user says they are using it to “Commute”, then we must dynamically show a couple of other textboxes to collect information about their commute:

 int2

If they select “Business”, then we must collect the type of business:

 int3

and if they select “Pleasure”, then no other contextual information is needed:

 int4

In this case, we just want to use simple client-side jQuery to show/hide controls when the user selects a value from the dropdown without an additional round trip to the server. Additionally, we obviously want to have validation (with the normal Data Annotations attributes) but *only* if the fields are actually displayed. For example, if the user selects “Commute” then the fields related to the commute must be validated since they are visible – but we should *not* validate the other textboxes (e.g,. type of business) because they are not required if they are not visible.

int5

The view model is still leveraging the normal Data Annotation attributes:

   1:  public class InterviewViewModel
   2:  {
   3:      [DisplayName("Primary use of vehicle")]
   4:      [Required(ErrorMessage =  "You must select vehicle use.")]
   5:      public int VehicleUse { get; set; }
   6:   
   7:      public IEnumerable<SelectListItem> VehicleUseList { get; set; }
   8:   
   9:      [DisplayName("Type of business")]
  10:      [Required(ErrorMessage = "Type of business is required.")]
  11:      public string BusinessType { get; set; }
  12:   
  13:      [DisplayName("Days driven to work (1-5)")]
  14:      [Required(ErrorMessage = "Number of days driven to work is required.")]
  15:      public int? DaysCommute { get; set; }
  16:   
  17:      [DisplayName("Miles driven to work")]
  18:      [Required(ErrorMessage = "Miles driven to work is required.")]
  19:      public int? CommuteMiles { get; set; }
  20:  }

By creating a custom model binder that performs input validation (based on Sanderson’s post where he uses an Action filter), we had our solution to the problem for server-side validation.

   1:  public class InputValidationModelBinder : DefaultModelBinder
   2:  {
   3:      protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
   4:      {
   5:          var modelState = controllerContext.Controller.ViewData.ModelState;
   6:          var valueProvider = controllerContext.Controller.ValueProvider;
   7:   
   8:          var keysWithNoIncomingValue = modelState.Keys.Where(x => !valueProvider.ContainsPrefix(x));
   9:          foreach (var key in keysWithNoIncomingValue)
  10:              modelState[key].Errors.Clear();
  11:      }
  12:  }

Let’s look at the mark up for the page:

   1:  <h2>Interview</h2>
   2:  <% using (Html.BeginForm()) { %>
   3:      <fieldset>
   4:          <div>
   5:              <%:Html.LabelFor(m => m.VehicleUse) %>
   6:              <%:Html.DropDownListFor(m => m.VehicleUse, Model.VehicleUseList) %>
   7:              <%:Html.ValidationMessageFor(m => m.VehicleUse)%>
   8:          </div>
   9:          <div id="businessTypeDiv">
  10:              <%:Html.LabelFor(m => m.BusinessType) %>
  11:              <%:Html.EditorFor(m => m.BusinessType) %>
  12:              <%:Html.ValidationMessageFor(m => m.BusinessType) %>
  13:          </div>
  14:          <div id="commuteDiv">
  15:              <div>
  16:                  <%:Html.LabelFor(m => m.DaysCommute) %>
  17:                  <%:Html.EditorFor(m => m.DaysCommute)%>
  18:                  <%:Html.ValidationMessageFor(m => m.DaysCommute)%>
  19:              </div>
  20:              <div>
  21:                  <%:Html.LabelFor(m => m.CommuteMiles) %>
  22:                  <%:Html.EditorFor(m => m.CommuteMiles)%>
  23:                  <%:Html.ValidationMessageFor(m => m.CommuteMiles)%>
  24:              </div>
  25:          </div>
  26:      </fieldset>
  27:      <input type="submit" value="Save" />
  28:  <% } %>

This displays all of the required HTML that we need.  We also have a section of jQuery will handles the showing/hiding of elements based on the section of the VehicleUse dropdown:

   1:  <script type="text/javascript">
   2:      $(function () {
   3:          $.fn.enable = function () {
   4:              return this.show().removeAttr("disabled");
   5:          }
   6:   
   7:          $.fn.disable = function () {
   8:              return this.hide().attr("disabled", "disabled");
   9:          }
  10:   
  11:          var vehicleUse = $("#VehicleUse");
  12:          var businessTypeSection = $("#businessTypeDiv,#businessTypeDiv input");
  13:          var commuteSection = $("#commuteDiv,#commuteDiv input");
  14:          setControls();
  15:   
  16:          vehicleUse.change(function () {
  17:              setControls();
  18:          });
  19:   
  20:          function setControls() {
  21:              switch (vehicleUse.val()) {
  22:                  case "1": //commuteSection
  23:                      commuteSection.enable();
  24:                      businessTypeSection.disable();
  25:                      break;
  26:                  case "2": //Pleasure
  27:                  case "":
  28:                      commuteSection.disable();
  29:                      businessTypeSection.disable();
  30:                      break;
  31:                  case "3": //Business
  32:                      businessTypeSection.enable();
  33:                      commuteSection.disable();
  34:                      break;
  35:              }
  36:          }
  37:      });
  38:  </script>

Notice that in addition to showing/hiding the controls, we also enable/disable the controls by setting the “disabled” attribute. Setting the disabled attribute will prevent the element from being posted to the server on the form submission. When the user selects the “Commute” option i the dropdown, for example, we will fall into case “1” on line 22 – this will enable/show all the elements inside the <div id=”commuteDiv”> and it will disable/hide all the elements inside the <div id=”businessTypeDiv”>.

This all works great when *only* server-side validation is enabled with our custom model binder that does input validation. However, when we add:

   1:  <% Html.EnableClientValidation(); %>

this prevents the form from being submitted! The OOTB Microsoft JavaScript library is performing validation on *all* controls regardless of whether the controls are enabled or not.

Microsoft’s JavaScript files are actually produced from C# by using Script#. If you look at the solution for MVC you will see this:

mvc-solution

The 2 projects highlighted above produce these JavaScript files which are ultimately embedded in your project when you do “File – New – MVC Web Application” inside Visual Studio:

scriptsfolder

Notice there is a *.debug.js version produced for each one. The debug version is human readable and the non-debug version is minified (e.g., whitespace is removed, variable names are shortened, etc.). Inside the MicrosoftMvcValidationScript project there is a class called FormContext which has a Validate() method. We can modify this method by adding a single IF statement (on line #9 below) to only perform validation IF the field is not disabled:

   1:  public string[] Validate(string eventName) {
   2:      FieldContext[] fields = Fields;
   3:      ArrayList errors = new ArrayList();
   4:   
   5:      for (int i = 0; i < fields.Length; i++) {
   6:          FieldContext field = fields[i];
   7:          
   8:          // validate only enabled fields
   9:          if (!field.Elements[0].Disabled)
  10:          {
  11:              string[] thisErrors = field.Validate(eventName);
  12:              if (thisErrors != null)
  13:              {
  14:                  ArrayList.AddRange(errors, thisErrors);
  15:              }
  16:          }
  17:      }
  18:   
  19:      if (ReplaceValidationSummary) {
  20:          ClearErrors();
  21:          AddErrors((string[])errors);
  22:      }
  23:   
  24:      return (string[])errors;
  25:  }

Once we build the project, it will produce new versions of MicrosoftMvcValidation.js and MicrosoftMvcValidation.debug.js which we can then copy into our solution to replace the original versions.  Now our scenario works end-to-end and now *includes* client-side validation behavior in the way we expect. Our form is no longer prevented from being posted to the server due to the hidden/disabled fields not having a value.

The complete solution for this can be downloaded here.


Wednesday, June 23, 2010 #

When setting up my AppFabric environment yesterday, I was running into (what I thought) was a strange error:

Workflow persistence is not fully functional because the net.pipe protocol is missing from the application’s list of enabled protocols.

 

 

At first, I was quite confused by this. I had double-checked to make sure that net.pipe *was* enabled.  First I checked the Site Bindings for the web site itself:

 

Next, I check the Enabled protocols by going to “Advanced Settings” at the application level. Sure enough, I had previously added “net.pipe” in the comma separated list:

 

 

After a few minutes of beating my head against the wall, it occurred to me that IIS might be picky with *how* the Enabled Protocols is formatted.  Sure enough, the problem is that I did not realize I had a {space} after the comma.  I had “http, net.pipe” when I should have had “http,net.pipe”. Once I removed the space, everything was resolved:


Monday, June 14, 2010 #

MVC 2 includes an attribute for model metadata called the HiddenInput attribute. The typical usage of the attribute looks like this (line #3 below):

   1:  public class PersonViewModel
   2:  {
   3:      [HiddenInput(DisplayValue = false)]
   4:      public int? Id { get; set; }
   5:      public string FirstName { get; set; }
   6:      public string LastName { get; set; }
   7:  }

So if you displayed your PersonViewModel with Html.EditorForModel() or Html.EditorFor(m => m.Id), the framework would detect the [HiddenInput] attribute metadata and produce HTML like this:

   1:  <input id="Id" name="Id" type="hidden" value="21" />

This is pretty straight forward and allows an elegant way to keep the technical key for your model (e.g., a Primary Key from the database) in the HTML so that everything will be wired up correctly when the form is posted to the server and of course not displaying this value visually to the end user. However, when I was giving a recent presentation, a member of the audience asked me (quite reasonably), “When would you ever set DisplayValue equal to true when using a HiddenInput?” To which I responded, “Well, it’s an edge case. There are sometimes when…er…um…people might want to…um…display this value to the user.” It was quickly apparent to me (and I’m sure everyone else in the room) what a terrible answer this was. I realized I needed to have a much better answer here.

First off, let’s look at what is produced if we change our view model to use “true” (which is equivalent to use specifying [HiddenInput] since “true” is the default) on line #3:

   1:  public class PersonViewModel
   2:  {
   3:      [HiddenInput(DisplayValue = true)]
   4:      public int? Id { get; set; }
   5:      public string FirstName { get; set; }
   6:      public string LastName { get; set; }
   7:  }

Will produce the following HTML if rendered from Htm.EditorForModel() in your view:

   1:  <div class="editor-label">
   2:      <label for="Id">Id</label>
   3:  </div>
   4:  <div class="editor-field">
   5:      21<input id="Id" name="Id" type="hidden" value="21" /> 
   6:      <span class="field-validation-valid" id="Id_validationMessage"></span>
   7:  </div>

The key is line #5. We get the text of “21” (which happened to be my DB Id in this instance) and also a hidden input element (again with “21”).

So the question is, why would one want to use this? The best answer I’ve found is contained in this MVC 2 whitepaper:

When a view lets users edit the ID of an object and it is necessary to display the value as well as to provide a hidden input element that contains the old ID so that it can be passed back to the controller.

Well, that actually makes sense. Yes, it seems like something that would happen *rarely* but, for those instances, it would enable them easily. It’s effectively equivalent to doing this in your view:

   1:  <%: Html.LabelFor(m => m.Id) %>
   2:  <%: Model.Id %>
   3:  <%: Html.HiddenFor(m => m.Id) %>

But it’s allowing you to specify it in metadata on your view model (and thereby take advantage of templated helpers like Html.EditorForModel() and Html.EditorFor()) rather than having to explicitly specifying everything in your view.


Sunday, June 13, 2010 #

In my presentation this past weekend at NoVa Code Camp, a member of the audience caught my final demo on video. In this demo, I combine multiple new features from MVC 2 to show how to build apps quickly with MVC 2. These features include:

  • Template Helpers / Editor Templates
  • Server-side/Client-side Validation
  • Model Metadata for View Model
  • HTML Encoding Syntax
  • Dependency Injection
  • Abstract Controllers
  • Custom T4 Templates
  • Custom MVC Visual Studio 2010 Code Snippets

The projector screen is a little difficult to see during parts of the video – a video of the direct screencast can be seen here: MVC 2 in 2 Minutes.

 

Direct link to YouTube video here.


Thanks to everyone who attended my MVC 2 presentation at NOVA Code Camp. The code samples and PowerPoint can be downloaded here: Top 10 Ways MVC 2 Will Boost Your Productivity.


Thursday, June 10, 2010 #

Microsoft just released the Visual Studio 2010 Pro Power Tools extension and it is awesome. A summary of all the features can be found here and it is available in the Visual Studio Gallery here. There are a bunch of great features but, in my opinion, the best one is the replacement for the Add Reference dialog. This gives sub-string search capabilities as well as the ability to add multiple references without having to continually re-open the dialog. For this feature alone, you should install the Pro Power Tools right now. There are a few blogs posts that do a good job describing all the features but what I wanted to do here was to post a quick screencast (7 minutes) that shows the features that I think are really cool. I show most (but not all) of the features focusing on the ones I think are the best. The features I cover are:

  • Installation with the Extension Manager
  • Add Reference Dialog replacement
  • Tab Well including pinned tabs, pinned tabs in second row, fixed close button, colorized tabs, dirty indicator
  • Highlight current line
  • Triple Click for full-line selection
  • Ctrl + Click for Go To Definition
  • Colorized Parameter Help

Enjoy!

(Right-click and Zoom to view in full screen)


Wednesday, June 02, 2010 #

ILMerge is a utility which allows you the merge multiple .NET assemblies into a single binary assembly more for convenient distribution. Recently we ran into problems when attempting to use ILMerge on a .NET 4 project. We received the error message:

An exception occurred during merging:
Unresolved assembly reference not allowed: System.Core.
    at System.Compiler.Ir2md.GetAssemblyRefIndex(AssemblyNode assembly)
    at System.Compiler.Ir2md.GetTypeRefIndex(TypeNode type)
    at System.Compiler.Ir2md.VisitReferencedType(TypeNode type)
    at System.Compiler.Ir2md.GetMemberRefIndex(Member m)
    at System.Compiler.Ir2md.PopulateCustomAttributeTable()
    at System.Compiler.Ir2md.SetupMetadataWriter(String debugSymbolsLocation)
    at System.Compiler.Ir2md.WritePE(Module module, String debugSymbolsLocation, BinaryWriter writer)
    at System.Compiler.Writer.WritePE(String location, Boolean writeDebugSymbols, Module module, Boolean delaySign, String keyFileName, String keyName)
    at System.Compiler.Writer.WritePE(CompilerParameters compilerParameters, Module module)
    at ILMerging.ILMerge.Merge()
    at ILMerging.ILMerge.Main(String[] args)

It turns out that this issue is caused by ILMerge.exe not being able to find the .NET 4 framework by default. The answer was ultimately found here. You either have to use the /lib option to point to your .NET 4 framework directory (e.g., “C:\Windows\Microsoft.NET\Framework\v4.0.30319” or “C:\Windows\Microsoft.NET\Framework64\v4.0.30319”) or just use an ILMerge.exe.config file that looks like this:

   1:  <configuration>
   2:      <startup useLegacyV2RuntimeActivationPolicy="true">
   3:          <requiredRuntime safemode="true" imageVersion="v4.0.30319" version="v4.0.30319"/>
   4:      </startup>
   5:  </configuration>

This was able to successfully resolve my issue.


Wednesday, May 26, 2010 #

A while back I blogged about how to create an HTML Helper to produce a radio button list.  In that post, my HTML helper was “wrapping” the FluentHtml library from MvcContrib to produce the following html output (given an IEnumerable list containing the items “Foo” and “Bar”):

   1:  <div>
   2:      <input id="Name_Foo" name="Name" type="radio" value="Foo" /><label for="Name_Foo" id="Name_Foo_Label">Foo</label>
   3:      <input id="Name_Bar" name="Name" type="radio" value="Bar" /><label for="Name_Bar" id="Name_Bar_Label">Bar</label>
   4:  </div>

With the release of MVC 2, we now have editor templates we can use that rely on metadata to allow us to customize our views appropriately.  For example, for the radio buttons above, we want the “id” attribute to be differentiated and unique and we want the “name” attribute to be the same across radio buttons so the buttons will be grouped together and so model binding will work appropriately. We also want the “for” attribute in the <label> element being set to correctly point to the id of the corresponding radio button.  The default behavior of the RadioButtonFor() method that comes OOTB with MVC produces the same value for the “id” and “name” attributes so this isn’t exactly what I want out the the box if I’m trying to produce the HTML mark up above.

If we use an EditorTemplate, the first gotcha that we run into is that, by default, the templates just work on your view model’s property. But in this case, we *also* was the list of items to populate all the radio buttons. It turns out that the EditorFor() methods do give you a way to pass in additional data. There is an overload of the EditorFor() method where the last parameter allows you to pass an anonymous object for “extra” data that you can use in your view – it gets put on the view data dictionary:

   1:  <%: Html.EditorFor(m => m.Name, "RadioButtonList", new { selectList = new SelectList(new[] { "Foo", "Bar" }) })%>

Now we can create a file called RadioButtonList.ascx that looks like this:

   1:  <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
   2:  <%
   3:      var list = this.ViewData["selectList"] as SelectList;
   4:  %>
   5:  <div>
   6:      <% foreach (var item in list) {
   7:             var radioId = ViewData.TemplateInfo.GetFullHtmlFieldId(item.Value);
   8:             var checkedAttr = item.Selected ? "checked=\"checked\"" : string.Empty;
   9:      %>
  10:          <input type="radio" id="<%: radioId %>" name="<%: ViewData.TemplateInfo.HtmlFieldPrefix %>" value="<%: item.Value %>" <%: checkedAttr %>/>
  11:          <label for="<%: radioId %>"><%: item.Text %></label>
  12:      <% } %>
  13:  </div>

There are several things to note about the code above. First, you can see in line #3, it’s getting the SelectList out of the view data dictionary. Then on line #7 it uses the GetFullHtmlFieldId() method from the TemplateInfo class to ensure we get unique IDs. We pass the Value to this method so that it will produce IDs like “Name_Foo” and “Name_Bar” rather than just “Name” which is our property name. However, for the “name” attribute (on line #10) we can just use the normal HtmlFieldPrefix property so that we ensure all radio buttons have the same name which corresponds to the view model’s property name. We also get to leverage the fact the a SelectListItem has a Boolean Selected property so we can set the checkedAttr variable on line #8 and use it on line #10. Finally, it’s trivial to set the correct “for” attribute for the <label> on line #11 since we already produced that value.

Because the TemplateInfo class provides all the metadata for our view, we’re able to produce this view that is widely re-usable across our application. In fact, we can create a couple HTML helpers to better encapsulate this call and make it more user friendly:

   1:  public static MvcHtmlString RadioButtonList<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, params string[] items)
   2:  {
   3:      return htmlHelper.RadioButtonList(expression, new SelectList(items));
   4:  }
   5:   
   6:  public static MvcHtmlString RadioButtonList<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> items)
   7:  {
   8:      var func = expression.Compile();
   9:      var result = func(htmlHelper.ViewData.Model);
  10:      var list = new SelectList(items, "Value", "Text", result);
  11:      return htmlHelper.EditorFor(expression, "RadioButtonList", new { selectList = list });
  12:  }

This allows us to simply the call like this:

   1:  <%: Html.RadioButtonList(m => m.Name, "Foo", "Bar" ) %>

In that example, the values for the radio button are hard-coded and being passed in directly. But if you had a view model that contained a property for the collection of items you could call the second overload like this:

   1:  <%: Html.RadioButtonList(m => m.Name, Model.FooBarList ) %>

The Editor templates introduced in MVC 2 definitely allow for much more flexible views/editors than previously available. By knowing about the features you have available to you with the TemplateInfo class, you can take these concepts and customize your editors with extreme flexibility and re-usability.


Saturday, May 22, 2010 #

In a couple of recent Code Camps, I’ve given my presentation: Top 10 Ways MVC 2 Will Boost Your Productivity. In the presentation, I cover all major new features introduced in MVC 2 with a focus on productivity enhancements. To drive the point home, I conclude with a final demo where I build a couple of screens from scratch highlighting many (but not all) of the features previously covered in the talk. A couple of weeks ago, I was asked to make it available online so here it is. In 2 minutes the demo builds a couple screens from scratch that provide a goal setting tracker for a user.

MVC 2 features included in the video are:

  • Template Helpers / Editor Templates
  • Server-side/Client-side Validation
  • Model Metadata for View Model
  • HTML Encoding Syntax
  • Dependency Injection
  • Abstract Controllers
  • Custom T4 Templates
  • Custom MVC Visual Studio 2010 Code Snippets

The complete code samples and slide deck can be downloaded here: Top 10 Ways MVC 2 Will Boost Your Productivity.

Enjoy!

(Right-click and Zoom to view in full screen)

 

Click here for Direct link to video


Tuesday, May 18, 2010 #

Tomorrow (5/19/2010) I’ll be at BaltoMSDN presenting C# 4.0.  Also, on Saturday I’ll be presenting MVC 2 at the Richmond Code Camp.  Hope to see you there!


Monday, May 17, 2010 #

Portable Areas from MvcContrib provide a great way to build modular and composite applications on top of MVC. In short, portable areas provide a way to distribute MVC binary components as simple .NET assemblies where the aspx/ascx files are actually compiled into the assembly as embedded resources. I’ve blogged about Portable Areas in the past including this post here which talks about embedding resources and you can read more of an intro to Portable Areas here.

As great as Portable Areas are, the question that seems to come up the most is: what about MasterPages? MasterPages seems to be the one thing that doesn’t work elegantly with portable areas because you specify the MasterPage in the @Page directive and it won’t use the same mechanism of the view engine so you can’t just embed them as resources. This means that you end up referencing a MasterPage that exists in the host application but not in your portable area. If you name the ContentPlaceHolderId’s correctly, it will work – but it all seems a little fragile.

Ultimately, what I want is to be able to build a portable area as a module which has no knowledge of the host application. I want to be able to invoke the module by a full route on the user’s browser and it gets invoked and “automatically appears” inside the application’s visual chrome just like a MasterPage. So how could we accomplish this with portable areas? With this question in mind, I looked around at what other people are doing to address similar problems. Specifically, I immediately looked at how the Orchard team is handling this and I found it very compelling. Basically Orchard has its own custom layout/theme framework (utilizing a custom view engine) that allows you to build your module without any regard to the host. You simply decorate your controller with the [Themed] attribute and it will render with the outer chrome around it:

   1:  [Themed]
   2:  public class HomeController : Controller

Here is the slide from the Orchard talk at this year MIX conference which shows how it conceptually works:

orchard theme

 

It’s pretty cool stuff.  So I figure, it must not be too difficult to incorporate this into the portable areas view engine as an optional piece of functionality. In fact, I’ll even simplify it a little – rather than have 1) Document.aspx, 2) Layout.ascx, and 3) <view>.ascx (as shown in the picture above); I’ll just have the outer page be “Chrome.aspx” and then the specific view in question. The Chrome.aspx not only takes the place of the MasterPage, but now since we’re no longer constrained by the MasterPage infrastructure, we have the choice of the Chrome.aspx living in the host or inside the portable areas as another embedded resource!

Disclaimer: credit where credit is due – much of the code from this post is me re-purposing the Orchard code to suit my needs.

To avoid confusion with Orchard, I’m going to refer to my implementation (which will be based on theirs) as a Chrome rather than a Theme. The first step I’ll take is to create a ChromedAttribute which adds a flag to the current HttpContext to indicate that the controller designated Chromed like this:

   1:  [Chromed]
   2:  public class HomeController : Controller

The attribute itself is an MVC ActionFilter attribute:

   1:  public class ChromedAttribute : ActionFilterAttribute
   2:  {
   3:      public override void OnActionExecuting(ActionExecutingContext filterContext)
   4:      {
   5:          var chromedAttribute = GetChromedAttribute(filterContext.ActionDescriptor);
   6:          if (chromedAttribute != null)
   7:          {
   8:              filterContext.HttpContext.Items[typeof(ChromedAttribute)] = null;
   9:          }
  10:      }
  11:   
  12:      public static bool IsApplied(RequestContext context)
  13:      {
  14:          return context.HttpContext.Items.Contains(typeof(ChromedAttribute));
  15:      }
  16:   
  17:      private static ChromedAttribute GetChromedAttribute(ActionDescriptor descriptor)
  18:      {
  19:          return descriptor.GetCustomAttributes(typeof(ChromedAttribute), true)
  20:              .Concat(descriptor.ControllerDescriptor.GetCustomAttributes(typeof(ChromedAttribute), true))
  21:              .OfType<ChromedAttribute>()
  22:              .FirstOrDefault();
  23:      }
  24:  }

With that in place, we only have to override the FindView() method of the custom view engine with these 6 lines of code:

   1:  public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
   2:  {
   3:      if (ChromedAttribute.IsApplied(controllerContext.RequestContext))
   4:      {
   5:          var bodyView = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
   6:          var documentView = ViewEngines.Engines.FindPartialView(controllerContext, "Chrome");
   7:          var chromeView = new ChromeView(bodyView, documentView);
   8:          return new ViewEngineResult(chromeView, this);
   9:      }
  10:   
  11:      // Just execute normally without applying Chromed View Engine
  12:      return base.FindView(controllerContext, viewName, masterName, useCache);
  13:  }

If the view engine finds the [Chromed] attribute, it will invoke it’s own process – otherwise, it’ll just defer to the normal web forms view engine (with masterpages). The ChromeView’s primary job is to independently set the BodyContent on the view context so that it can be rendered at the appropriate place:

   1:  public class ChromeView : IView
   2:  {
   3:      private ViewEngineResult bodyView;
   4:      private ViewEngineResult documentView;
   5:   
   6:      public ChromeView(ViewEngineResult bodyView, ViewEngineResult documentView)
   7:      {
   8:          this.bodyView = bodyView;
   9:          this.documentView = documentView;
  10:      }
  11:   
  12:      public void Render(ViewContext viewContext, System.IO.TextWriter writer)
  13:      {
  14:          ChromeViewContext chromeViewContext = ChromeViewContext.From(viewContext);
  15:   
  16:          // First render the Body view to the BodyContent
  17:          using (var bodyViewWriter = new StringWriter())
  18:          {
  19:              var bodyViewContext = new ViewContext(viewContext, bodyView.View, viewContext.ViewData, viewContext.TempData, bodyViewWriter);
  20:              this.bodyView.View.Render(bodyViewContext, bodyViewWriter);
  21:              chromeViewContext.BodyContent = bodyViewWriter.ToString();
  22:          }
  23:          // Now render the Document view
  24:          this.documentView.View.Render(viewContext, writer);
  25:      }
  26:  }

The ChromeViewContext (code excluded here) mainly just has a string property for the “BodyContent” – but it also makes sure to put itself in the HttpContext so it’s available. Finally, we created a little extension method so the module’s view can be rendered in the appropriate place:

   1:  public static void RenderBody(this HtmlHelper htmlHelper)
   2:  {
   3:      ChromeViewContext chromeViewContext = ChromeViewContext.From(htmlHelper.ViewContext);
   4:      htmlHelper.ViewContext.Writer.Write(chromeViewContext.BodyContent);
   5:  }

At this point, the other thing left is to decide how we want to implement the Chrome.aspx page. One approach is the copy/paste the HTML from the typical Site.Master and change the main content placeholder to use the HTML helper above – this way, there are no MasterPages anywhere. Alternatively, we could even have Chrome.aspx utilize the MasterPage if we wanted (e.g., in the case where some pages are Chromed and some pages want to use traditional MasterPage):

   1:  <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
   2:  <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   3:      <% Html.RenderBody(); %>
   4:  </asp:Content>

At this point, it’s all academic. I can create a controller like this:

   1:  [Chromed]
   2:  public class WidgetController : Controller
   3:  {
   4:      public ActionResult Index()
   5:      {
   6:          return View();
   7:      }
   8:  }

Then I’ll just create Index.ascx (a partial view) and put in the text “Inside my widget”. Now when I run the app, I can request the full route (notice the controller name of “widget” in the address bar below) and the HTML from my Index.ascx will just appear where it is supposed to.

chromed page

 

This means no more warnings for missing MasterPages and no more need for your module to have knowledge of the host’s MasterPage placeholders. You have the option of using the Chrome.aspx in the host or providing your own while embedding it as an embedded resource itself.

I’m curious to know what people think of this approach. The code above was done with my own local copy of MvcContrib so it’s not currently something you can download. At this point, these are just my initial thoughts – just incorporating some ideas for Orchard into non-Orchard apps to enable building modular/composite apps more easily. Additionally, on the flip side, I still believe that Portable Areas have potential as the module packaging story for Orchard itself.

 

What do you think?