Microsoft MVP Award for ASP.Net/IIS

I was honored this morning when I checked my email and discovered that I have been awarded a Microsoft MVP Award in ASP.Net/IIS for the 2011/2012 year.  This was a great surprise and I’m excited to be joining a group of people I highly regard in the community.

For those of you not familiar with the MVP program, Microsoft MVP’s are those individuals that share their time and knowledge with the developer community around Microsoft tools and technologies.  They might be leaders of user groups, speakers, prolific bloggers, authors, or just anyone who enriches the community they participate in.  For more information on the MVP program, check out the MVP site on Microsoft: http://mvp.support.microsoft.com/

I would like to take the time to thank some of the local MVP’s in the Colorado area for their great contributions, and for providing leadership and mentorship to me.  These individuals include (but not limited to):
Chris Wallace
Ben Hoelting
Joe Mayo
Julie Yack & David Yack
Kathleen Dollard
William Wergeson

I’m excited to be joining this group of distinguished individuals, and hope I can live up to the high standard they have set before me.

Notes from Build Conference Day 2 Keynote

Just like yesterday, here are my raw notes from watching the Build day 2 keynote.  Also just like yesterday, I don’t guarantee the accuracy of these Smile

Day 2 keynote

·         Theme

o   Windows server 8, azure, vs2011

·         Multiplayer game between wp7 and windows 8 communicating through azure

·         Productivity power tools has 1m + dl

o   Installed by default in vs2011

·         VS 2011

o   Find matching clones

§  Finds code similar to selected text?

o   Image editor built into vs2011

§  Loading of 3d model directly in vs

o   DOM explorer

§  Kind of like firebug inside of vs

§  Clicking a link will open the server side file in vs  `              

·         MVC4

o   New template

§  Uses html5

§  Works with mobile devices well

o   New async keyword used for controllers

o   Mobile optimize

§  Theres a new mobile template

§  jQuery mobile will ship by default in asp.net

o    

·         ASP.NET

o   Bundling and Minification

§  Automatically minifies & combines and includes css/js

§  Similar to pipeline in rails?

o   WebSocketHandler

§  New handler built for web sockets?

§  New in .net 4.5

o   Quick deploy to Azure

·         .Net 4.5

·         TFS 2011

o   Team Foundation Service hosted in azure

o   Activation code included in packet to use tfs in azure

·         Windows Server 8

o   Storage spaces

§  JABOD – just a bunch of disks

o   Virtual Machine

·         Azure

o   Data platform

§  Sql azure

§  Table storage

o   Access Control Service

§  To keep devs from writing tons of code for access

·         Reimagining Microsoft

o   New hardware

o   Cloud services

o   New app scenarios

o   New dev opportunities

·         WP7.5

o   30k apps

o   New phones coming

·         Estimating 350+ installations of windows shipping this year

Notes from Build Conference Day 1 Keynote

Here are my raw, unedited notes from today’s Build conference keynote that I took while watching the live stream.  I don’t make any claim they are 100% accurate, but just what I interpreted as I heard them.

·         Windows 8 will run all windows 7 apps? Even on ARM?

·         Themes

o   Remimaging windows

o   Metro style apps

§  Full screen

§  Immersive

§  Touch enabled

§  Fast and fluid

·         Performance gains

o   Windows 8 running lower resources than windows xp?

o   Less memory

§  540 vs 281mb   

·         Picture password

o   Touch based password entering

·         Home screen shows data at a glance

o   Email

o   Appointments

o   Etc.

·         Windows 8 has a similar win7 interface as well

·         Windows 8 has a very metro (wp7/xbox) style interface

·         Share App?

o   Semantically rich clipboard

o   Contracts?

·         Settings sync across multiple systems

o   Login profile pic

o   If used with a windows live id

§  Wonder how it works with ad login

o    

·         Apps should work together as a web of apps on your machine

·         Windows 8 apps written in

o   Html5 / js

§  Native controls being called from js

·         Windows ui controls

§  Client apis being exposed to javascript

§  Expression Blend 5 to edit HTML5 apps for win8

§   

o   Xaml/Silverlight

§  Existing Silverlight app taken and made to work like a metro app

o   If you write app in html5/xaml it will just run on ARM processors

·          

·         Windows App store for purchasing win8 apps

o   Will show were in the process the app certification is at in app hub

o   Devs will get tech compliance tools to make sure their apps meet requirements

o   Plus over apples controlling model

o   Will list win32 apps (quicken) in app store as well

·         Windows 8 bootup super fast

o   Almost booted up in the same time that the monitor took to come on

·         Demo Gremlins – lol

·         New power state that uses ultra low power

·         Resolution support

o   1024 width – metro apps run

o   1366 width – side by side is possible

·         Tap 2 share

o   Cards have antennas (rfid?) that can give info to machine just by tapping

·         Lots of work built into connectivity to allow for roaming between 3g and wifi

·         Samsung windows developer pc

o   1 year of 2gb/mo included

o   4gb ram

o   64gb ssd

o   Sensor

o   Usb

o   Dev preview of win8

o   Made for developers

o   Has samples and sdks shown during keynote

·         Windows 8 as a professional platform

o   Keyboard/mouse/dual monitors

o   Can use pin based security

o   Roll mouse down in bottom left hand corner brings up start menu

o   New task manager has improved view of cpu/memory/disk usage

o   Refresh your PC without losing your files

§  Keeps metro apps

§  Non metro apps will need to have a command line tool ran to do a refresh (ie visual studio)

o   Reset your PC will be just like a fresh clean install

o   Remote desktop will allow touch interface

o   Hyper v in the windows client?

o   Up button in explorer takes you to parent directory

o   Background images will now span multiple monitors

o   Just typing at the start screen will bring up search

o    

Global Filters and Dependency Injection in MVC3

I’ve been struggling with finding a good solution to resolve dependencies in global filters lately.  Since it does not appear that global filters are created through the FilterAttributeFilterProvider (I don’t get any results back from base.GetFilters, hit me up if I’m doing something wrong here), my global filters that had resolve attributes on its properties were never being created by the provider, and thus, not getting those properties resolved.

It then dawned on me that the global filters are actually being instantiated in the global.asax.cs file (or wherever your app startup exists at).  So instead of newing up the object directly, I just let Ninject do it for me:

private static void RegisterGlobalFilters(GlobalFilterCollection filters, IKernel kernel)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(kernel.TryGet(typeof(UserProviderFilterAttribute)));
        }

At first this felt like a giant hack, but after awhile I warmed up to it and realized that since this is the area of responsibility for creating global filters, that using Ninject to resolve its dependencies does in fact belong here.

If you have other methods for doing resolving your dependencies in global filters, or if I am way off base, I would love to hear any comments or suggestions.

Add a little salt to your hashed passwords with System.Web.Helpers.Crypto

In the news lately, there have been many incidents of data being stolen.  On sensitive information, it’s a good practice to use encryption to add an extra layer of protection in case your data does get stolen.  For passwords, a cryptographic function called a hash is often used.  A hash takes a string of data, and returns an (hopefully) unique value that can be used to identify the original string.  Hashing is a form of one way encryption, which means that once you hash something, you can’t un-hash it.

When you store your passwords as a hash of the original password, it doesn’t seem obvious at first how you can check to see if the password the user provides is correct.  If you can’t decrypt a hash, how are you suppose to check to see if the password provided is correct?  Instead of trying to decrypt the hash, you would instead hash the provided password and compare the two hashes.

There is a fundamental problem with just using plain hashes, however.  When using the same hashing algorithm, the same string will always compute the same hash.  Therefore, if someone was to get ahold of your database full of hashed passwords, they could compare the passwords against a list of known hashes (which are readily available and known as a Rainbow Table).  Using a highly complex and secure password might help ensure that its hashed equivalent will never end up in a Rainbow Table, however, that is not going to help all those winners out there using tigerblood for the password.  Its your job to help protect those people by using a technique called salting when generating your stored hashes.

Salting involves generating some random bytes (the salt) and injecting them into both the original password, and then the stored hash.  For instance, if the password is tigerblood and the random bytes are %34gsDz, then the password that we will actually hash will be tigerblood%34gsDz.  When we get back the hash for tigerblood%34gsDz, we will then inject the salt in a pre-determined fashion into the hash (pre-determined so that we will know how to pull it out later). 

When the user tries to log in, we will pull the hash out of the database, extract the salt back out, append the salt to the provided password, then hash that password and compare the hashes.  Since there are some random bits added to every password, every salted hash will produce a unique value, and therefore, render the computed hashes stored in Rainbow Tables useless.

This sounds like a complicated process, however, the new Crypto library in the System.Web.Helpers assembly (included with Webmatrix and MVC3), automatically adds a salt to the passwords hashed with the static HashPassword function (unlike the Hash function which does not use a salt).  The VerifyHashedPassword function will correctly extract the salt and use it to compare the hashes.

While this libraries imply that they should be used in the presentation layer due to their name, it is safe to include a reference to System.Web.Helpers.dll in your services and repository layers.  Now there is no excuse to not hash passwords, since System.Web.Helpers.Crypto makes the process a single line of code. 

DDD NLayered Architecture Guide from Microsoft

The Platform Architecture Team at Microsoft has published a mammoth (~500ish pages) guide on doing Domain Driven Architecture on the .Net platform.  I have only browsed through it so far, but it looks to have some pretty good information if you are wondering on different techniques in architecting your application.

Go here to read their blog post about the guide and download it:
http://msdn.microsoft.com/es-es/architecture/en

There is also a sample application on codeplex that accompanies the guide available here:
http://microsoftnlayerapp.codeplex.com/

Happy Coding!

Slides and demos from my What’s New in MVC3 talk at the South Colorado.NET UG

Thanks everyone who came out to hear my talk on the cool new features in MVC3 last week at the South Colorado.NETUG.  During the talk, I only got about 2/3 of the way through the demos, but if you like, you can download the demo code and take a look at the MVC Scaffolding and the integrated Dependency Injection support that MVC3 now has.

Enabling a submit button when a textbox has value in jQuery

A common pattern on the web is to only enable a submit button on a form if a value is filled out in a textbox.  The other day I was asked by a colleague how to do this in jQuery, and while I gave the basic pseudo code, I was curious on the exact method, so I put this together real quick and decided to share it with the world.

The premise is simple: We want to check the textbox after every time a change is made to it to see if there is any value in it.  If there is, we enable the button (by removing the disabled attribute), and if there isn’t, then we make sure the button stays disabled.  We initially load the form with the submit button disabled.

The trick to accomplishing this was in coming up with the right event to fire off the textbox.  At first I thought the change event would work, but that only fires when the textbox loses focus (not what we want here).  Then I tried keypress, but it seems that event gets fired before the textbox is updated, which gives us the previous value, not the current one we need.  Finally, I tried the keyup event, and that seems to work just fine.

Below is the code to accomplish this.  It might not be the best way to do this, but it works in this case.  Also make sure you always validate on the server side as well.

   1:  <!DOCTYPE html>
   2:  <html>
   3:  <head>
   4:      <title></title>
   5:  </head>
   6:   
   7:  <script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
   8:   
   9:  <script type="text/javascript">       
  10:      $(document).ready(function () {     
  11:          $("#name").keyup(function (data) {              
  12:              if ($(this).val() != "") {  
  13:                  $("#enter").removeAttr("disabled"); 
  14:              } 
  15:              else {  
  16:                  $("#enter").attr("disabled", "disabled"); 
  17:              }  
  18:          });
  19:      });  
  20:  </script>
  21:   
  22:  <body>
  23:      <div>        
  24:          <label for="name">
  25:              Name</label>
  26:          <input type="text" id="name" name="name" />        
  27:          <br /><br />        
  28:          <input type="submit" disabled="disabled" value="Enter" id="enter" />       
  29:      </div>    
  30:  </body>
  31:  </html>

Using a grid that can sort, page, and filter in Asp.Net MVC3–Part 1–Using the WebGrid WebHelper

If you are coming from Asp.Net WebForms development, you are probably use to controls that include a lot of base functionality out of the box.  Some of these controls were the DataGrid and GridView, which would construct an html table for you without writing a single line of html.  While these controls offered productivity gains because you did not need to mess with the html, css, or JavaScript in order to get them to run, they gave you little control on what the output was, and often times, the output was less than desirable.

In Asp.Net MVC development, you have complete control of your html output.  This is great news for those that want this type of power, but for those that still look for the productivity gains of some type of grid control, using MVC had its drawbacks.  There have been a few grid controls provided by the community (such as the one in MvcContrib), however, there is now one available in MVC3 out of the box.  With the release of MVC3 and WebMatrix, there is now a suite of web helpers, one of which is the WebGrid, which we will be using in Part 1 of this series to create a grid that can sort, page, and filter data on an html page.

The WebGrid WebHelper is located in the System.Web.WebHelpers assembly, which is referenced by default in a new MVC3 application. 

Getting the MvcWebGrid app setup

To begin, create a new MVC3 application called MvcWebGrid.  Make sure you select Empty for the template, and that the view engine is set to Razor.  Next, right click on the Controllers folder and select add->New Controller.  Name the controller HomeControler, and leave the checkbox to create the CRUD methods unchecked.

For simplicity sake, we will not connect to a real database in this sample.  Instead, I have created a class that returns a lists of music albums (generated from the MvcMusicStore tutorial at mvcmusicstore.codeplex.com).  You can find this class in the code download (linked at the end of this article), or here on github.  This is a simple static class with a single method called GetAlbums, which returns an IEnumerable<Album>.  Add this class to your models folder.

In your home controller, modify your Index action method to like like so:

   1:  public ActionResult Index()
   2:  {
   3:      var albums = AlbumRepo.GetAlbums();
   4:      return View(albums);
   5:  }

Nothing fancy happening here, we are just returning the whole list of albums to our view.  We still need to create our index view, but before we do, lets update the _Layout.cshtml file in the Views/Shared folder so our site has a bit more of a look to it.  Modify the file like so:

   1:  <!DOCTYPE html>
   2:  <html>
   3:  <head>
   4:      <title>@ViewBag.Title</title>
   5:      <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
   6:      <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript">
   7:      </script>
   8:  </head>
   9:   
  10:  <body>
  11:      <div id="header">
  12:          Welcome to my awesome music site where 
  13:          a deep dish of awesome stew is served up daily
  14:          <p/> <p /><p />
  15:      </div>
  16:      
  17:      @RenderBody()
  18:   
  19:      <div id="footer">
  20:          <p/> <p /><p />
  21:          You have reached the bottom of this page, now what?
  22:      </div>
  23:  </body>
  24:  </html>

Adding the WebGrid to the app

Now that we have a basic layout for our site, lets create the index view.  Go back to the home controller, right click anywhere within the index action method, and select add view.  Keep all the defaults and click Add.

Change the new view to look like the following:

   1:  @model IEnumerable<Album>
   2:   
   3:  @{
   4:      ViewBag.Title = "MVC Music Store Grid";
   5:  }
   6:   
   7:  @using (Html.BeginForm())
   8:  {
   9:      <fieldset>
  10:          <legend>Search</legend>
  11:   
  12:          <div>
  13:              Album Id:
  14:          </div>
  15:          <div>
  16:              <input type="text" id="albumid" name="albumid" />
  17:          </div>
  18:   
  19:          <div>
  20:              Album Name:
  21:          </div>
  22:          <div>
  23:              <input type="text" id="albumName" name="albumName" />
  24:          </div>
  25:   
  26:          <p>
  27:              <input type="submit" value="Search" />
  28:          </p>
  29:      </fieldset>
  30:  }
  31:   
  32:  <div id="myGrid">
  33:      @Html.Partial("_grid", Model)
  34:  </div>

We will be separating the WebGrid into its own partial view, so right click on the Views/Home folder, select add, and then view.  Name the view _grid, and check the “Create as a partial view” checkbox, then click add.  Prepending the name of our Razor view with a underscore tells Asp.Net that this file should not be served if requested directly, which is perfect for our partial views.

In our grid partial view, we will now be using the new WebGrid helper.  We start off creating an instance of the WebGrid (passing in our model into the constructor), and then call the GetHtml method which generates the html for the grid and outputs it to the screen:

   1:  @model IEnumerable<Album>
   2:   
   3:  @{
   4:      var grid = new WebGrid(Model);
   5:      @grid.GetHtml();
   6:  }

When we run the app, we get a web page that looks like so:

image

If you inspect the html for the new grid, you will see that it is clean markup, with no added styles or nasty viewstate that we have seen in the past with WebForms.  You might also notice that the table html is semantically correct, where the header is in the thead section, the content in the tbody section, and the paging in the tfoot section.  Having your tables formatted properly will go a long ways if you want to try to extend your table functionality using JavaScript libraries such as jQuery, where it was often difficult to achieve this in WebForms.

Another bonus is that the paging and sorting already work!  Out of the box, the WebGrid provides these functions by doing Get requests and passing in a few values over the query string.  The WebGrid will see these values in the new request, and adjust the output accordingly.  This means that the WebGrid expects the entire set of data in each view in order to generate the paging properly.  For small sets of data this is not a problem, but even in our sample app you can notice a lag when hitting the links.  Fixing this issue is out of the scope of this article, but just be aware that you will need to come up with a different solution if your data sets are large.

The WebGrid provides a lot of options for configuration.  These options are provided by passing in parameters to the WebGrid’s constructor, as well as the GetHtml method.

image

image

We will modify some of these options to add some Ajax functionality to the screen (so that paging and sorting don’t refresh the entire screen), as well as change how some of the columns appear.  Modify _grid.cshtml to look like so:

   1:  @model IEnumerable<Album>
   2:   
   3:  @{
   4:      var grid = new WebGrid(Model, rowsPerPage: 15, ajaxUpdateContainerId: "myGrid");
   5:      @grid.GetHtml(columns: grid.Columns(
   6:                          grid.Column("AlbumId", "Album Id"),
   7:                          grid.Column("Title", "Title"),
   8:                          grid.Column("Artist", "Artist")
   9:                          ));
  10:  }

In the constructor, we setting the size of the page to handle 15 albums at a time, as well as setting the container id of the div in the index.cshtml page that holds our grid.  The simple act of setting the ajaxUpdateContainerId will automatically enable our screen to use Ajax to update the screen on pages and sorts.  All we need to do is make sure jQuery is included in the project, which it is by default in the _Layout.cshtml page.

The GetHtml method take a columns param, where we pass in a list of column objects we want to use on the grid.

One thing I don’t particularly care for is how the Ajax is inserted into the page.  If you take a look at the source, all of the links now have onclick methods inserted into them.  This gets away from the unobtrusive JavaScript theme the rest of MVC3 strived so hard to achieve.  We will talk some more about unobtrusive JavaScript in the next section.

Filtering the grid

You probably noticed that our index.cshtml page has had a form in it that we will be using to filter the data in the grid.  This form is simple by design, and will allow us to filter the form either by the Album Id, or the Album Name.  Before we do anything with the form, lets add a new action method in our home controller that will let us filter the data:

   1:  [HttpPost]
   2:  public ActionResult Index(int? albumId, string albumName)
   3:  {
   4:      var albums = AlbumRepo.GetAlbums();
   5:   
   6:      if (!string.IsNullOrEmpty(albumName))
   7:          albums = albums.Where(a => a.Title.Contains(albumName)).ToList();
   8:   
   9:      if (albumId.HasValue)
  10:          albums = albums.Where(a => a.AlbumId == albumId).ToList();
  11:   
  12:      return View(albums);
  13:  }
 
This new action method has the same name as our other action method, but has the HttpPost attribute which tells MVC that this method will only respond to post requests.  We accept two params into the method that will be used to filter the data. (Note: the code in this action method is not a good way to filter data, it is just demo code, so don’t reuse it in production).
Now when we run the app, we can filter the data.  However, our site is doing a complete post and refresh of the page every time we do a search.  We will now add Ajax to the form.
We will use the new unobtrusive Ajax support that is in MVC3 to accomplish this, and do it without having to write a single line of JavaScript.  The Ajax.BeginForm has been around for awhile in MVC, but it has been changed to now use jQuery and not the Microsoft Ajax library.  Also, there is no more JavaScript inserted into the screen on your behalf (unlike the WebGrid Ajax support shown above).  Instead, MVC3 uses HTML5 data attributes to mark the form, and a special script that is used to wire the Ajax functionality up at runtime.
In index.cshtml, change the Html.BeginForm line to the following:
   1:  @using (Ajax.BeginForm(new AjaxOptions 
   2:      { InsertionMode = InsertionMode.Replace, UpdateTargetId = "myGrid" }))
   3:  {
The AjaxOptions parameter tells our form how to handle the Ajax reqeuest.  In this case, we are telling it we want the InsertionMode to replace the current contents in the myGrid div tag (much like we did with the paging and sorting on the grid).  All that is left to do is add the JavaScript file that will make this magic happen.  In the _Layout.cshtml file, add the following line directly below the line that includes jQuery:
   1:  <script type="text/javascript" src="../../Scripts/jquery.unobtrusive-ajax.min.js">
   2:  </script>  

Make sure you don’t include any of the JavaScript files that start with Microsoft, as those are just included for backwards compatibility.  In MVC3, you want to be using the scripts who’s filenames start with jQuery.

If you run the app now, you might notice a strange oddity when filtering the data.  The entire response is copied into the myDiv tag, meaning that we get another copy of the form, along with the WebGrid table again.  When using Ajax.BeginForm, the response that is sent is expected to only be the content that changes, not the entire page.  We can easily fix this and return just the updated grid by changing the index action method that accepts the HttpPost to return a partial view of only the grid and not the entire index view (this is why we separated the grid out from the index view in the first place).

Update the index action method for the filtering to return a partial view by modifying the last line as such:

   1:  return PartialView("_grid", albums);

Now when you enter an a AlbumId or a partial Album name, the grid will filter and display properly.

Summary

In this post, I went over how the new WebGrid html helper can be used to quickly generate html tables with paging, sorting, and filtering.  I also showed how to enable the Ajax features of the WebGrid, as well as using the new unobtrusive Ajax features in MVC3.  If you are familiar with webforms development, but new to MVC, then you can use these techniques to easily add rich functionality to your MVC apps.  These techniques did not require deep knowledge of html or JavaScript to accomplish our desired results.

In my next artilce, I will show how to do the same thing using straight html and JavaScript (via jQuery).  We won’t rely on the framework to generate any of our code, but will instead dig deep and get close to the metal.  I think you will discover it is not as scary as it sounds.

You can download the code via github (click the Download button to download all the code in a zip file):https://github.com/elylucas/MvcWebGrid-Part1

String Extension Methods in Razor

The new Razor view engine contains several handy extension methods you can use in your views.  These methods mostly deal with either detecting if a string value can be converted to a particular type, or converting string values to a particular type.  For instance, the following code checks to see if a querystring value is a decimal, and if so, to format it as a currency:


@{
    if (Request.QueryString["amount"].IsDecimal())
    {
        @Request.QueryString["amount"].AsDecimal().ToString("c")W
    }
    else
    {
        @: Amount is not a valid number
    }
}

There are Is(Type), and As(Type) methods for bools, datetimes, decimals, floats, and ints. All of the As(Type) conversion methods take in an optional second parameter that can serve as the default value in case the conversion is not successful.

These extension methods are handy and can save some time and lines of code when dealing with strings.  They are in the System.Web.WebPages namespace, which new projects in MVC3 and Webmatrix automatically reference, so you do not need to worry about adding any using statements into your views in order to take advantage of them.  If you want to take advantage of them in your views, you can simply add a using statement to System.Web.WebPages.