Wednesday, October 21, 2009

VS2010: A First Look at Beta 2 for ASP.NET – Part 1

If you haven’t yet downloaded Visual Studio 2010 Beta 2, what are you waiting for? Until then, here’s a first look at what’s new for ASP.NET developers with .NET 4 and Visual Studio 2010.

Visual Changes

image

First off, there’s a new splash screen and icon! I know, I know, this really isn’t important for day-to-day use. But I feel it reflects Microsoft’s renewed commitment to great user experience. Personally, I absolutely love it.

image

This is the new icon that shows up in the taskbar.

image

Also there’s a new theme for the overall UI. A bit darker, and 100% more awesome. Even the menus are in WPF, so it feels more “2010” and less “2003”.

New ASP.NET Default Template

image

When you do File –> New Project and choose the ASP.NET Web Application project template, you now get a much more robust project template by default for new web forms projects, complete with authentication, much like the default ASP.NET MVC project template.

Snippets for ASPX Markup

image

The awesome snippets that make coding in C# and VB more fun have made their way to ASPX markup. Start typing “<button” and press tab twice to get a button snippet like this. One annoying issue I’ve noticed is that trying to type a normal <a> tag is painful, because it tries to put in an <accessdatasource> snippet instead. Hopefully this will be resolved by the next Beta/RC.

Client ID Mode

There is a new ClientIDMode attribute that can be applied to most server controls that changes the output ID to make it more JavaScript and CSS friendly. Given the following ASPX code:

<asp:Panel ID="pnlContent" runat="server" ClientIDMode="Static">
This is some content
</asp:Panel>
The following HTML is outputted:
<div id="pnlContent">
This is some content
</div>
As compared to the following HTML output without ClientIDMode=”Static”:
<div id="MainContent_pnlContent">
This is some content
</div>
Which, as you know, if that pnlContent panel was nested 5 layers deep in controls, you would see each of those layers’ IDs present in its ID. This makes the IDs of the elements predictable for use in JavaScript and CSS.

HTML Encoding Block Syntax

Especially when dealing with ASP.NET MVC, but also with WebForms, you end up needing to HTML encode output when using the ASP-style blocks. With the following code-behind:
protected void Page_Load(object sender, EventArgs e)
{
FooterContent = "Hello <World> !";
}

public string FooterContent { get; set; }
And the following ASPX page:
<%= FooterContent %>
We get the following output:

image

But if we wanted to HTML encode that output, we previously would need to do this:
<%= Server.HtmlEncode(FooterContent) %>
Now, we can use a new block syntax to do the same, without the function call:
<%: FooterContent %>
And now we get properly escaped HTML output:
Hello &lt;World&gt; !
Which shows up properly in our browser as we would expect:

image

Tuesday, October 6, 2009

Extension Methods on Null References

I was wondering the other day, why can’t we have extension methods on null references? For example, if I have a null IList<string>, and I call the static extension method FirstOrDefault(), which returns null if there are no items, why can’t I call it anyways even if the IList<string> is null? The method is static, so it doesn’t rely on an instance, and it could reduce code in many instances. The following code would throw an exception, but I feel it should return a null value.

IList<string> myList = null;
string first = myList.FirstOrDefault();


If that were possible, to call extension methods safely on null references, here’s an example of a TrimOrDefault() method that would trim the string if not null, or return string.Empty if null:



public static class Extensions
{
public static string TrimOrDefault(this string input)
{
if (string.IsNullOrEmpty(input))
return string.Empty;

return input.Trim();
}
}


What do you think? What are the pros and cons?

Wednesday, September 30, 2009

Creating Your Own IoC Container: Part 2

In the first part of this post series (which, honestly, I didn’t intend to need a Part 2), I discussed how you can easily create your own container for basic inversion of control (IoC) needs. However, many people may need to use Dependency Injection (DI) as well, so I’ve modified the project to support DI.

Also, a colleague pointed out that there’s another reason why you may want to do this – to simply see how it all works. Sure, you can plop Ninject into a project and start using DI/IoC, but creating your own makes you realize what’s really involved and going on behind-the-scenes.

Here I’ve modified the previous example to support DI, and it took less than an hour.

Warning: I have only briefly tested this code, and have not created unit tests. Before using in production, I’d recommend testing it thoroughly. You’ll also need to get the previous post working on your end before integrating these features. I also noticed a bug after publishing this post reading through the code that if you request an IFoo, and Foo : IFoo has a constructor that is asking for an IFoo parameter, you'll end up in an endless loop and probably stack overflow. Ideally this should detect a circular Resolve() call, and throw an exception.

The IServiceResolver Interface

This bit is not required, however I realized as I was writing the DependencyInjector class below that I was tightly coupling it with ServiceResolver from the previous post. Since this is very much an anti-pattern, I decided to make ServiceResolver implement an interface, so that you can use your own IServiceResolver implementation with this DependencyInjector class. Here’s the interface:

using System;

namespace Core
{
public interface IServiceResolver
{
void Register<TFrom, TTo>();
T Resolve<T>();
object Resolve(Type fromType);
}
}


Notice that I’ve added a non-generic version of this class. This was done for compatibility, and now the ServiceResolver class looks like the following. The major changes are it now implements the IServiceResolver interface, and there is the new non-generic method which is called by the generic method. Also, it does not throw an exception if there has not been a registration for the given type. Instead, it creates a new object and looks for any injections. This is to remove the need to bind items to themselves. Note that there is still a tight coupling in the default constructor to DependencyInjector. You may wish to remove this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
/// <summary>
/// Resolves abstract types or interfaces to concrete implementations. Use <see cref="ServiceLocator" /> for static/shared access.
/// </summary>
public class ServiceResolver : IServiceResolver
{
private Dictionary<Type, object> _store;
private Dictionary<Type, Type> _bindings;

/// <summary>
/// Default constructor; instantiates a new ServiceResolver object.
/// </summary>
public ServiceResolver()
{
this.DependencyInjector = new DependencyInjector(this);
_store = new Dictionary<Type, object>();
_bindings = new Dictionary<Type, Type>();
}

/// <summary>
/// Creates a new ServiceResolver with a given IDependencyInjector.
/// </summary>
/// <param name="injector">The IDependencyInjector to use for dependency injection.</param>
public ServiceResolver(IDependencyInjector injector)
{
this.DependencyInjector = injector;
_store = new Dictionary<Type, object>();
_bindings = new Dictionary<Type, Type>();
}

/// <summary>
/// Gets an implementation object of a registered abstract type or interface.
/// </summary>
/// <typeparam name="T">The registered abstract type or interface to look up.</typeparam>
/// <returns>Returns an object of the given type.</returns>
public T Resolve<T>()
{
return (T)Resolve(typeof(T));
}

/// <summary>
/// Gets an implementation object of a registered abstract type or interface.
/// </summary>
/// <param name="fromType">The registered abstract type or interface to look up.</param>
/// <returns>Returns an object of the given type.</returns>
public object Resolve(Type fromType)
{
// check for registration
if (!_bindings.ContainsKey(fromType))
return DependencyInjector.GetInjectedInstance(fromType);

// get destination type
Type dest = _bindings[fromType];

// check for already requested object
if (_store.ContainsKey(dest))
return _store[dest];

// create a new instance of this type
object obj = DependencyInjector.GetInjectedInstance(dest);

// add to store for future use
_store.Add(dest, obj);

return obj;
}

/// <summary>
/// Registers a type with its corresponding implementation type.
/// </summary>
/// <typeparam name="TFrom">The abstract type or interface to use as a key.</typeparam>
/// <typeparam name="TTo">The implementation type to use as a value.</typeparam>
public void Register<TFrom, TTo>()
{
_bindings.Add(typeof(TFrom), typeof(TTo));
}

/// <summary>
/// Gets or sets a dependency injector to use for types that need injection.
/// </summary>
public IDependencyInjector DependencyInjector { get; set; }

}
}


The InjectAttribute class



In order to tell our DependencyInjector class that we want to inject something, we need to decorate either a constructor or some properties (or both) with an [Inject] attribute. If you’ve never created your own attributes, all you have to do is create a new class with a name that ends in Attribute (the “Attribute” bit is cut off on use) and make it inherit from Attribute. Here’s our empty InjectAttribute class:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Constructor)]
public class InjectAttribute : Attribute
{

}
}

the IDependencyInjector Interface


Since we want to make our DependencyInjector loosely coupled with any use of it, we want to make it implement an interface.


using System;

namespace Core
{
public interface IDependencyInjector
{
T GetInjectedInstance<T>() where T : class;
object GetInjectedInstance(Type fromType);
IServiceResolver ServiceResolver { get; set; }
}
}

The DependencyInjector Class


Now that we have all of the plumbing out of the way, we can show off our new DependencyInjector class.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Core
{
/// <summary>
/// A class for getting instances of objects that need dependencies injected to function.
/// </summary>
public class DependencyInjector : IDependencyInjector
{
/// <summary>
/// Creates a new DependencyInjector with a default IServiceResolver for resolving types.
/// </summary>
public DependencyInjector() : this(new ServiceResolver())
{ }

/// <summary>
/// Creates a new DependencyInjector with a given IServiceResolver for resolving types.
/// </summary>
/// <param name="resolver">The IServiceResolver to use for resolving types to implementations.</param>
public DependencyInjector(IServiceResolver resolver)
{
this.ServiceResolver = resolver;
}

/// <summary>
/// Gets or sets an IServiceResolver to use for resolving types to implementations.
/// </summary>
public IServiceResolver ServiceResolver { get; set; }

/// <summary>
/// Gets an injected instance of a given type.
/// </summary>
/// <typeparam name="T">The type to instantiate and inject.</typeparam>
/// <returns>Returns a new instance of the given type.</returns>
public virtual T GetInjectedInstance<T>() where T : class
{
return (T)GetInjectedInstance(typeof(T));
}

/// <summary>
/// Gets an injected instance of a given type.
/// </summary>
/// <param name="fromType">The type to instantiate and inject.</param>
/// <returns>Returns a new instance of the given type.</returns>
public virtual object GetInjectedInstance(Type fromType)
{
object obj = null;

foreach (var constructor in fromType.GetConstructors())
{
// look for inject attribute
var attr = GetConstructorInjectAttribute(constructor);

if (attr != null)
{
// get parameters to inject
var parmValues = GetResolvedParameterValues(constructor);

if (parmValues.Count > 0)
obj = Activator.CreateInstance(fromType, parmValues.ToArray());

break;
}
}

// handle case where no constructor injections
if (obj == null)
obj = Activator.CreateInstance(fromType);

foreach (var prop in fromType.GetProperties())
{
// look for inject attribute
var attr = GetPropertyInjectAttribute(prop);

if (attr != null)
prop.SetValue(obj, ServiceResolver.Resolve(prop.PropertyType), new object[] { });
}

return obj;
}

/// <summary>
/// Gets an InjectAttribute (if any) for the given constructor.
/// </summary>
/// <param name="constructor">The constructor to inspect for an InjectAttribute.</param>
/// <returns>Returns an InjectAttribute if exists, or null if not.</returns>
protected virtual InjectAttribute GetConstructorInjectAttribute(ConstructorInfo constructor)
{
var attrs = constructor.GetCustomAttributes(typeof(InjectAttribute), true);
return attrs.OfType<InjectAttribute>().FirstOrDefault();
}

/// <summary>
/// Gets an InjectAttribute (if any) for the given property.
/// </summary>
/// <param name="prop">The property to inspect for an InjectAttribute.</param>
/// <returns>Returns an InjectAttribute if exists, or null if not.</returns>
protected virtual InjectAttribute GetPropertyInjectAttribute(PropertyInfo prop)
{
var attrs = prop.GetCustomAttributes(typeof(InjectAttribute), true);
return attrs.OfType<InjectAttribute>().FirstOrDefault();
}

/// <summary>
/// Gets a list of parameter values for the given constructor, resolved by the ServiceResolver.
/// </summary>
/// <param name="constructor">The constructor to resolve parameters for.</param>
/// <returns>Returns a new list of parameter values.</returns>
protected virtual List<object> GetResolvedParameterValues(ConstructorInfo constructor)
{
var parms = constructor.GetParameters();
List<object> parmValues = new List<object>();

foreach (var parm in parms)
{
if (parm.ParameterType.IsInterface || parm.ParameterType.IsAbstract)
{
Type parmType = parm.ParameterType;
object parmValue = ServiceResolver.Resolve(parmType);
parmValues.Add(parmValue);
}
else
throw new InvalidOperationException("Unable to inject a parameter that is not an interface or abstract type.");
}

return parmValues;
}

}
}

I’m not going to cover line-by-line what this class does, but basically it looks for any InjectAttributes decorating a constructor or properties, and if it finds them, it resolves instances automatically using the ServiceLocator (another tight coupling) and fills them in.


Usage


Back in our ASP.NET MVC test app, we have created a new interface to use for testing, ILogger. It has one implementation (but could have many), and this one is WebLogger which writes out the log message to the current HttpResponse.


using System;

namespace CustomIoCMvc.Models
{
public interface ILogger
{
void Log(string message);
}
}

And here’s our WebLogger:


using System;
using System.Web;

namespace CustomIoCMvc.Models
{
public class WebLogger : ILogger
{
public void Log(string message)
{
HttpContext.Current.Response.Write(message);
}
}
}

We, of course, need to wire up this implementation in our Global.asax.cs:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);

// register types
ServiceLocator.Register<ICustomerRepository, CustomerRepository>();
ServiceLocator.Register<ILogger, WebLogger>();

}

Our CustomerRepository is going to now use an ILogger for all of its calls. Here it is with a Constructor injection:


using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using Core;

namespace CustomIoCMvc.Models
{
public class CustomerRepository : ICustomerRepository
{
[Inject]
public CustomerRepository(ILogger logger)
{
this.Logger = logger;
}

public Customer Find(int id)
{
Logger.Log("Find called with param value " + id.ToString());
return FindAll().Where(c => c.Id == id).FirstOrDefault();
}

public List<Customer> FindAll()
{
Logger.Log("FindAll called.");
var data = new List<Customer>();
data.Add(new Customer() { Id = 1, Name = "Joe" });
data.Add(new Customer() { Id = 2, Name = "Steve" });
data.Add(new Customer() { Id = 3, Name = "Karen" });
return data;
}

public ILogger Logger { get; set; }
}
}

And here’s our CustomerRepository with Property injection:


using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using Core;

namespace CustomIoCMvc.Models
{
public class CustomerRepository : ICustomerRepository
{

public Customer Find(int id)
{
Logger.Log("Find called with param value " + id.ToString());
return FindAll().Where(c => c.Id == id).FirstOrDefault();
}

public List<Customer> FindAll()
{
Logger.Log("FindAll called.");
var data = new List<Customer>();
data.Add(new Customer() { Id = 1, Name = "Joe" });
data.Add(new Customer() { Id = 2, Name = "Steve" });
data.Add(new Customer() { Id = 3, Name = "Karen" });
return data;
}

[Inject]
public ILogger Logger { get; set; }
}
}


Both have been tested with the same result. But first, a little background about what’s going on here.



Our CustomersController is requesting from the service locator an instance of ICustomerRepository. It finds that we’ve bound ICustomerRepository to CustomerRepository, and goes to instantiate that class. What we’ve modified our code to do is to look, before we instantiate, if there’s a constructor with an [Inject] attribute. If there is, we fill in the constructor parameters with the needed types. If not, we go ahead and create the object with the default constructor.



Next, after we’ve instantiated the object, it looks for any properties with an [Inject] attribute, and does the same. Finally, it returns the object.



Therefore, in this case, our DependencyInjector is getting a request for a new CustomerRepository, it looks for a constructor with [Inject], sees one (in the first example) and resolves ILogger to the bound WebLogger type, gets an instance of WebLogger, and fills it in to the constructor. In the second example, it uses a default constructor but finds the [Inject] decorated Logger property, resolves ILogger to WebLogger, and sets it.



So here’s our output. You can’t really see it (because it’s a cheap quick hack), but theres a “FindAll called.” string at the top of the page:



image



Let me know in the comments if you have any issues or constructive criticism of this code. Hope this helps!

Wednesday, September 23, 2009

Creating Your Own IoC Container

A few posts ago I covered how to take your first steps into Dependency Injection with Ninject. Continuing on the DI/IoC theme, let’s now look at how you can create your own Inversion of Control (IoC) container.

Suppose that your organization has very strict limits on what outside software you can use due to licensing, but you still want to do IoC. Or, perhaps you don’t need your IoC container to do very much other than the basics and you don’t want the weight of another full-featured DLL. This is what we will be creating today, with 2 classes: a ServiceResolver and a ServiceLocator.

(Aside: For those that feel I’m using the term “Service Locator” inappropriately, please forgive me. For this example that’s the name I came up with.)

A basic IoC container needs to do the following:

  • Register abstract types or interfaces to concrete implementation types
  • Resolve abstract types or interfaces to implementation objects
  • Keep track of the registered types
  • Keep already-resolved objects available for re-use
  • Create instances of the implementation types behind-the-scenes

Our two classes will accomplish that, but only one has most of the logic – the ServiceResolver. The reason for the ServiceLocator class is to provide static methods around the ServiceResolver, and maintain a static instance of the resolver. Since static methods are difficult to test, this allows you to test the functionality of the ServiceResolver class, and trust that the basic wrapper functionality of the ServiceLocator just works.

The Light At The End

Sometimes it’s fun to see what we’re aiming to do, instead of starting from the beginning, right? Basically we’re going to have a simple ASP.NET MVC site that is going to have a Customers controller. The Index action will ask the service locator for an implementation of ICustomerRepository so that it is loosely coupled. In our Global.asax class, we will register the binding of ICustomerRepository to CustomerRepository. The reason for this is we are pretending that CustomerRepository hits the database, so that for our unit tests we could create a mock repository that does not.

Our Global.asax.cs file looks like this:





  1. protected void Application_Start()
  2. {
  3. RegisterRoutes(RouteTable.Routes);
  4. // register types
  5. ServiceLocator.Register<ICustomerRepository, CustomerRepository>();

  6. }




Note that in a real-world app, you may wish to register types on each page request, not on application start.

And our Index action looks like this:





  1. public ActionResult Index()
  2. {

  3. var repo = ServiceLocator.Resolve<ICustomerRepository>();

  4. ViewData["customers"] = repo.FindAll();

  5. return View();

  6. }




The ServiceResolver Class

Let’s look at the ServiceResolver class that does all the heavy lifting (although there really isn’t much).





  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace Core
  6. {
  7. /// <summary>
  8. /// Resolves abstract types or interfaces to concrete implementations. Use <see cref="ServiceLocator" /> for static/shared access.
  9. /// </summary>
  10. public class ServiceResolver
  11. {
  12. private Dictionary<Type, object> _store;
  13. private Dictionary<Type, Type> _bindings;

  14. /// <summary>
  15. /// Default constructor; instantiates a new ServiceResolver object.
  16. /// </summary>
  17. public ServiceResolver()
  18. {
  19. _store = new Dictionary<Type, object>();
  20. _bindings = new Dictionary<Type, Type>();
  21. }

  22. /// <summary>
  23. /// Gets an implementation object of a registered abstract type or interface.
  24. /// </summary>
  25. /// <typeparam name="T">The registered abstract type or interface to look up.</typeparam>
  26. /// <returns>Returns an object of the given type.</returns>
  27. public T Resolve<T>()
  28. {
  29. // check for registration
  30. if (!_bindings.ContainsKey(typeof(T)))
  31. throw new InvalidOperationException(string.Format("Requested type {0} has not been registered.", typeof(T).ToString()));

  32. // get destination type
  33. Type dest = _bindings[typeof(T)];

  34. // check for already requested object
  35. if (_store.ContainsKey(dest))
  36. return (T)_store[dest];

  37. // create a new instance of this type
  38. T obj = (T)Activator.CreateInstance(dest);

  39. // add to store for future use
  40. _store.Add(dest, obj);

  41. return obj;
  42. }

  43. /// <summary>
  44. /// Registers a type with its corresponding implementation type.
  45. /// </summary>
  46. /// <typeparam name="TFrom">The abstract type or interface to use as a key.</typeparam>
  47. /// <typeparam name="TTo">The implementation type to use as a value.</typeparam>
  48. public void Register<TFrom, TTo>()
  49. {
  50. _bindings.Add(typeof(TFrom), typeof(TTo));
  51. }

  52. }
  53. }




First, notice the _store and _bindings members. Those are our ways of keeping track of registered types (_bindings) and reusable already-resolved objects (_store).

The Register<TFrom, TTo>() method adds to the _bindings dictionary the “from” and “to” types to use later, whenever Resolve<T>() is called. Since we’re just storing types in the dictionary, there is little overhead and it’s okay to register all our types in advance.

Finally, the Resolve<T>() method looks for a pre-registered type binding, and throws an error if it doesn’t find one. Then, it looks to see if an object has already been created for this type. If so, it returns it. If not, it creates an instance of the type and adds it to the _store dictionary before returning it.

You can certainly use the ServiceResolver class by itself for IoC, but I prefer using static methods for conciseness. That’s why we need a static wrapper class, called ServiceLocator.

The ServiceLocator Class

Here’s our ServiceLocator static wrapper class.





  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace Core
  6. {
  7. /// <summary>
  8. /// A service locator to resolve abstract types or interfaces to concrete implementations.
  9. /// </summary>
  10. public class ServiceLocator
  11. {

  12. private static ServiceResolver _instance = null;
  13. private static object _lock = new object();

  14. /// <summary>
  15. /// Gets a shared instance of the ServiceResolver.
  16. /// </summary>
  17. /// <returns>Returns the shared instance of a ServiceResolver, or a new one if it has not yet been accessed.</returns>
  18. private static ServiceResolver GetInstance()
  19. {
  20. lock (_lock)
  21. {
  22. if (_instance == null)
  23. _instance = new ServiceResolver();

  24. return _instance;
  25. }
  26. }

  27. /// <summary>
  28. /// Binds an abstract type to a concrete implementation.
  29. /// </summary>
  30. /// <typeparam name="TFrom">The abstract type or interface to use as a key.</typeparam>
  31. /// <typeparam name="TTo">The implementation type to use as a value.</typeparam>
  32. public static void Register<TFrom, TTo>()
  33. {
  34. GetInstance().Register<TFrom, TTo>();
  35. }

  36. /// <summary>
  37. /// Gets an implementation of the given type.
  38. /// </summary>
  39. /// <typeparam name="T">The abstract type or interface to look up.</typeparam>
  40. /// <returns>Returns an implementation of the given type.</returns>
  41. public static T Resolve<T>()
  42. {
  43. return GetInstance().Resolve<T>();
  44. }

  45. }
  46. }





Notice that we’ve got one static instance of the service resolver, and a GetInstance() method that instantiates it if it doesn’t exist. Also notice our Resolve and Register methods that have the same signature (albeit static) as our ServiceResolver class.

This enables us to simply call ServiceLocator.Resolve<T>() without needing to find an instantiated resolver or create one.

Just to show you that this was tested, here’s our view:





  1. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

  2. <h2>Customers</h2>
  3. <ul>
  4. <% foreach (Customer c in (List<Customer>)ViewData["customers"])
  5. { %>
  6. <li><%= c.Name %></li>
  7. <% } %>
  8. </ul>
  9. </asp:Content>




Here’s our CustomerRepository:





  1. namespace CustomIoCMvc.Models
  2. {
  3. public class CustomerRepository : ICustomerRepository
  4. {

  5. public Customer Find(int id)
  6. {
  7. return FindAll().Where(c => c.Id == id).FirstOrDefault();
  8. }

  9. public List<Customer> FindAll()
  10. {
  11. var data = new List<Customer>();
  12. data.Add(new Customer() { Id = 1, Name = "Joe" });
  13. data.Add(new Customer() { Id = 2, Name = "Steve" });
  14. data.Add(new Customer() { Id = 3, Name = "Karen" });
  15. return data;
  16. }

  17. }
  18. }




And here’s the output:

image

Hope this helps! Please leave constructive comments below. Also note that I'm still playing around with formatting code, please forgive me if it doesn't render correctly!

Tuesday, September 22, 2009

Pair Programming in the News

20pre600.1I’ve been a huge fan of pair programming for a while now. It really is more productive, and it effectively is a real-time code review as you write it. I’ve had the chance to do some pair programming here at the new gig, and it’s worked out really well. A new favorite quote of mine when paraphrased goes something like “You don’t learn from people that agree with you” and with pair programming that is definitely the case. You learn from the mistakes you make when your partner disagrees with what you just wrote.

So I was very excited to find an article about pair programming in the New York Times. Check it out and let me know in the comments what your thoughts are.

I’ve got a few new discoveries with ASP.NET MVC and Dependency Injection that I’m gearing up some posts about, and as you may have noticed, I’m still trying to figure out the best way to get code into this blog as a formatted, copy-and-paste-able format.

I’m looking forward to the next meetings (and my first) of JaxDUG (Jacksonville .NET User Group), ArcSIG (for Architects), and the Jacksonvile SQL Server Users Group. I’m a big fan of community, and if you’ve never been to a local .NET user group, I strongly encourage you to give it a try.

Update: It appears that at least one person is asserting a more pessimistic view of this article. I really am not a proponent of that kind of negative, borderline arrogant language, as I try to make this blog positive and forward-thinking for beginners as well as experts -- but it's an interesting read nonetheless.

Wednesday, August 19, 2009

ASP.NET: WebForms Validation with Data Annotations

Last night at my last regular trip to the Lakeland .NET User Group I had a discussion with someone about how it’s great that Data Annotations is being used by Dynamic Data, RIA services, and now ASP.NET MVC 2, but that there isn’t a WebForms validation control (like the PropertyProxyValidator in the Validation block of Enterprise Library) to auto-validate against Data Annotations. I suggested we write one. I did so this morning.

If you aren’t familiar with Data Annotations, it’s a really cool feature of .NET 3.5 SP1. Check out those 3 links above (Dynamic Data, RIA, and MVC) for more info of how they’re used elsewhere.

The DataAnnotationValidator Class

Here’s the code for the Data Annotations Validator that I built for WebForms. I just created this as a class file in the App_Code folder of my web project for testing, but you’d probably want to move it into your shared library (if you have one). You’ll need to add a reference to System.ComponentModel.DataAnnotations first.

image

And there’s just 2 properties in this class:

image

Data Annotating Your Class

Here’s a test class I wrote using some common annotations:

image

Here you see you can add multiple validators together (such as Required and StringLength in this example). And there’s also a RegularExpression validator:

image

Usage

To use this DataAnnotationValidator on your page, you must first register the namespace. (Note: you can also do this in the web.config to force it on all pages in your site.)

image

The namespace value must match the namespace of DataAnnotationValidator.

To add a validator to a form field, just create a new <val:DataAnnotationValidator> tag for each field:

image

Notice the SourceType property? That value must match the full type name of the object you’re validating.

Now when you try and submit your form you get this:

image

(In this example, the Address 2 field is not marked as required.)

You can also simply add a ValidationSummary to the page to show what is wrong:

image

And now we get a helpful list of errors:

image

You’re probably thinking, though, “what’s so special about this? I could just use a RequiredFieldValidator.” True, but we now have multiple validators per property with just one validator tag, and we don’t have to make the front end logic match the back end annotations. Separation of concerns!

Here’s the RegularExpression data annotations validator at work:

image

You can see where this becomes handy – you annotate your class once, and you can then use it in RIA services, ASP.NET MVC 2, and now WebForms, and you don’t have to have any validation logic in your front end code. This idea could easily be modified for Windows Forms or WPF as well. You could also easily modify the code to set a CSS style for the textbox that would change the background color on error.

Hope this helps! Let me know any questions or concerns in the comments.

Also, I couldn’t have done this without some guidance from the Enterprise Library PropertyProxyValidator source code, and this Stack Overflow question/answer.

Update: Using DisplayName

I realized that I was forgetting a key part of data annotations – that it supports the DisplayNameAttribute! This removes all of the string error messages from the class definition and generates them for you. Below are the modifications to support DisplayName. If a display name is not given, it will use the property name instead, which is great for single word property names like “City”.

In your class file that you’re annotating, import System.ComponentModel.

image

In the DataAnnotationValidator class, modify the routine to look up the DisplayName or property name like this:

image

Also make sure you modify the Me.ErrorMessage line to use attr.FormatErrorMessage(displayName) like above.

Now, you can yank out all of those error message strings! If you’ve got a single word property name, like Id, you can just do this:

image

And if you need to add a display name, you can add the DisplayName() attribute:

image

Once we’ve made these modifications (which make the class definition much more concise), we get the following output on our form, without having to write our own error messages:

image

You’ll still want to keep the error message specified for the RegularExpression annotation validator, because it actually shows the RegEx expression in the error message, which will confuse your users.

Monday, August 17, 2009

First Steps into Dependency Injection with Ninject

I recently started playing around with dependency injection, but it was very much a by-hand process using constructor injection without any kind of framework. It worked well for my proof of concepts, but I had a breakthrough today when I tried Ninject. If you’re looking to get into DI/IoC, this hopefully will be a good place to start. I’m right there with you, I’m a newbie to DI as well.

If you’re already confused by the first paragraph, Dependency Injection (hereafter called DI) and Inversion of Control (hereafter called IoC) are almost synonyms for a development methodology where you aim to reduce coupling between classes as much as possible. Coupling means that one class depends on another, which increases complexity for large projects and almost ruins testability. For example, if your class needs to use a database connection, you might not want to couple it with SqlClient.SqlConnection, you might just want to couple it to the interface IDbConnection instead, so that it can accept any type of connection. (SqlConnection implements IDbConnection.) This makes your code more flexible for testing, because you can create a mock connection that implements IDbConnection and perform unit tests without hitting your database. This is just one example, although there are many reasons to use DI.

While there are other methods of injection, I’m only going to talk about 2 in this post – constructor injection and property injection.

In this example, let’s say you have a Customer class that needs to use a database connection. Since you want to roll your own database connection wrapper classes, you also want to implement logging so you can keep track of your database requests.

Let’s start out with a console application.

Disclaimer: This is demo code only. It doesn’t actually connect to a database, and does not implement best practices for security or anything else. Please keep that in mind!

Downloading Ninject

You can download Ninject and take a short tutorial at www.ninject.org.  The download is a .zip file with all of the Ninject DLLs that you’ll ever need, but really we’re just concerned with the Ninject.Core assembly.

Add Ninject as a Reference

Create a new console application, and from the My Project pages, add the extracted Ninject.Core.dll file as a reference.

image

It’ll also make it easier later on to go ahead and import the Ninject.Core namespace from the References property page:

image

The Old Way

First, let’s look at how we might previously have implemented the Customer class without DI.

image

Here you can see that we’ve got a private SqlConnection object that is created in the constructor. There’s no way here to swap that out for a mock connection for testing, and we’ve got a coupling between Customer and SqlConnection.

Now let’s look at how SqlConnection does its logging (note that this class is obviously just for demo purposes):

image

As you might have guessed, our SqlConnection object now has a tight coupling with ConsoleLogger. What if we wanted to log to a database or email instead? With this method, we can’t.

Dependency Injection By Hand

As I mentioned earlier, I started out by doing DI by hand, so let’s see what that might look like.

First let’s make an interface for our database connection:

image

Now, here’s what our SqlConnection class looks like:

image

We still have a dependency on ConsoleLogger, but we’ll remove that later.

Now our customer class no longer has a dependency on SqlConnection:

image

And here’s how we use it in our console app:

image

And the result is (with our ConsoleLogger output):

image

We still have to inject the SqlConnection by hand, which would work in front end code, but is not ideal.

So, proceeding onto removing the dependency on ConsoleLogger, how would we accomplish this with the method above? Well, we’d probably have to pass in a new ConsoleLogger (implementing ILogger) into our customer object as well. However, then we’d have to pass that logger from the customer into the SqlConnection by a constructor or property. And what if we have to create multiple objects that use the same connection or logger? It becomes a mess very quickly. This is where Ninject steps in to help.

Let’s wrap up a few more things, such as creating an interface for our loggers:

image

Then we’d make ConsoleLogger implement ILogger.

image

Setting Up our Injections

How Ninject and other DI solutions work is by automatically wiring up our dependencies for us. For example, we need to wire up 2 dependencies: anytime we want an IDataConnection in this app we want to use a SqlConnection, and anytime we want an ILogger we want a ConsoleLogger. This makes the code testable because you can wire up in your tests to use a mock IDataConnection instead, with another type of logger if you wish.

We’re going to use those two methods of injection as mentioned here before. First, constructor injection. We want to use the constructor of the Customer object to inject a dependency on SqlConnection. Here’s how we mark that constructor for injection:

image

Next, we want to use property injection to inject a dependency of ConsoleLogger into the SqlConnection.

image

Note that we’re accomplishing the same goal, but using a Property instead of a Constructor.

Tying It All Together

Ninject uses the idea of a “kernel” to generate all the dependencies. And the kernel can have passed into it multiple “modules” to wire them all together. First we’ll create the DataModule, although you can call it whatever you like:

image

Note that it must inherit from StandardModule for this to work.

Those 2 lines of code inside the Load method are pretty powerful. They’re saying, using generics, that anytime a class requests an IDataConnection, we want a SqlConnection, and anytime a class requests an ILogger, we get a ConsoleLogger. This is dependency injection at work!

So now that we have our loosely coupled classes (because no class depends on another) and our module for wiring up our connection and logger, we need to actually use the kernel.

image

image

Hooray for DI! Now, our front end code doesn’t need to know that it’s using a SqlConnection or ConsoleLogger, it’s happening for us behind the scenes. We could even make the SqlConnection or ConsoleLogger a singleton so that there’s only one instance of it in our application, just by adding the <Singleton()> attribute to the class.

I hope this shows off the basics of using Ninject in an application. Beyond this, I’m not an expert. I only recently got involved in DI, and only today with Ninject. But I’m really impressed so far, and I think once you play around with it you will be too.

Please do not hesitate to (kindly) let me know your questions or concerns in the comments.