MVC – The Start

This shows my initial setup of an MVC 2 RC 2 application. Using Visual Studio 2010 RC I selected File –> New –> Project… then under Visual C#, Web, I selected the ASP.NET MVC 2 Web Application.

image

Then when I click OK I get the following dialog. Since I’m a very strong believer in Unit Tests I of course do create an associated Unit Test project.

image

The first thing I did then was to run the unit tests… there were 18. I like to know the code coverage too… So I have to create some test settings and turn on the code coverage. Right clicking on the solution I add a new item:

image

Out of habit I call it Local.testsettings because I usually end up with a Build.testsettings that is set up differently.

image Under Data and Diagnostics I turn on code coverage and configure it. This is a bit tricky for the moment. For this to really work you need to add an assembly and select the actual .dll. Here are those screen shots for my project:

I don’t select any of the items that show up by default:

image

but instead I select the Add Assembly…

image

I navigated to the bin folder of my MVC application and selected that dll. Go ahead and select OK on the next message:

image

Click OK on the next dialog:

image Then hit Apply and Close on the Test Settings window. Now when I run all my tests again I can open the code coverage window:

image

And when I do, I see that I have about 50% code coverage.

image  

There are several other things that I do before I consider the project initially setup…

I turn on Code Analysis and select the Microsoft All Rules rule set.

image

After that I run the code analysis (Analyze –>  Run Code Analysis on KarlZMvcGallery) to see there are 14 warnings. I’ll breeze through getting rid of these but I will highlight some important items. The first is to create a Code Analysis Dictionary. I’m not sure why it is not as easy as merely adding a new item to the project, but you have to create a new file and type in it yourself. I created one from someone’s post so long ago that I don’t recall where that post is, but I copy that file from project to project. Here is the file I have to get rid of the “CA1704 : Microsoft Naming: Correct the spelling of …” warnings:

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Dictionary>
  3.   <Words>
  4.     <Unrecognized>
  5.       <Word>cb</Word>
  6.     </Unrecognized>
  7.     <Recognized>
  8.       <Word>Mvc</Word>
  9.     </Recognized>
  10.     <Deprecated>
  11.       <Term PreferredAlternate="EnterpriseServices">ComPlus</Term>
  12.     </Deprecated>
  13.   </Words>
  14.   <Acronyms>
  15.     <CasingExceptions>
  16.       <Acronym>GEDCOM</Acronym>
  17.     </CasingExceptions>
  18.   </Acronyms>
  19. </Dictionary>

After you add CodeAnalysisDictionary.xml to your project, you need to change the Build Action for the file to Code Analysis Dictionary:

image

I don’t know why the AssemblyInfo.cs file does not already have these two lines, but I need to add them each time:

  1. using System;
  2. [assembly: CLSCompliant(true)]

With a bit more work and some suppression of messages such as “Consider consolidating the namespace” in your project suppression file you have a project that has 0 Errors, 0 Warnings, and 0 Messages!

Now I feel like I’ve got a project initially setup.

MVC Overview

Technorati Tags:

What’s different about Microsoft’s ASP.NET MVC (Model-View-Controller)?

There are some very good books about MVC (such as Steven Sanderson’s book), but here are the features I enjoy the most:

Routing – The routing model in MVC makes you really think about what you want your URLs to look like. In EVERY instance my application ended up much simpler than I originally thought.

Controller – The controller does most of the binding work for you so you don’t have to constantly set the values of controls in your code behind.

*-Driven Development – My top two would be Test Driven Development (TDD) and Model Driven Development. MVC reinforces both.

Extension Methods – The HtmlHelper class is quite powerful and one can easily extend it if features are missing. This lets you type something like:

  1. <%= Html.DropDownListFor(model => model.Category, ViewData["Categories"] as SelectList) %>

I feel fortunate that I worked with web applications for many years. That made the move to WPF (Windows Presentation Foundation) much easier than someone moving from WinForms. However, the Binding model was a significant change from WebForms. The notion that I didn’t have to constantly write MyTextBox.Text = model.Property in my code behind was a relief. I finally appreciated Binding and then started to work with MVC where the Controller class provides the same capability.

I still do very little client side code because it is typically so hard to test, but I see slow improvements.

Not for Every Problem

While MVC is very powerful, it does not need to be the only tool you use on the web. However, I find that for data driven applications the model is much more natural. Having just finished a full application and benefiting from the power of MVC it will be one of the most used tools for me. But have no fear… You can fairly easily mix and match traditional controls within MVC… I’ll eventually have some examples of that.

MVC – Upcoming Series

Technorati Tags: ,

I’ve been playing with Microsoft’s ASP.NET MVC (Model-View-Controller) application on and off for about a year now. It’s been moving at such a fast pace that it seemed I was always starting over with another install – CTPs, V1 Visual Studio 2008, previews for Visual Studio 2010… And now I’m currently on MVC 2 RC 2 with Visual Studio 2010.

So now that I’m coming up the learning curve, I can see how powerful this is. But I also see that it’s so powerful it is easy to forget what you did to do something. So I plan to start a series of posts that will allow me to “remember” what I’ve done in an easy to consume fashion. I hope others will find it helpful too. As I go along I’ll actually be creating an MVC Gallery with tips I pick up. I pretty much never figure out how to do these on my own, so I’ll provide links to the original sites I used as well.

I’m sure it will be slow-going based on my past experience, but I think I’m ready to begin. I guess the final piece that I’m missing to provide the sense of urgency I really want is an ability to post my work. I’ve deployed two MVC .NET 4.0 applications, but only on machines I controlled… and none of those are on the internet. I need to have .NET 4.0 installed so that I can use the ASP.NET v4.0 application pool in IIS. Neither of my hosting companies have that at the time of this post. My motivation will be much higher when I actually go live with one of the apps.

Testing HtmlHelper in MVC 2 RC 2

Technorati Tags: ,,,

I strive to use TDD (Test Driven Development) so not having unit tests drives me crazy. I was so pleased to run across this post http://ox.no/posts/mocking-htmlhelper-in-aspnet-mvc-rc1-using-moq making it easy for me to unit test the Html Helper.

But then I downloaded the MVC 2 RC 2 and all my unit tests for HtmlHelper broke! It was late at night and I was getting errors that made it sound like there was an issue with a method I could not override. After looking more closely it looks like a TextWrite parameter was added to the constructor of the HtmlHelper.

  1. public static HtmlHelper CreateHtmlHelperOriginal(ViewDataDictionary vd)
  2. {
  3.     var mockViewContext = new Mock<ViewContext>(
  4.       new ControllerContext(
  5.             new Mock<HttpContextBase>().Object,
  6.             new RouteData(),
  7.             new Mock<ControllerBase>().Object),
  8.         new Mock<IView>().Object,
  9.         vd,
  10.         new TempDataDictionary());
  11.  
  12.     var mockViewDataContainer = new Mock<IViewDataContainer>();
  13.     mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);
  14.  
  15.     return new HtmlHelper(mockViewContext.Object,
  16.       mockViewDataContainer.Object);
  17. }

Here is the modification I needed to make to have my tests run again:

  1. public static HtmlHelper CreateMockHelper(ViewDataDictionary vd)
  2. {
  3.     var mockViewContext = new Mock<ViewContext>(
  4.         new ControllerContext(
  5.             new Mock<HttpContextBase>().Object,
  6.             new RouteData(),
  7.             new Mock<ControllerBase>().Object),
  8.         new Mock<IView>().Object,
  9.         vd,
  10.         new TempDataDictionary(),
  11.         new StringWriter());
  12.  
  13.     var mockViewDataContainer = new Mock<IViewDataContainer>();
  14.     mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);
  15.  
  16.     return new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object);
  17. }

Note the change in line 10 and the addition of line 11:

image

I thank Håvard Stranden for their original post and hope this one might help others that prefer well tested code that are using MVC 2 RC 2.

2002 Indian – What a ride

Technorati Tags:

Last night was very interesting. Each year The Briarwood School has a fund raising event which includes silent as well as live auctions. Last night one of the auction items was a 2002 Indian. While I don’t have the actual picture, this image was the closest I could find:

image

The color looks the same, but as I recall, the one I rode had a seat for two.

Now, I did NOT purchase the bike. However, the person that did was not prepared to take the bike home that evening, so as someone with a motorcycle license I was asked to take it to someone’s nearby garage for safe keeping until the true owner could retrieve it.

It would probably have been a lot more fun had their been sufficient gas in the tank(s). However, even once I had gas the “cob webs” were clearly there for the first mile. After that it began to be fun. It did look pretty nice all lit up. And the bike was spotless with less than 2700 miles on it.

It’s certainly not what I’m used to – a 2001 Honda Goldwing. And I couldn’t imagine taking it to Canada (6000 miles) as I did my bike in 2001. But it was a novel ride.

Error Check for MaxLength in Entity Framework

Technorati Tags: ,,

HEADLINE: edmProperty.TypeUsage.Facets[“MaxLength”].Value comes in handy.

I don’t make a habit of making a post when someone else has done some work… I might point it out, and in that spirit here is the post that finally sent me in the right direction: http://soci.hu/blog/. However, the post is not in English (fortunately, C# is spoken internationally :-) ) and it doesn’t solve the problem but provided the hint I needed to break through.

The Problem

Here is my problem. I’m working on an MVC application and I don’t want to have to manually write code that will check that user input has not exceeded the maximum length. Now you can use various annotation approaches for this, but I choose to use an approach that is more easily tested.

I throw an exception that I then catch and turn into an error that is exposed via the IDataErrorInfo interface so my MVC user knows that they’ve input a string that exceeds the maximum. (And this pattern was from Steven Sanderson’s book on MVC).

My Solution

Here’s what the final code looks like in a class of mine:

Code Snippet
  1. try
  2. {
  3.     if (value.Length > 10) // Added so we don't need to write code manually to verify the length of string properties. This will bubble up as message to user.
  4.     {
  5.         throw new ArgumentException(String.Format(Properties.Resources.EntityFrameworkStringMaxLengthError, "Abbr", "10"));
  6.     }
  7.     _abbr = value;
  8.     OnPropertyChanged("Abbr");
  9. }

How I Did It

I’m using the Entity Framework (EF) Self Tracking Entities (STEs) templates with a fair number of modifications. Here is one more modification I made. Inside the setter in the .tt file for the types (Model.tt) I added the following:

Code Snippet
  1.             if (<#=code.FieldName(edmProperty)#> != value)
  2. <#
  3.        }
  4. #>
  5.            {
  6.                 try
  7.                 {
  8. <#                  if (code.Escape(edmProperty.TypeUsage) == "string")
  9.                     {
  10.                         string facetName = "MaxLength";
  11.                         int maxLength = 0;
  12.                         if (Int32.TryParse(edmProperty.TypeUsage.Facets[facetName].Value.ToString(), out maxLength))
  13.                         {
  14. #>
  15.                     if (value.Length > <#= maxLength.ToString() #>) // Added so we don't need to write code manually to verify the length of string properties. This will bubble up as message to user.
  16.                     {
  17.                         throw new ArgumentException(String.Format(Properties.Resources.EntityFrameworkStringMaxLengthError, "<#= code.Escape(edmProperty) #>", "<#= maxLength.ToString() #>"));
  18.                     }
  19. <#
  20.                         }
  21.                     }
  22. #>

The key element which I got from that important post I mentioned earlier is the the property that contains the MaxLength value from your .edmx file. That is: edmProperty.TypeUsage.Facets[“MaxLength”].Value.

Since I work to eliminate all the code warnings Microsoft so kindly provides me I place the errors in the resources file. Here is what that looks like in my Resources.resx file:

  • Name: EntityFrameworkStringMaxLengthError   
  • Value: {0} must be {1} characters or less.   
  • Comment: Where {0} is the name of the property and {1} is the MaxLength for the string.

So now if someone inputs a value that is too long, here is what they will see in my user interface:

image

So as my requirements change, I don’t really have to do too much in my code to communicate effectively with my users.

The Entity Framework, MVC 2, .NET 4.0 and Visual Studio 2010 are coming along nicely.

Showing the Version for an MVC App

Technorati Tags: ,,

The primary MVC (Model-View-Controller) application that I’m working on is called KarlZMvc resulting in a dll called KarlZMvc.dll. To get the version output on my Site.Master page I need to include the following line:

Code Snippet
  1. <%= typeof(KarlZMvc.MvcApplication).Assembly.GetName().Version.ToString() %>

I tried all sorts of combinations with the GetExecutingAssembly, or calling, etc. But none seemed to work. This is with ASP.NET MVC 2 using Visual Studio 2010 Beta 2.

Gentleman’s Smart Key Passive Entry

Technorati Tags: ,

Headline: I enjoy the “Gentleman’s Keyless Entry” that I have with my 2010 Toyota Prius.

What do I mean by Gentleman’s Keyless Entry? First I need to review some history.

Before Remote Locks

There was a day that cars did not have remotes to lock and unlock them. So a driver had two basic choices – Open the door for the lady, or “the slide”. For the slide you merely hop in on the driver side and then slide across the seat until you could reach the lock on the passenger side.  My first car was a 1970 Mercury Marquis. I could lie down in the front seat (it was a bench seat) and not have my head or feet touch either door! That’s quite a slide! Of course, in smaller cars it was “the lean” (and frequently I saw that accompanied by a cigarette dangling from the driver’s mouth – their left hand was busy bracing by gripping the steering wheel while the right hand was busy unlocking the door, thus leaving the cigarette to dangle…).

Electric Locks

Next came the electric locks. Once you opened the driver’s door you could press a button and open all the locks. Now it was very convenient “not to be a gentleman”. Merely let your lady approach the passenger’s side and wait for you to unlock the doors.

With Remote Locks

But it was the remote that unlocks the door that really brought about the deterioration of gentlemanly behavior regarding car doors. Now you could unlocked the doors before you each arrived at the car. This was quite efficient and discrete. Remote locks don’t highlight lack of opening the door nearly as much as “the lean” or “the slide”!

and now…

Gentleman’s Keyless Entry

I now have a car with smart key passive entry. I don’t even need to take the key out of my pocket to click the remote in order to open the door. However, there’s a catch! Placing my hand on the driver’s door handle will not open the passenger’s door. However, when I open the passenger’s side door it unlocks all the doors.

So now my electronic device actually encourages me to walk around to my lady’s door and open it for her – then return to the driver’s side. (The alternative of course it either to remove the remote from my pocket or to open the driver’s side then press the unlock button.)

It makes me smile every time I walk to her side, open the door, let her in, and close it.

After many years now technology actually encourages gentlemanly behavior rather than discourage it… :-)

Globalization in web.config

Technorati Tags: ,,

Headline: Putting the following code in the web config (at least for an ASP.NET MVC app) will cause your pages to honor the user’s browser settings.

Code Snippet
  1.   <!–If culture and uiCulture are set to auto, ASP.NET can set the UI culture and culture for a Web page automatically, based on the values that are sent by a browser.–>
  2.   <globalization culture="auto:en-US" uiCulture="auto:en"/>
  3. </system.web>

I got the idea from the following post:

But when I ran tests and looked at the Microsoft documentation, the enableClientBasedCulture is not used at this time (not even in .NET 4.0):

http://stackoverflow.com/questions/1633980/asp-net-mvc-when-to-set-thread-currentthread-currentuiculture

However, the thread did send me in the right direction. So now if a user sets their language for Internet Explorer:

Tools –> Internet Options

image

Then Languages:

image

In the example above, the preferred language is en-GB (Great Britain English) which will display dates in dd/mm/yyyy order. When I display a web page today (5 Feb 2010) I can see this:

image

When this was in the Site.Master:

Code Snippet
  1. [<%= System.Globalization.CultureInfo.CurrentUICulture.Name %>] <%= DateTime.Today.ToShortDateString() %>

Works great! 

Forget the Colon as a Separator

Technorati Tags: ,

Headline: Only use a colon as a separator when there is no other visible means of separation. Stated differently, “Stop using a colon between a label and a text box!

Back in DOS (Disc Operating System) when there was no graphical user interface we needed a way to let the user know what the computer’s territory was, and which was territory of the user. We might ask for inputs doing something like this:

Year:

The colon indicated “The text on the left of the colon is the computer’s, you can type on the right”. The visual separation was useful, particularly on large input screens where you would tab from field to field. But those days are LONG gone. We now have Microsoft’s ASP.NET MVC (Model-View-Controller) 2. So why then does is use colons by default? The default would be:

image

rather than:

image

Will the colon help the user know where they should type? Is the border around their text box not enough? (An in the situation I have the user can’t even type to the right of the colon…) I think it just adds clutter that prevents a clean look on the page. I find I must continually make edits to remove the artifacts – and the term artifacts is quite fitting.

Cheers… I’m off to delete a bunch of colons.