Welcome to MSDN Blogs Sign in | Join | Help

Chris Tavarez has provided a handy adapter (UnityServiceLocator) for using ServiceLocator to resolve types from a Unity container.  You can then use ServiceLocator.SetLocatorProvider() to register the UnityServiceLocator as the default provider for ServiceLocator. 

For this example, we will be using ServiceLocator and Unity to resolve the type IFoo to Foo using a singleton lifetime.  Then we will get two instances of IFoo and compare to ensure that they are the same object. 

Here are four different approaches to configuring ServiceLocator and Unity that I have found during my searches on the web:

1:

   1: static void Main(string[] args)
   2: {            
   3:     UnityServiceLocator locator = new UnityServiceLocator(ConfigureUnityContainer());
   4:     ServiceLocator.SetLocatorProvider(() => locator);
   5:  
   6:     var a = ServiceLocator.Current.GetInstance<IFoo>();
   7:     var b = ServiceLocator.Current.GetInstance<IFoo>();
   8:  
   9:     Console.WriteLine(a.Equals(b));            
  10: }
  11:  
  12: private static IUnityContainer ConfigureUnityContainer()
  13: {
  14:     UnityContainer container = new UnityContainer();
  15:     container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager());
  16:     return container;
  17: }

2:

   1: static void Main(string[] args)
   2: {      
   3:     ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(ConfigureUnityContainer()));
   4:  
   5:     var a = ServiceLocator.Current.GetInstance<IFoo>();
   6:     var b = ServiceLocator.Current.GetInstance<IFoo>();
   7:  
   8:     Console.WriteLine(a.Equals(b));            
   9: }
  10:  
  11: private static IUnityContainer ConfigureUnityContainer()
  12: {
  13:     UnityContainer container = new UnityContainer();
  14:     container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager());
  15:     return container;
  16: }

3:

   1: static void Main(string[] args)
   2: {
   3:     UnityContainer container = new UnityContainer();
   4:     container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager());
   5:  
   6:     ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
   7:  
   8:     var a = ServiceLocator.Current.GetInstance<IFoo>();
   9:     var b = ServiceLocator.Current.GetInstance<IFoo>();
  10:  
  11:     Console.WriteLine(a.Equals(b));            
  12: }

4:

   1: static void Main(string[] args)
   2: {
   3:     UnityContainer container = new UnityContainer();
   4:     container.RegisterType<IFoo, Foo>(new ContainerControlledLifetimeManager());
   5:     UnityServiceLocator locator = new UnityServiceLocator(container);
   6:     
   7:     ServiceLocator.SetLocatorProvider(() => locator);
   8:  
   9:     var a = ServiceLocator.Current.GetInstance<IFoo>();
  10:     var b = ServiceLocator.Current.GetInstance<IFoo>();
  11:  
  12:     Console.WriteLine(a.Equals(b));            
  13: }

 

So these implementations seem to to do the same basic thing: register the UnityServiceLocator and use it to resolve types.  But…

howardpayne

Pop quiz:

Can you find the subtle differences and explain the problems that they can cause? 

Explanation:

Example #1:  This implementation works as expected.  The two instances (a and b) reference the same container controlled object.

Example #2:  This one is just wrong.  The two instances are not the same object, but two distinct objects.  Since the argument for the SetLocatorProvider() method is a delegate, each call to ServiceLocator.Current executes the delegate again, creating a new Unity container for every call.  This one also has the same side effect as #3.

Example #3:  This one gives the correct behavior with respect to instances a and b, but leads to a new UnityServiceLocator object being created for each ServiceLocator.Current call.  This could lead to a lot of objects just hanging around until the GC runs and reclaims the memory.

Example #4:  Works as expected.  Essentially the same as #1 but without wrapping the container creation in a method.

 

The two primary conclusions that I came to during this exercise are:

  1. Make sure that you understand the API and code that you are calling.  It may not always be black and white.  As in example #2 above, forgetting that this is a delegate can lead to the wrong behavior.
  2. Don’t rely blindly on example code from the internet.  Some of the code that I have posted is probably error prone.  Sample code is just that: a sample.

A custom Role Provider is a very useful tool for adding custom authorization to your ASP.NET and/or ASP.NET MVC applications.  A common use for a custom Role Provider is when you have role information stored in a data store that differs from the schema that is used by the built-in ASP.NET Role Providers.  In this case, ASP.NET provides a abstract RoleProvider class that can be used to implement the custom provider.  This contains role-specific methods such as: CreateRole, DeleteRole, GetRolesForUser, etc.  In a custom Role Provider, you provide the implementation of these methods using your database access mechanism of choice.  The MSDN documentation for implementing a custom Role Provider is a good place to start if you want to learn more about this.

In this post, I am NOT going to detail the steps in creating a custom Role Provider.  Examples of this can be found all over the internet.  Rather, I am going to talk about a recent gotcha with implementing a custom Role Provider that was encountered on a project that I am working on. 

The following preconditions are used in our custom implementation:

  • We are using the Entity Framework as our data access and the Unity Application Block/Service Locator for dependency injection and inversion of control. 
  • We are abstracting away the Entity Framework context using the Repository pattern.
  • The IRoleRepository instance is managed by Unity using a per-request lifetime manager.

Here is a quick snippet of the initial custom provider that we implemented:

   1: public class CustomRoleProvider : RoleProvider
   2: {
   3:     private IRoleRepository roleRepository;
   4:  
   5:     public CustomRoleProvider()
   6:         : this(ServiceLocator.Current.GetInstance<IRoleRepository>())
   7:     {
   8:     }
   9:  
  10:     public CustomRoleProvider(IRoleRepository roleRepository)
  11:     {
  12:         this.roleRepository = roleRepository;
  13:     }
  14:  
  15:     // Role Provider Abstract members
  16:  
  17:     // ...
  18:  
  19:     public override void CreateRole(string roleName)
  20:     {
  21:         Role newRole = Role.CreateFromName(roleName);
  22:         this.roleRepository.Add(newRole);
  23:     }
  24:  
  25:     // ...
  26: }

At the outset, this seemed to be working great.  The application functioned.  The unit tests passed.  Our roles that were stored in the database were being managed by the custom Role Provider.  Then we started to notice some weird behavior. 

  • Direct modifications of the Role table in the database were not exposed by the role provider until a restart of Cassini/IIS.
  • Changes made using a per-request instance of IRoleRepository were not exposed by the role provider, but changes made using the System.Web.Security.Roles class were.

Blank-Facepalm

I had a facepalm moment and quickly realized that I had neglected to remember a very important part of implementing a custom Role Provider.  During the initialization of an ASP.NET application, a single instance of the RoleProvider class is instantiated and used for the life of the application.  Of course, this all made perfect sense now.  The Entity context for the role provider was effectively a singleton since is was only being injected at the beginning of the application.  It didn’t take long for this context to become stale if changes were made to the roles during other requests.

The MSDN fine print does talk about this:

For each role provider specified in the configuration for an application, ASP.NET instantiates a single role-provider instance that is used for all of the requests served by an HttpApplication object. As a result, you can have multiple requests executing concurrently. ASP.NET does not ensure the thread safety of calls to your provider. You will need to write your provider code to be thread safe. For example, creating a connection to a database or opening a file for editing should be done within the member that is called, such as AddUsersToRoles , rather than opening a file or database connection when the Initialize method is called.

“Implementing a Role Provider (Threading Section)", Microsoft Developer Network Library, http://msdn.microsoft.com/en-us/library/8fw7xh74.aspx

The quick fix for this problem was to change the custom role provider to use a new IRoleRepository without a lifetime manager (returning a new instance for every call to GetInstance()) for each call to a method on the provider:

   1: public class CustomRoleProvider : RoleProvider
   2: {
   3:     public CustomRoleProvider()
   4:     {
   5:     }
   6:  
   7:     // Role Provider Abstract members
   8:  
   9:     // ...
  10:  
  11:     public override void CreateRole(string roleName)
  12:     {
  13:         Role newRole = Role.CreateFromName(roleName);
  14:  
  15:         IRoleRepository roleRepository = ServiceLocator.Current.GetInstance<IRoleRepository>(“NoLifetime”);
  16:         roleRepository.Add(newRole);
  17:     }
  18:  
  19:     // ...
  20: }

So what have we learned? 

  • When using the Entity framework, make sure that you are handling your context with care.  Misuse can often cause bugs that are hard to find.
  • Read the MSDN documentation.  It may contain very important information that you might overlook or forget.
  • Integration testing is just as important as unit testing.
  • Remember that ASP.NET has some architectural paradigms that do not always behave the way that you think they should (more on this in a future post with the always fun ThreadStatic attribute).

When using Unity as your IoC container, one way to configure the container is to use an configuration section in your app.config or web.config file.  A simplified example of this configuration is shown below:

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <configuration>
   3:   <configSections>
   4:     <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
   5:   </configSections>
   6:  
   7:   <unity>
   8:     <typeAliases>
   9:       <typeAlias alias="IMyInterface1" 
  10:                  type="UnityConfigTestApp.IMyInterface1, UnityConfigTestApp" />
  11:       <typeAlias alias="MyClass1" 
  12:                  type="UnityConfigTestApp.MyClass1, UnityConfigTestApp" />
  13:     </typeAliases>
  14:     <containers>
  15:       <container>
  16:         <types>
  17:           <type type="IMyInterface1" mapTo="MyClass1" />
  18:         </types>
  19:       </container>
  20:     </containers>
  21:   </unity>
  22: </configuration>

This configuration allows you to specify the types and the mappings for your Unity container.  An example of how to implement this concept can be found here: http://weblogs.asp.net/podwysocki/archive/2008/03/27/ioc-and-unity-configuration-changes-for-the-better.aspx

In this post, I am going to show an easy way to test the validity of your Unity XML configuration.  In the example configuration above, we are only dealing with two types and one mapping so things are not too complicated.  But in a real application you might have a large number of types and mappings which can make the configuration difficult to maintain.  A small typo can cause your application to fail at runtime since there is no compile time validation of the Unity configuration.

To perform this validation, I am going to write a couple of simple unit tests.  Now, these are not true unit tests since they are not testing a unit of code, but I found a unit test construct to be the best way to perform this validation in a simple and quickly testable way.  The two unit tests that I wrote are shown below:

   1: using System;
   2: using System.Linq;
   3: using System.Text.RegularExpressions;
   4: using System.Xml;
   5: using Microsoft.VisualStudio.TestTools.UnitTesting;
   6:  
   7: [TestMethod]
   8: [DeploymentItem(@"UnityConfigTestApp\App.config")]
   9: public void TypeAliases_should_reference_valid_types()
  10: {
  11:     XmlDocument unityConfig = new XmlDocument();
  12:     unityConfig.Load("App.config");
  13:     XmlNode unityNode = unityConfig.DocumentElement.SelectSingleNode("unity");
  14:     XmlNodeList typeAliases = unityNode.SelectNodes("typeAliases/typeAlias");
  15:  
  16:     foreach (XmlNode typeAliasNode in typeAliases)
  17:     {
  18:         string typeFullName = RemoveWhiteSpace(typeAliasNode.Attributes["type"].Value);
  19:         Type currentType = Type.GetType(typeFullName);
  20:  
  21:         Assert.IsNotNull(currentType, String.Format("'{0}' is not a valid type.", typeFullName));
  22:     }
  23: }
  24:  
  25: [TestMethod]
  26: [DeploymentItem(@"UnityConfigTestApp\App.config")]
  27: public void Type_mappings_should_be_compatible()
  28: {
  29:     XmlDocument unityConfig = new XmlDocument();
  30:     unityConfig.Load("App.config");
  31:     XmlNode unityNode = unityConfig.DocumentElement.SelectSingleNode("unity");
  32:     XmlNodeList typeList = unityNode.SelectNodes("containers/container/types/type");
  33:  
  34:     foreach (XmlNode typeNode in typeList)
  35:     {
  36:         string typeName = typeNode.Attributes["type"].Value;
  37:         string mapToName = typeNode.Attributes["mapTo"].Value;
  38:  
  39:         XmlNode typeTypeAliasNode = unityNode.SelectSingleNode(String.Format("typeAliases/typeAlias[@alias = \"{0}\"]", typeName));
  40:         XmlNode mapToTypeAliasNode = unityNode.SelectSingleNode(String.Format("typeAliases/typeAlias[@alias = \"{0}\"]", mapToName));
  41:  
  42:         Assert.IsNotNull(typeTypeAliasNode, String.Format("Could not locate a typeAlias element for '{0}'.", typeName));
  43:         Assert.IsNotNull(mapToTypeAliasNode, String.Format("Could not locate a typeAlias element for '{0}'.", mapToName));
  44:  
  45:         string typeFullName = RemoveWhiteSpace(typeTypeAliasNode.Attributes["type"].Value);
  46:         string mapToFullName = RemoveWhiteSpace(mapToTypeAliasNode.Attributes["type"].Value);
  47:  
  48:         Type currentType = Type.GetType(typeFullName);
  49:         Type mapToType = Type.GetType(mapToFullName);
  50:         Assert.IsNotNull(currentType, String.Format("'{0}' is not a valid type.", typeFullName));
  51:         Assert.IsNotNull(mapToType, String.Format("'{0}' is not a valid type.", mapToFullName));
  52:  
  53:         bool areTypesCompatible = false;
  54:  
  55:         if (currentType.IsAssignableFrom(mapToType) ||                                          // test assignabilty
  56:             mapToType.Name == currentType.Name ||                                               // or matching names
  57:             mapToType.GetInterfaces().Where(x => x.Name == currentType.Name).Count() == 1 ||    // or generic interfaces
  58:             (mapToType.BaseType != null && mapToType.BaseType.Name == currentType.Name))        // or generic base classes
  59:         {
  60:             areTypesCompatible = true;
  61:         }
  62:  
  63:         Assert.IsTrue(areTypesCompatible, String.Format("Cannot map '{0}' to '{1}'.", typeName, mapToName));                
  64:     }
  65: }
  66:  
  67: private static string RemoveWhiteSpace(string inputString)
  68: {
  69:     if (inputString == null)
  70:         return null;
  71:  
  72:     return Regex.Replace(inputString, @"[\s\r\n]", String.Empty);
  73: }

A couple of things about configuring the tests:

  1. You will notice the DeploymentItemAttribute on each of the tests.  This references the relative path to the config file from the solution directory.
  2. Any assemblies that are referenced in the unity configuration section need to be included as references in the test project.

The first test validates that the types specified in the <typeAliases> are valid types.  We just iterate through each <typeAlias> and check that the type can be found.  If it can be found, then it should be a valid type.

The second tests validates the type mapping specified in the <type> elements of the configuration.  To do this, we get the full names for the types by referencing back to the matching <typeAlias> elements.  We then get a reference to those types and compare them for compatibility (This part is done at line 55 in the code above).  The types are checked for compatibility by following a set of rules:

  1. Check to see if the types are directly assignable.
  2. Check to see if the names match.
  3. Check to see if the to type implements the from interface (needed for generic interfaces)
  4. Check to see if the to type inherits from the from base class (needed for generic base classes)

Once we have these tests in our test suite, we can validate the types and mappings without having to run the application and hope that we didn’t mistype something in the configuration.

One of my favorite features of ASP.NET MVC is the support for JSON.  In MVC, an Action Method in a Controller can return a JsonResult.  This really comes in handy when integrating with jQuery to provide AJAX-like functionality in an application.

In this post, I am going to share some of the different ways that I have used for testing Action Methods that return a JsonResult.  Some implementations can be very easy to test, and some can be difficult.  We will start with the easy ones first.

Let’s say that we have the following Action Methods in a Controller that return JSON.  Of course, your methods would likely return something that is calculated, but these are hard-coded for the example:

   1: public ActionResult JsonOne()
   2: {
   3:     string fooString = "test";
   4:     return Json(fooString);
   5: }
   6:  
   7: public ActionResult JsonTwo()
   8: {
   9:     int fooInt = 10;
  10:     return Json(fooInt);
  11: }
  12:  
  13: public ActionResult JsonThree()
  14: {
  15:     List<int> fooList = new List<int>();
  16:     fooList.Add(3);
  17:     fooList.Add(5);
  18:     fooList.Add(7);
  19:  
  20:     return Json(fooList);
  21: }

Unit testing the above implementations is very simple.  We can just write the following tests against the JsonResult.Data property:

   1: [TestMethod]
   2: public void JsonOneTest()
   3: {
   4:     HomeController controller = new HomeController();
   5:     JsonResult actual = controller.JsonOne() as JsonResult;
   6:     
   7:     Assert.AreEqual("test", actual.Data);
   8: }
   9:  
  10: [TestMethod]
  11: public void JsonTwoTest()
  12: {
  13:     HomeController controller = new HomeController();
  14:     JsonResult actual = controller.JsonTwo() as JsonResult;
  15:     
  16:     Assert.AreEqual(10, actual.Data);
  17: }
  18:  
  19: [TestMethod]
  20: public void JsonThreeTest()
  21: {
  22:     HomeController controller = new HomeController();
  23:     JsonResult actual = controller.JsonThree() as JsonResult;
  24:     List<int> result = actual.Data as List<int>;
  25:  
  26:     Assert.AreEqual(3, result.Count);
  27:     Assert.AreEqual(9, result[0]);
  28:     Assert.AreEqual(4, result[1]);
  29:     Assert.AreEqual(7, result[2]);
  30: }

You might notice that in the third test above, we have to convert the JsonResult.Data property to a List<int>.  The Data property on JsonResult is an object, so for some more complex types, we will have to explicitly convert the result to the type that we expect it to be.

This simple testing method works great for regular types, but what if we return a JSON object that contains an anonymous type reference or an IQueryable?  An example of this is shown below:

   1: public ActionResult JsonFour()
   2: {
   3:     var fooAnon = new
   4:     {
   5:         First = "Bob",
   6:         Last = "Smith"
   7:     };
   8:  
   9:     return Json(fooAnon);
  10: }
  11:  
  12: public ActionResult JsonFive()
  13: {
  14:     List<int> fooList = new List<int>();
  15:     fooList.Add(9);
  16:     fooList.Add(4);
  17:     fooList.Add(7);
  18:  
  19:     IQueryable<int> fooQueryable = fooList.AsQueryable()
  20:         .OrderBy(x => x);
  21:  
  22:     return Json(fooQueryable);
  23: }

These JsonResults cannot be tested in the same simple way as the first examples.  So how can we test them?  I will show you the solution that I came up with (there might be a better way to do this, but this is what I came up with).  In the case of JsonFour (line 1), once the anonymous type is returned, we cannot access it from code since anonymous types are limited to scope.  And in the case of JsonFive (line 12), we are returning an IQueryable<int> that will not actually be executed until the enumeration on the query (because of lazy loading). 

The following code shows the method that I use to test these types of JsonResults:

   1: [TestMethod]
   2: public void JsonFourTest()
   3: {
   4:     HomeController controller = new HomeController();
   5:     JsonResult actual = controller.JsonFour() as JsonResult;
   6:     
   7:     var result = JsonHelper.GetJsonObjectRepresentation<IDictionary<string, object>>(actual);
   8:  
   9:     Assert.AreEqual("Bob", result["First"]);
  10:     Assert.AreEqual("Smith", result["Last"]);
  11: }
  12:  
  13: [TestMethod]
  14: public void JsonFiveTest()
  15: {
  16:     HomeController controller = new HomeController();
  17:     JsonResult actual = controller.JsonFive() as JsonResult;
  18:     
  19:     var result = JsonHelper.GetJsonObjectRepresentation<List<int>>(actual);
  20:  
  21:     Assert.AreEqual(3, result.Count());
  22:     Assert.AreEqual(4, result[0]);
  23:     Assert.AreEqual(7, result[1]);
  24:     Assert.AreEqual(9, result[2]);
  25: }
  26:  
  27: //using Rhino.Mocks;
  28: public static T GetJsonObjectRepresentation<T>(JsonResult jsonResult)
  29: {
  30:     var controllerContextMock = MockRepository.GenerateStub<ControllerContext>();
  31:     var httpContextMock = MockRepository.GenerateStub<HttpContextBase>();
  32:     var httpResponseMock = MockRepository.GenerateStub<HttpResponseBase>();
  33:  
  34:     httpContextMock.Stub(x => x.Response).Return(httpResponseMock);
  35:     controllerContextMock.HttpContext = httpContextMock;
  36:  
  37:     jsonResult.ExecuteResult(controllerContextMock);
  38:  
  39:     var args = httpResponseMock.GetArgumentsForCallsMadeOn(x => x.Write(null));
  40:  
  41:     JavaScriptSerializer serializer = new JavaScriptSerializer();
  42:     return serializer.Deserialize<T>(args[0][0] as string);
  43: }

The helper method (line 28) uses RhinoMocks to mock a controller context that can be used to simulate the execution of the JsonResult.  We can then deserialize the JSON string representation back into the object type that was used to create the JSON result.  After doing that, we can compare the actual result to the expected result.

One interesting thing to notice here is what happens in JsonFourTest on line 7.  When we get the deserialized anonymous type, it is returned as a IDictionary<string, object> by the JavaScriptSerializer (line 41 and 42).  Knowing this helps us to cast the result to an IDictionary for accessing the members for testing.  So if you had a list of anonymous types, you can call the helper method using the type List<IDictionary<string, object>> to access the anonymous type members.

If anyone knows of a better way to do this, please let me know.  This is just my quick attempt at solving the problem.

"Make everything as simple as possible, but not simpler"

Albert Einstein

With all of the software design patterns available to developers, I think that we sometimes lose focus of the pragmatic development approach: Write code that works.

Don’t get me wrong, I do believe that software patterns are a very valuable tool in the software developers repertoire.  When implemented correctly they provide enhancements in maintainability, flexibility, and typically result in cleaner code.  After all, patterns are exactly what the name implies: a standard and effective way to implement common objectives.

However, the misuse of patterns can lead to significant problems as well.  The unnecessary overuse of patterns can result in the following:

1. Code Complexity

“Every time you put extra stuff into your code to make it more flexible, you are usually adding more complexity.” - Martin Fowler

Unless there is a need to introduce complexity, it is simply a bad development practice.  Complexity has many side effects.  If not introduced with care, complexity can lead to problems with testability and maintainability, which is the fundamental opposite of the compelling reasons to implementing design patterns.

2. Unnecessary Code

If a developer sets out to implement patterns before fully understanding the requirements, extra code can be introduced that does not serve a real purpose in the application.  When we get into this over-creative zone, we tend to anticipate what we think that the application will need rather than coding to the specifications.  This leads to both increased complexity and increased maintainability, as well as loosing sight of the real goals of the implementation.

3. Paralysis by Analysis

When trying to predetermine patterns from the start or a development project, a developer can often get caught up in a state of perpetual design analysis.  This period of paralysis is bad for two reasons.  It typically incurs a significant cost in time and it keeps the developer from concentrating on and implementing the actual requirements of the project.

4. Cost of Development

All of the above lead to an increased amount if time spent on design that is not spent on writing code to satisfy the requirements.  As professional developers, this is the ultimate goal: To write code on time and on target.

Patterns should be implemented when a reason becomes evident.  This is the essence of refactoring.

Code refactoring is the process of changing a computer program's internal structure without modifying its external behavior or existing functionality. This is usually done to improve code readability, simplify code structure, change code to adhere to a given programming paradigm, improve maintainability, or improve extensibility.” - Wikipedia

If your development process includes proper unit testing practices, refactoring to an apparent design pattern is easily manageable while still maintaining the original purpose and validity of the implementation.

Good software design is an evolutionary process.  In my opinion, a developer should start with one goal in mind: to meet the needs of the customer.  This really the only metric that matters.  Sure, we all want to write “beautiful” code and be academic developers, but the needs of the customer must come first.  The rest will come in due course.  To be a successful developer I think that we need to remember the basics: start simple and write code that works.

There is a meme going around Facebook where everyone is writing 25 random things about themselves.  I thought I would share this on my blog as well.  So without further ado, here are some random facts about me:

 

1. I get really annoyed when people spell my name wrong. In case you are not aware, my full name is 'Jeremiah Christofer Clark'. Even as I write that, I get a spelling error warning on my middle name. Typically, Christofer is spelled 'Christopher', but mine is different, so deal with it. I also often get 'Jerimiah' or 'Jeremia', which are just stupid.

2. On the same name subject, I can't stand the nickname 'Jeremy' that everyone seems to apply to me when they first meet me. People who know me call me 'Miah'. This nickname was given to me by my grandmother when I was very young.

3. I am a pseudo only child. I have 2 half sisters, 3 half brothers, and 1 adopted brother.

4. When I was a young kid, I was deathly afraid of Tomato Worms. My mom used to make me pick the tomatoes from the garden, and I was terrified of them. That is pretty much the only thing I have ever feared. Here is a picture in case you are interested: http://www.flickr.com/photos/organicpixel/237425991/

5. I turned 13 on Friday the 13th. Oh yeah, and it was also Good Friday.

6. I have a man-crush on Ryan Reynolds. Damn you Scarlett Johansson :)

7. I am above average at everything that I do, but great at nothing. It is just something that I have learned to accept.

8. When I was a kid I had a tendency to get my head stuck in things, including the railings at the mall and a fence. I also once fastened a zip-tie around my neck because I thought it would be fun. Yeah, that was a stupid idea.

9. My second and third toe on my left foot are webbed together. Maybe I am the missing link...

10. I love to argue for the sake of arguing. I most likely agree with you on a lot of things, but I like confrontation. It helps me to see all of the different viewpoints on a topic.

11. I don't ever get stressed out. No matter what happens in life, it is always manageable if you have a little patience and think through it.

12. I am a night person. If I go to bed before 2AM, it is a really rare occasion.

13. I am obsessed with getting the maximum achievements on any XBOX 360 game that I play. Some games are much easier than others to do this with.

14. Speaking of obsessions, if I start watching a movie I have to finish it. Even if I have seen it 100 times, I have to finish watching it.

15. I am an Eagle Scout.

16. Why do restaurants/stores that have an entry with double doors always seem to lock one of the doors and make you use the other one? Is there a reason behind this? I absolutely hate walking up to an entrance, pulling on the door, and it wont move. Drives me nuts.

17. The only thing that I miss about being in the Navy was being out to sea. The friends that you make when you are in the middle of the ocean with nothing to do are priceless.

18. My favorite musical/operetta is Les Miserables by Victor Hugo.

19. I am currently working in one of my dream jobs. If you asked me 10 years ago about where I would want to work, the answer would have been Microsoft.

20. Although I love my job, I hate Maryland. Too many people in such a condensed area. I really miss the vastness of Texas. And the friendly people there also.

21. I don't like cats. I don't trust them. They are always up to something.

22. I absolutely hate Cormac McCarthy. If you do not know who that is, he wrote the novel 'No Country For Old Men'. While it is a good story, his writing style totally blows. He is credited as one of the greatest American writers and I couldn't agree less.

23. I have met both Oliver North and Gordon B. Liddy. I guess I have a thing for political henchmen.

24. I have seen Boyz II Men in concert. And it was awesome!

25. If I could live anywhere in the world, it would be in Cairns, Australia. I was fortunate enough to visit most of the larger cities in Australia when I was in the Navy and I love it there.

A few co-workers and I lately have been having this conversation.  The following hypothetical argument illustrates the con of the argument:

How can we be engineers if we can’t agree on what we’re building? Do engineers have conversations like this:

Engineer 1: “It’s a bridge.”

Engineer 2: “No, it’s a span.”

Engineer 1: “Die, heretic!”

My co-worker Scott came up with the above example.  He has also posted a short blurb on his blog about this.  How true is that example though.  We have the above types of conversations/argument all the time when it comes to defining a software solution.

Initially I was on the pro side of this argument, believing that we were indeed Software Engineers.  After some thought and reflection, I have since switched my position to agree with Scott.  Here are some of the reasons for my decision:

  1. I think that we like to apply the term “engineer” to ourselves because we think that it makes our job sound important.  The term historically implies skill, design, construction and creation.   My problem with this is that lately, the term “engineer” has been applied to all kinds of job positions to make them sound more prestigious than they really are.  Over time this term has been devalued.  Now there are positions like garbage engineers (trash collector), administrative engineer (resource manager), and sales engineer (salesman).  Now, I am not trying to imply that these jobs are meaningless or simplistic, but rather that the term “engineer" has recently been used to apply a more prestigious name to the position. 
  2. In my opinion, true engineers operate under specific rules and natural laws.  With software development, we are Gods in our own little world.  Sure we are constrained by certain rules, but those limitations are not as clearly defined as they are with physical engineering.  We don’t have to worry about gravity, weather, or thermodynamics.  Most of our rules are not even exposed to us at the level that we develop, but rather they are abstracted away by the compiler and hardware that we are running on.  Within our development environment, we can do just about anything that we want to.
  3. Mistakes in physical engineering typically result in injury or death.  Mistakes in software design typically only result in inconvenience.  Sure, there are the cases where a bad software design can lead to physical loss, but these are the exception.  For example, consider the Zune leap year bug.  If a nuclear engineer made the same mistake the results could be devastating.  Risk management is much more of a priority for the physical engineering practices than it is for software development (in most cases). 

Edit: I have received some comments pertaining to reason #3.  What I am trying to imply here is that mistakes in physical engineering usually result in more relative cost than mistakes made in software development.  While this reason alone is not enough to make the point, I think that it has to be a factor in the decision.  I also think that there are cases where software developers could be considered engineers.  The discussion that I am trying to have is whether we can apply the blanket label of "Software Engineers" to developers as has recently seemed to be the case in our community.

I like to think of us a more akin to chefs (who could even be called culinary engineers).  We can take many different approaches to reach the same solution.  Some designs might be better than others, but that is of constant debate.  If you put 10 developers in a room and give them a proposal, you will likely have 10 different approaches to achieving the resulting solution.  And the 10 developers will argue their individual approach to the end, each believing that their implementation is more correct than another's.  And in the end, each result might even meet the requirements.  But it is the lack of specific design laws that persuades me to believe that we are not engineers in the true sense of the word.

I am interested to hear what others have to say on the topic, so feel free to flame me or post your reasons for believing one way or the other.

Edit: Another take on the argument: http://savvyduck.blogspot.com/2009/02/its-job-title.html

I have been working on a project that uses the Entity Framework as the persistence store.  I am implementing a global search capability that returns results from the various entities that have a string property that start with a given query string.  So I started out with  writing code for each entity that did something like the following:

One method for Customers:

   1: public IQueryable<Customers> Search(string query)
   2: {
   3:     return entities.Customers.Where(x => x.Name.StartsWith(query);
   4: }

And another for Products:

   1: public IQueryable<Products> Search(string query)
   2: {
   3:     return entities.Products.Where(x => x.ProductName.StartsWith(query);
   4: }

Of course, the search logic in my project is a little more complicated than what is shown above, but we are keeping this simple to show the ideas.  Now imagine that I am implementing this same method for about 10 entities that I am working with.  Some of the issues that come up are code duplication and increased maintenance.  If I change a part of the search logic, I have to change it in 10 different places.  Wouldn’t it be nice if I could write a generic search method that would work across all of the entity types.  I started digging into expression trees and here is the solution that I came up with.

The parameter in the Where methods above is an example of an expression.  I am telling the query what I want it to do when the enumeration is run.  In the case above, it will select each entity where the property (Name for Customers and ProductName for Products) starts with the string specified in the query.

Using a generic expression builder, we can replace the two (or 10) method calls above with a single method that will return the search results for a given entity.  Here is the code for that (I will explain in a minute):

   1: public static IQueryable<T> Search<T>(IQueryable<T> entity, string query, Expression<Func<T, string>> inclusion)
   2: {
   3:     // Get the parameter name from the inclusion expression
   4:     string inclusionString = ((MemberExpression)(inclusion.Body)).Member.Name;
   5:     
   6:     // Get the method information for the String.StartsWith() method
   7:     MethodInfo mi = typeof(String).GetMethod("StartsWith", new Type[] { typeof(String) });
   8:  
   9:     // Build the parameter for the expression
  10:     ParameterExpression X = Expression.Parameter(typeof(T), "x");
  11:  
  12:     // Build the member that was specified for the expression
  13:     MemberExpression field = Expression.PropertyOrField(X, inclusionString);
  14:  
  15:     // Call the String.StartsWith() method on the member
  16:     MethodCallExpression startsWith = Expression.Call(field, mi, Expression.Constant(query));
  17:  
  18:     // Build the expression
  19:     Expression<Func<T, bool>> expression =  Expression.Lambda<Func<T, bool>>(startsWith, X);
  20:  
  21:     // Perform the search logic and return the results
  22:     return entity.Where(expression);
  23: }

First, this may seem like more code, but remember that we are working with 10 entities here.  Also, the logic for the search is now contained in one place, so if we need to make changes we only have to do it in one place. 

This can now be called by using the following code, which will use the common method to return the Products and Customers that start with the letter  “J”:

   1: Search<Customers>(entities.Customers, "J", x => x.Name);
   2: Search<Products>(entities.Products, "J", x => x.ProductName);

So what does the Search<T> method do?  It builds a dynamic expression based on the parameters provided.  We are passing the IQueryable to search, the query string to search for, and the string property of the IQueryable to search on.  Using the Expression class, we are then dynamically building an expression that looks like the following (in the case of the Customers entity):

x => x.Name.StartsWith("J");

This is exactly the same expression that we used in the initial methods at the top of this post.  You can take a look at the generated expression by inserting the following code on line 20 in the Search<T> method body above:

Console.WriteLine(expression.ToString());

This is my first attempt at really digging into expressions in .Net.  I find it very interesting and can think of a lot of uses for dynamic expressions.

Last night I wrote a post about the Visual Studio Unit Testing Extensions that I put out on CodePlex.  I forgot to mention one of my favorite features that the library provides.

I showed how you can use the library to write readable unit tests like the following:

[TestMethod]
public void NewWay_Test()
{
   int number = 5;
   number.ShouldEqual(5);
   number.ShouldBeGreaterThan(4);
   number.ShouldBePositive();
}

Another feature of this library is the ability to chain assertions. Each assertion method returns the original source value, so the same test above can also be written the following way:

[TestMethod]
public void NewWay_Test()
{
   int number = 5;
   number.ShouldEqual(5)
      .ShouldBeGreaterThan(4)
      .ShouldBePositive();
}

I think that this makes the unit test even more readable and also reduces the amount of code that is needed.

If you can think of any features or assertion methods that you would like to see added to the library, please let me know either by commenting on this post or at the CodePlex discussion site.

This is a personal hobby project that I have been working on recently.  The code has been released on CodePlex and can be found here.

The Visual Studio Testing Extensions is a library that exposes a set of extension methods to provide a way to write more readable unit tests in the Visual Studio Unit Testing environment. It is developed in C# using Visual Studio 2008.

This project was created to add to the basic assertions that unit testing in Visual Studio (VS) provides. In VS, the way to do unit testing assertions is to write test code such as the following:

[TestMethod]
public void OldWay_Test()
{
   int number = 5;
   Assert.AreEqual(number, 5);
   Assert.IsTrue(number > 4);
   Assert.IsTrue(number > -1);
}

While this approach is sufficient for most cases, I was looking to provide a more readable way to write unit tests. This library contains a number or extension methods that allow you to perform assertions using the following syntax:

[TestMethod]
public void NewWay_Test()
{
   int number = 5;
   number.ShouldEqual(5);
   number.ShouldBeGreaterThan(4);
   number.ShouldBePositive();
}

When an assertion fails, the failure notification is the same behavior that VS provides out of the box, displaying the assertion that caused the failure and the arguments associated with the assertion.


The other feature that this library provides is the ability to assert multiple expected exceptions in a single test method, rather than being limited to one expected exception like VS provides. You can provide the snippet to test for an exception via an Action() delegate. An example of this is shown below:

[TestMethod]
public void Testing_ExceptionsTest()
{
   int zero = 0;
   Testing.ShouldThrowException<DivideByZeroException>(() => { int y = 15 / zero; });
   Testing.ShouldThrowException<ArgumentNullException>(() => { throw new ArgumentNullException(); });
}

The source release for this project contains a complete suite of unit tests to validate the expected functionality that the library provides. In addition, the unit tests are a good example of the various extension methods that the library provides.


If you are interested in contributing to this project, please let me know.

Function caching, or more specifically memoization, is a code optimization technique that can be used to speed up code that calls complex functions with the same inputs.  Let's take a look at the classic fibonacci function:

   1: private int Fib(int val)
   2: {
   3:     return val <= 2 ? 1 : Fib(val - 2) + Fib(val - 1); 
   4: }

This is a recursive function that computes the nth value of the fibonacci sequence, where n is passed as an argument to the function.  As the value of n increases, the time taken to compute the result increases.  If this function is called multiple times with the same input, the cost associated with the calculation is incurred each time.  It would be nice if we could cache the results of the first call for a specific input and then if the function is called again with the same input, we just return the result from the previous call.  It would also be nice if we could provided a generic way to do this so that it would apply to any type of function.  In this post, I will share a few classes that I wrote to facilitate this type of function caching.

The following code is a class that provides the caching mechanism for a given function that consists of a single argument.

   1: public sealed class CachedFunction<T, TResult>
   2: {
   3:     private Func<T, TResult> _function;
   4:     private int _cacheSize;
   5:     private Dictionary<T, CacheInformation<T, TResult>> _cache;
   6:  
   7:     // The constructor for the CachedFunction class.
   8:     private CachedFunction(Func<T, TResult> function, int cacheSize)
   9:     {
  10:         this._function = function;
  11:         this._cacheSize = cacheSize;
  12:         this._cache = new Dictionary<T, CacheInformation<T, TResult>>(this._cacheSize);
  13:     }
  14:  
  15:     // A factory method that created a new instance of the CacheFunction class with the default cache size.
  16:     public static CachedFunction<T, TResult> Create(Func<T, TResult> function)
  17:     {
  18:         return Create(function, 10);
  19:  
  20:     }
  21:  
  22:     // A factory method that created a new instance of the CacheFunction class.
  23:     public static CachedFunction<T, TResult> Create(Func<T, TResult> function, int cacheSize)
  24:     {
  25:         if (function == null)
  26:             throw new ArgumentNullException("function");
  27:         if (cacheSize <= 0)
  28:             throw new ArgumentOutOfRangeException("cacheSize", Resources.ArgumentOutOfRangeExceptionIntLessThanOneMessage);
  29:  
  30:         return new CachedFunction<T,TResult>(function, cacheSize);
  31:     }
  32:  
  33:     // This method is called to execute the function with the argument specified.
  34:     // If the argument exists in the cache, the cached result is returned, otherwise
  35:     // the original function is called and the result is added to the cache.
  36:     public TResult Execute(T arg1)
  37:     {
  38:         if (this._cache.ContainsKey(arg1))
  39:             return this.GetReturnFromCache(arg1);
  40:         else
  41:         {
  42:             TResult returnValue = this._function(arg1);
  43:             this.AddToCache(arg1, returnValue);
  44:             return returnValue;
  45:         }
  46:     }
  47:  
  48:     // This method adds a new argument/result pair to the cache.  If the size
  49:     // if the cache dictionary exceeds the cache size value, then the oldest cached
  50:     // result with the smallest number of executions is removed from the cache.
  51:     private void AddToCache(T argument1, TResult returnValue)
  52:     {
  53:         if (this._cache.Count >= this._cacheSize)
  54:         {
  55:             int min = this._cache.Min(x => x.Value.ExecutionCount);
  56:             this._cache.Remove(this._cache.First(x => x.Value.ExecutionCount == min).Key);
  57:         }
  58:  
  59:         this._cache.Add(argument1, CacheInformation<T, TResult>.Create(argument1, returnValue));
  60:     }
  61:  
  62:     // This method returns a function result from the cache that corresponds
  63:     // to the given argument.
  64:     private TResult GetReturnFromCache(T argument1)
  65:     {
  66:         return this._cache[argument1].ReturnValue;
  67:     }
  68: }

The cache dictionary in the code above contains a class that represents the functions argument, return value, and the number of times that this instance of the function has been called.  That code is shown below:

   1: internal sealed class CacheInformation<T, TResult>
   2: {
   3:     private TResult _returnValue;
   4:     private int _executionCount;
   5:  
   6:     private CacheInformation(T argument1, TResult returnValue)
   7:     {
   8:         this.ExecutionCount = 0;
   9:         this.Argument1 = argument1;
  10:         this.ReturnValue = returnValue;
  11:     }
  12:  
  13:     public static CacheInformation<T, TResult> Create(T argument1, TResult returnValue)
  14:     {
  15:         return new CacheInformation<T, TResult>(argument1, returnValue);
  16:     }
  17:  
  18:     public T Argument1 { get; private set; }
  19:     
  20:     public TResult ReturnValue 
  21:     {
  22:         get
  23:         {
  24:             Interlocked.Increment(ref this._executionCount);
  25:             return this._returnValue;
  26:         }
  27:         private set
  28:         {
  29:             this._returnValue = value;
  30:         }
  31:     }
  32:  
  33:     public int ExecutionCount 
  34:     { 
  35:         get
  36:         { 
  37:             return this._executionCount;
  38:         }
  39:         private set
  40:         {
  41:             this._executionCount = value;
  42:         }
  43:     }
  44:     
  45: }

Now let's take a look at how we can implement the same fibonacci function that we started with, but this time with the caching mechanism that we have implemented.

   1: private CachedFunction<int, int> myFunc;
   2:  
   3: public Program()
   4: {
   5:     myFunc = CachedFunction<int, int>.Create(x => Fib(x));
   6: }
   7:  
   8: private int Fib(int val)
   9: {
  10:     return val <= 2 ? 1 : Fib(val - 2) + Fib(val - 1); 
  11: }
  12:  
  13: public int DoFib(int val)
  14: {
  15:     return myFunc.Execute(val);
  16: }
  17:  
  18: static void Main(string[] args)
  19: {
  20:     Program p = new Program();
  21:     Console.WriteLine(p.DoFib(40));
  22:     Console.WriteLine(p.DoFib(39));
  23:     Console.WriteLine(p.DoFib(40));
  24:     Console.WriteLine(p.DoFib(39));
  25:     Console.WriteLine(p.DoFib(39));
  26:     Console.WriteLine(p.DoFib(39));
  27:     Console.WriteLine(p.DoFib(39));
  28:     Console.WriteLine(p.DoFib(40));
  29:     Console.WriteLine(p.DoFib(40));
  30:     Console.WriteLine(p.DoFib(40));
  31:     Console.WriteLine(p.DoFib(40));
  32: }

When the code above is executed, the first two calls will take some time to compute and then the following calls will return immediately with the cached result for 39 and 40.

This concept only provides value for functions that take some time to compute.  If the function is simple, like returning the square of an input, the cost associated with caching may outweigh the cost of the actual operation.  But in the case of something rather complex, this can save a lot of time if the inputs to a function are likely to be the same. 

The example I provided also only works for a function that takes a single argument, but this could be easily modified using a Tuple to provide support for functions that take multiple arguments.

This is something that I put together in a few minutes to provide a way to refresh a partial view on a specified time interval.

Let's create a MVC User Control that displays the current date and time called "TimeControl.ascx":

   1: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TimeControl.ascx.cs" Inherits="SAWeb.UI.Views.UserControls.TimeControl" %>
   2: <div>
   3: <%= DateTime.Now.ToString() %>
   4: </div>

We can render this in a view using the Html.RenderPartial() method.  How can we update this control using AJAX?  MVC provides an Ajax.ActionLink() helper method that we could use.  An example of this can be found here and here.  The only problem with this is that you have to click a link to update the control.  What if we want it to automatically update the partial view control via AJAX on a certain time interval, like every 5 seconds?  To do this, I have created a helper method that provides this functionality. 

The code for the helper method (Html.RenderPartialRefresh) is shown below:

   1: public static class RenderExtensions
   2: {    
   3:     // Extension method to render a partial view every interval specified.
   4:     public static void RenderPartialRefresh(this HtmlHelper htmlHelper, string name, string controller, string actionMethod, 
   5:         TimeSpan interval, string partialViewName)
   6:     {
   7:         RenderPartialRefresh(htmlHelper, name, controller, actionMethod, interval, partialViewName, htmlHelper.ViewData);
   8:     }
   9:  
  10:     // Extension method to render a partial view every interval specified, and providing a model to the control.
  11:     public static void RenderPartialRefresh(this HtmlHelper htmlHelper, string name, string controller, string actionMethod, 
  12:         TimeSpan interval, string partialViewName, object model)
  13:     {
  14:         if (model == null)                
  15:             throw new ArgumentNullException("model");
  16:         if (String.IsNullOrEmpty(name))
  17:             throw new ArgumentException("Argument cannot be null or empty.", "name");
  18:         if (String.IsNullOrEmpty(partialViewName))
  19:             throw new ArgumentException("Argument cannot be null or empty.", "partialViewName");
  20:  
  21:         // Building the javascript that registers the interval and performs the AJAX request.
  22:         StringBuilder builder = new StringBuilder();
  23:         builder.Append("<script language=\"javascript\">");
  24:         builder.Append("setInterval(function() {");
  25:         builder.Append("Sys.Mvc.MvcHelpers.$1(");
  26:         builder.AppendFormat("'{0}',", GenerateUrl(htmlHelper.ViewContext, null, actionMethod, controller, new RouteValueDictionary()));
  27:         builder.Append("'post','','', { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: '");
  28:         builder.AppendFormat("{0}", name);
  29:         builder.Append("'});},");
  30:         builder.AppendFormat("{0});", interval.TotalMilliseconds);
  31:         builder.Append("</script>");
  32:  
  33:         // Wraps the partial view in a div tag so that we can update by the id of the div.
  34:         htmlHelper.ViewContext.HttpContext.Response.Output.Write(builder.ToString());
  35:         htmlHelper.ViewContext.HttpContext.Response.Output.Write("<div id=\"{0}\" name=\"{0}\">", name);
  36:         htmlHelper.RenderPartial(partialViewName, model);
  37:         htmlHelper.ViewContext.HttpContext.Response.Output.Write("</div>");
  38:     }
  39:  
  40:     // Method to generate the URL given the controller and action method.
  41:     private static string GenerateUrl(ViewContext viewContext, string routeName, string actionName, 
  42:         string controllerName, RouteValueDictionary valuesDictionary)
  43:     {
  44:         UrlHelper helper = new UrlHelper(viewContext);
  45:         Type t = typeof(UrlHelper);
  46:         Object[] paramArray = { routeName, actionName, controllerName, valuesDictionary };
  47:         MethodInfo m = t.GetMethod("GenerateUrl", BindingFlags.NonPublic | BindingFlags.Instance);
  48:         string s = (string)m.Invoke(helper, paramArray);
  49:         return HttpUtility.HtmlAttributeEncode(s);
  50:     }
  51: }

The next step is to make sure that we have the AJAX scripts registered.  In the master page or the view, ensure that you have the following script references (with the correct path to the scripts):

   1: <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
   2: <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

And now, lets create a controller action method to return the partial view when called.  In this example, we will add the action method to the Home controller, and it simply returns a View of the TimeControl.ascx partial view.  This is called by the AJAX script every interval to update the partial view.

   1: [HandleError]
   2: public class HomeController : Controller
   3: {
   4:     ...
   5:  
   6:     // Simple action method that returns the partial view for the TimeControl.ascx
   7:     public ActionResult GetTimeControl()
   8:     {
   9:         return View("/Views/UserControls/TimeControl.ascx");
  10:     }
  11: }

Finally, to render the auto updating view, we can use the helper method that we created above, passing the name for the wrapping div ("timeDisplay"), the controller and action method to call for the update ("Home" and "GetTimeControl"), the TimeSpan for the interval (5 seconds), and the partial view to render ("TimeControl.ascx"):

   1: <h2>Auto Updating Partial View Example</h2>
   2:  
   3: <% Html.RenderPartialRefresh("timeDisplay", "Home", "GetTimeControl", new TimeSpan(0, 0, 5), "/Views/UserControls/TimeControl.ascx"); %>

Initially, the View will be rendered with the Date and Time of the request as shown below:

image

And every five seconds, the partial view control will update via AJAX (without a postback) to reflect the current time.  The image below shows the same page after 80 seconds without the need for a refresh.  You can see that the time has automatically updated.

image

The trickiest part of this was determining the javascript to perform the AJAX request.  There might be a better (and cleaner) way to do this, but this is something that I put together in about 20 minutes.  The goal of this is to show the power of AJAX in MVC and the ease of creating extension helpers in MVC to provide the functionality that you might need.

So I was thinking tonight, what if I want my MVC application to serve images that are stored in a SQL database as binary data? Or files that are stored in the database?   One of the things that I really like about MVC is that ability to add custom functionality in a fairly simple way.  A few days ago, I wrote a post showing how to implement a custom HtmlHelper method for rendering a group of checkboxes.  In this post, we are going to create a custom ActionResult class that can serve an image as the return value from a controller action method.

In the typical controller action method, a View is returned.  This allows the controller to render the View as the response for the web request.  You are probably familiar with this if you have been using MVC.  Here is a common example of this:

   1: public class HomeController : Controller
   2: {
   3:     public ActionResult Index()
   4:     {
   5:         ViewData["Title"] = "Home Page";
   6:         ViewData["Message"] = "Welcome to ASP.NET MVC!";
   7:  
   8:         return View();
   9:     }
  10: }

In the code above, View() is a method on the Controller class that returns a ViewResult.  ViewResult is a class that inherits from ActionResult.  The ViewResult class finds the associated view and renders the view to the output stream of the web response.  JsonResult is another type that can be returned in an action method.  JsonResult performs javascript serialization on some data and writes the serialized data to the web response.

So to answer our initial question, let's create an ImageResult class that will write the bytes of an image to the web response.  The code below is fairly straightforward - we inherit from ActionResult, define some properties that we need, set the properties in the constructor, and then create and return the response.

   1: public class ImageResult : ActionResult
   2: {
   3:     public ImageResult(Stream imageStream, string contentType)
   4:     {
   5:         if (imageStream == null)
   6:             throw new ArgumentNullException("imageStream");
   7:         if (contentType == null)
   8:             throw new ArgumentNullException("contentType");
   9:  
  10:         this.ImageStream = imageStream;
  11:         this.ContentType = contentType;
  12:     }
  13:  
  14:     public Stream ImageStream { get; private set; }
  15:     public string ContentType { get; private set; }
  16:  
  17:     public override void ExecuteResult(ControllerContext context)
  18:     {
  19:         if (context == null)
  20:             throw new ArgumentNullException("context");
  21:  
  22:         HttpResponseBase response = context.HttpContext.Response;
  23:  
  24:         response.ContentType = this.ContentType;
  25:         
  26:         byte[] buffer = new byte[4096];
  27:         while (true)
  28:         {
  29:             int read = this.ImageStream.Read(buffer, 0, buffer.Length);
  30:             if (read == 0)
  31:                 break;
  32:  
  33:             response.OutputStream.Write(buffer, 0, read);
  34:         }
  35:  
  36:         response.End();
  37:     }
  38: }

The next thing that I did was create a set of extension methods for the Controller class.  All that these methods do is create and return a new instance of the ImageResult class based on the arguments.  This allows you to pass the image as either a stream or a byte array.

   1: public static class ControllerExtensions
   2: {
   3:     public static ImageResult Image(this Controller controller, Stream imageStream, string contentType)
   4:     {
   5:         return new ImageResult(imageStream, contentType);
   6:     }
   7:  
   8:     public static ImageResult Image(this Controller controller, byte[] imageBytes, string contentType)
   9:     {
  10:         return new ImageResult(new MemoryStream(imageBytes), contentType);
  11:     }
  12: }

Now that we have that done, let's create a controller action method to get the images.  We just need to specify the binary image data and the content type for the image.

   1: public class HomeController : Controller
   2: {
   3:     public ActionResult Images(string id)
   4:     {
   5:         // Here is where we would take the id that was passed as
   6:         // the argument and get the image from the database or 
   7:         // filesystem.  In this example though, I am just going to 
   8:         // return the same image from my local hard drive 
   9:         // regardless of the id parameter.
  10:  
  11:         byte[] image = File.ReadAllBytes(@"C:\netLogo.jpg");
  12:         string contentType = "image/jpeg";
  13:  
  14:         // Here we are calling the extension method and returning    
  15:         // the ImageResult.
  16:         return this.Image(image, contentType);
  17:     }
  18: }

And we are done, and it was pretty easy.  In just a few dozen lines of code, we have provided a way to return images from a controller action without the need to create a view.  The result looks are shown below (and notice how we can user a meaningful URL, rather than something like "GetFile.aspx?filename=netLogo.jpg"):

image

We could do the same thing to return files from a database server by creating a FileResult class that is similar to ImageResult.  In fact, the only difference needed is to change the content type to "application/octet-stream" and then the browser will prompt the user for where to save the file.

image

Ok, I have to admit it: jQuery is awesome.  If you haven't started looking at it, I highly recommend that you do.  It works wonders in the ASP.NET MVC world.  One of the best things about jQuery is the enormous number of plug-ins that are available for adding even more functionality to the library.

The plug-in that I am going to be talking about in this post is jQuery Autocomplete

So let's make a autocomplete text box in MVC for adding tags (or labels) for a blog post.  First, we are going to need to put a text box in one of our views with the name "tags".

   1: <div>
   2:     <%= Html.TextBox("postTags")  %>
   3: </div>

Now, in the same view (or the master page) we need to add the references for jQuery Autocomplete.  The plug-in also comes with a stylesheet for styling the drop-down that will contain the autocomplete options.

   1: <link href="/Content/jquery.autocomplete.css" rel="stylesheet" type="text/css" media="screen" />
   2: <script type="text/javascript" src="/Scripts/jquery-1.2.6.js"></script>
   3: <script type="text/javascript" src="/Scripts/jquery.autocomplete.js"></script>

Next, we need to create a controller action that will return the list of autocomplete values in the JSON format. 

   1: [HandleError]
   2: public class UtilitiesController : Controller
   3: {
   4:     /// <summary>
   5:     /// This action method looks up the tags.
   6:     /// </summary>
   7:     /// <param name="q">The query that contains the user input.</param>
   8:     /// <param name="limit">The number of tags return.</param>
   9:     public ActionResult LookupTags(string q, int limit)
  10:     {
  11:         // We can get a list of tags from the database, but 
  12:         // for this example, I will populate a list with values.
  13:         List<string> tags = new List<string>();
  14:         tags.Add("asp");
  15:         tags.Add("mvc");
  16:         tags.Add("microsoft");
  17:         tags.Add("sql server");
  18:         tags.Add("jQuery");
  19:         tags.Add("ajax");
  20:  
  21:         // Select the tags that match the query, and get the 
  22:         // number or tags specified by the limit.
  23:         var retValue = tags
  24:             .Where(x => x.StartsWith(q))
  25:             .OrderBy(x => x)
  26:             .Take(limit)
  27:             .Select(r => new { Tag = r });
  28:  
  29:         // Return the result set as JSON
  30:         return Json(retValue);
  31:     }
  32: }

Finally, we have to add the jQuery Autocomplete initialization script in the view (or master page) to wire up the plug-in to the text box.  Notice in line 4 that we are using a the action method that we created above to get the list of tags.

   1: <script type="text/javascript">
   2: $(document).ready(function() 
   3: {
   4:     $("#postTags").autocomplete('<%=Url.Action("LookupTags", "Utilities") %>', 
   5:     {
   6:         dataType: 'json',
   7:         parse: function(data) 
   8:         {
   9:             var rows = new Array();
  10:             for (var i = 0; i < data.length; i++) 
  11:             {
  12:                 rows[i] = { data: data[i], value: data[i].Tag, result: data[i].Tag };
  13:             }
  14:             return rows;
  15:         },
  16:         formatItem: function(row, i, max) 
  17:         {
  18:             return row.Tag;
  19:         },
  20:         width: 300,
  21:         highlight: false,
  22:         multiple: true,
  23:         multipleSeparator: ","
  24:     });
  25: });
  26: </script>

The documentation for the plug-in details all of the various options that can be used in the autocomplete function.

Now we have an AJAX enabled autocomplete box using jQuery in ASP.NET MVC.

image

The power of jQuery never ceases to amaze me.  There will likely be plenty more posts to come on the topic of using jQuery in MVC.

The early previews of the MVC Toolkit contained a few helpers that are not available in the current MVC Beta and MVC Beta Futures.  On of the ones that was nixed was the CheckBoxList helper.  I was in need of this type of functionality lately and found myself out of luck.  I needed to add a dynamic list of checkboxes to a form, like the roles that a user could possible be a member of.  These roles could be added to or deleted from at any time.

I looked to the Html.CheckBox helper to see if that would work.  This helper can be used like so:

   1: /* The model for this is a Dictionary<string,bool> that contains 
   2:    the name for the role and whether the user is a member */
   3:  
   4: <% foreach (var info in ViewData.Model) { %>
   5:     <div><%= Html.CheckBox(info.Key, info.Value) %> <%= info.Key %></div>
   6: <% } %>

The problem with using Html.CheckBox for my scenario arises when you need to get the values in the form ActionMethod.  For Html.CheckBox, the form handler is expecting a boolean parameter for each checkbox.  An example is show below.

   1: [AcceptVerbs(HttpVerbs.Post)]
   2: public ActionResult Roles(bool administrator, bool user, bool poweruser)
   3: {
   4:     // Each bool parameter is the checked value for the checkbox that 
   5:     // has the same name.  If my list of roles is dynamic, this does
   6:     // not work so well :(
   7: }

As you can see, this would not satisfy the requirements that I had.  So what is the answer?  Create my own CheckBoxList helper of course.

Here is the extension method code for my implementation, along with a simple class that contains the info needed for each checkbox in the list..

   1: public static class InputExtensions
   2: {
   3:     public static string CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo)
   4:     {
   5:         return htmlHelper.CheckBoxList(name, listInfo,
   6:             ((IDictionary<string, object>) null));
   7:     }
   8:  
   9:     public static string CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo,
  10:         object htmlAttributes)
  11:     {
  12:         return htmlHelper.CheckBoxList(name, listInfo, 
  13:             ((IDictionary<string, object>)new RouteValueDictionary(htmlAttributes)));
  14:     }
  15:  
  16:     public static string CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo,
  17:         IDictionary<string, object> htmlAttributes)
  18:     {
  19:         if (String.IsNullOrEmpty(name))
  20:             throw new ArgumentException("The argument must have a value", "name");
  21:         if (listInfo == null)
  22:             throw new ArgumentNullException("listInfo");
  23:         if (listInfo.Count < 1)
  24:             throw new ArgumentException("The list must contain at least one value", "listInfo");
  25:  
  26:         StringBuilder sb = new StringBuilder();
  27:  
  28:         foreach (CheckBoxListInfo info in listInfo)
  29:         {
  30:             TagBuilder builder = new TagBuilder("input");
  31:             if (info.IsChecked) builder.MergeAttribute("checked", "checked");
  32:             builder.MergeAttributes<string, object>(htmlAttributes);
  33:             builder.MergeAttribute("type", "checkbox");
  34:             builder.MergeAttribute("value", info.Value);
  35:             builder.MergeAttribute("name", name);
  36:             builder.InnerHtml = info.DisplayText;
  37:             sb.Append(builder.ToString(TagRenderMode.Normal));
  38:             sb.Append("<br />");
  39:         }
  40:  
  41:         return sb.ToString();
  42:     }
  43: }
  44:  
  45: // This the information that is needed by each checkbox in the
  46: // CheckBoxList helper.
  47: public class CheckBoxListInfo
  48: {
  49:     public CheckBoxListInfo(string value, string displayText, bool isChecked)
  50:     {
  51:         this.Value = value;
  52:         this.DisplayText = displayText;
  53:         this.IsChecked = isChecked;
  54:     }
  55:  
  56:     public string Value { get; private set; }
  57:     public string DisplayText { get; private set; }
  58:     public bool IsChecked { get; private set; }
  59: }

This can then be used to render the list of checkboxes in a View as shown below:

   1: /* Where ViewData.Model is a List of CheckBoxListInfo objects that
   2:    provide the details for the checkboxes. */
   3:  
   4: <div><%= Html.CheckBoxList("roles", ViewData.Model) %></div>

And now, in the post ActionMethod, we can access the ones that have been checked like so:

   1: [AcceptVerbs(HttpVerbs.Post)]
   2: public ActionResult Roles(string[] roles)
   3: {
   4:     /* The 'roles' parameter contains the values from the 
   5:        checkboxes that were checked. */
   6: }

In addition to solving the issue that I was having, this post shows how easy it is to implement your own custom helpers in MVC.

More Posts Next page »
 
Page view tracker