Sponsors

Thứ Bảy, 30 tháng 3, 2013

Dependency Resolution in ASP.NET MVC3/4 with Ninject

The topic for this post is setting up the Ninject Inversion of Control (IoC) container in your ASP.NET MVC3/4 applications. I'm assuming the reader has familiarity with the following concepts:

  • Programming to an interface (or contract)
  • The IoC programming technique
  • Dependency injection
  • IoC containers

The intention is for this post to serve as a useful reference for ASP.NET MVC developers who want to get an IoC container (specifically Ninject) up and running swiftly with the MVC framework.

When working on a new MVC project, one of my first steps usually involves setting up an IoC container. I've typically used Ninject as my IoC container due to its ease of setup and intuitive fluent API. As of ASP.NET MVC3, there is the option of using the Ninject extension for MVC3 (wrapped up in a NuGet package called Ninject.MVC3). This option is simple to setup and you'll typically have little reason to use another approach. Another option is to write your own implementation of the IDependencyResolver interface. In this scenario, you'll implement this interface (which again is quite simple with Ninject) and then hook your custom resolver into the framework for it to use. In a nutshell, the MVC framework will use your custom IDependencyResolver implementation as a first port of call to resolve any required dependencies.

In this post, we'll go with the former option.

Using the Ninject.MVC3 NuGet Package

As mentioned, the Ninject.MVC3 NuGet package is an easy way to get Ninject up and running in your project. The first step is to get the package installed in your solution. I'm using Visual Studio 2012 so the steps may differ slightly depending on what version of the IDE you're running on. Right click your MVC solution node in Solution Explorer. Select the "Manage NuGet Packages for Solution" option in the context menu.



This will bring up the NuGet package manager dialog. In the top right, you should see a text box with the watermark "Search Online". Type "Ninject" and hit enter. In the middle pane, you'll see the Ninject.MV3 package, select it and click the Install button.



At this point, the NuGet package manager will have done all of the hard work. If you expand the App_Start folder in your solution, you'll find a new file called NinjectWebCommon.cs.



This file contains a static class definition and a number of static methods. The methods that you're interested in are the CreateKernal and the RegisterServices methods. If you have had experience with Ninject in the past, then you'll be at home with what the CreateKernal method is doing. It creates an instance of the StandardKernal (the default implementation of Ninjects IKernal interface). The StandardKernel is the class you'll use to map (or in Ninject terminology "bind") interfaces to the implementations that you want to use. This is done by using the generic methods Bind and To on the kernel object, where you pass your interface and implementation, respectively, as type parameters. You'll notice that the CreateKernal method makes a call to a method named RegisterServices. This is the method where you'll register your bindings with Ninject.


private static void RegisterServices(IKernel kernel)
{
// Register your ninject bindings here!
}
Now that Ninject is setup in the project, we'll try and inject a dependency through a controller constructor. In this example, imagine you have a simple logging interface, defined as:


public interface ILogService
{
void Log(string message);
}
We then have an implementation of this interface:


public class DebugLogService : ILogService
{
public void Log(string message)
{
System.Diagnostics.Debug.WriteLine(message);
}
}
Imagine further that we now wanted various actions in our HomeController to log to the debug output. With dependency injection, one way to inject our DebugLogService implementation into our HomeController would be through the constructor - as follows:


public class HomeController : Controller
{
private readonly ILogService _logService;

public HomeController(ILogService logService)
{
_logService = logService;
}

public ActionResult Index()
{
_logService.Log(
string.Format("Index() called at {0}",
DateTime.Now));

return View();
}
}
If you're following the steps and you now run your web application, you'll get a runtime exception stating that there was an error activating ILogService. This is good, as it tells you that Ninject tried to create an instance of the HomeController, but failed in doing so because the HomeController has no default constructor. The constructor that it does have, however, has one required parameter (logService) that Ninject has no type bindings for. We'll now go back to the static RegisterServices method in the NinjectWebCommon class and add the binding as shown below:


private static void RegisterServices(IKernel kernel)<br />{<br /> kernel.Bind<ILogService>().To<DebugLogService>();<br />}
If you now run the application, you'll find that the HomeController is successfully being instantiated with Ninject passing an instance of the DebugLogService class through to the constructor. You can verify this by looking at the output window for the log entry.



And that's it - you'll now follow this pattern for registering your bindings in the RegisterServices method and programming to your interfaces for which you have registered bindings. As all of your bindings are registered in a single location, swapping out your implementations with other implementations is an easy job. We can now easily switch all logging to a file by writing a new FileLogService (that implements ILogService) and then bind this to the ILogService in the RegisterServices method.

Chủ Nhật, 17 tháng 3, 2013

Binding to PasswordBox in WPF (using MVVM)

I'm currently working on a Windows Presentation Foundation (WPF) client application that adheres to the Model View ViewModel (MVVM) design pattern. Having had a lot of experience with .NET WinForms, the WPF learning curve wasn't so steep. The main areas I initially concentrated on were getting to grips with XAML, then concepts such as data binding, commands, dependency properties and attached properties. It's the last of these that helped in resolving the problem I had with the PasswordBox control and view model binding.

In WPF, data binding enables you to hook a specific property in your data context (in my case, the view model) to a property on a user interface control. For example, the following XAML markup shows how the Text property on a TextBox can be bound to the FirstName property on the view model:
<TextBox Height="23" 
         Width="120" 
         Text="{Binding Path=FirstName, Mode=TwoWay}" />
As the Mode is set to TwoWay, any text changes by the user will result in the FirstName property being updated in the view model, likewise, any programmatic change to the FirstName view model property will result in the user interface being updated (provided that your view model implements the INotifyPropertyChanged interface and the setter of the FirstName property raises the OnPropertyChanged event). In my case, I had a PasswordBox control in my XAML markup that needed binding to a view model string property named Password. Initially I tried this in XAML:
<PasswordBox Name="userPasswordBox"
             Height="23" 
             Width="120"  
             Password="{Binding Path=Password, Mode=OneWay}" />
However, the Visual Studio XAML designer immediately underlined the 'Password="{Binding...' line and stated the error:
A 'Binding' cannot be set on the 'Password' property of type 'PasswordBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
As the binding error message alludes to, it turns out that the Password property on the PasswordBox control is a standard .NET CLR property and this was a deliberate security-based design decision by Microsoft to prevent plain text passwords from sitting around in memory. In my case however, having the password sit in memory wasn't an issue.

Of course, if the application I was working on wasn't using MVVM, then I could easily have picked up the user entered password in the code-behind in a button click event handler (e.g. this.userPasswordBox.Password would return the plain password). But because the application was adhering to MVVM, the code-behind was pretty much empty (except for the usual constructor boilerplate code). Instead, all of the UI "events" were being handled by the view model via command objects exposed as public properties. This therefore made retrieving the password from the PasswordBox and assigning it to the view model Password property an annoyingly interesting problem!

After doing a bit of research on the web, I found a couple of solutions.

  • Pass the PasswordBox control to the view model: In this solution, the PasswordBox control itself is passed back to the view model via a command parameter (which is hooked up to the "OK" button). The method that handles the command then gets the PasswordBox instance via an object type parameter which can be cast back into a PasswordBox. You can then retrieve the password easily through the PasswordBox.Password property.
  • Use attached properties to enable binding: In this solution, attached properties (a special type of dependency property) are created, enabling you to use them on the PasswordBox control and bind to your view model property.

The first solution above works but I wasn't too happy with passing a UI component to my view model - it violates the MVVM design pattern principle of decoupling the view from the view model. I went for the second option as it enabled binding to the PasswordBox.Password property (albeit indirectly) and didn't violate the use of MVVM in the process.

To get this working, take a look at the static PasswordBoxAssistant class on Samuel Jack's interesting blog. The class defines the attached properties that you can then use in your XAML markup, in my case, it resulted in the following markup:
<PasswordBox Name="userPasswordBox"
             Height="23" 
             Width="120"  
             ap:PasswordBoxAssistant.BindPassword="true"
             ap:PasswordBoxAssistant.BoundPassword=
                "{Binding Path=Password, 
                  Mode=TwoWay, 
                  UpdateSourceTrigger=PropertyChanged}"
 
/>
As shown in the markup above, you'll need to import the namespace that the PasswordBoxAssistant class is defined in and add an alias to it (in my case "ap"). Having done that, it's finally just a case of using the attached properties to wire up the binding to your view model property.

Thứ Sáu, 1 tháng 3, 2013

The Generic Lazy Type

Lazy<T> is a monad type that was introduced in .NET 4 and provides an alternative mechanism for implementing lazy initialisation. Lazy initialisation is where you intentionally delay the creation of an object that is expensive to create.

You would typically want to use lazy initialisation in scenarios where the object (which is expensive to create) may or may not be used in the execution flow of your program. In this case, it makes sense to only initialise the object if it is required. One reliable place where you may have seen the lazy initialisation tactic being used is in an implementation of a singleton class - which will have a method or property that returns the singleton instance, for example:


public MySingletonClass GetInstance()
{
if (_singleton == null)
_singleton = new MySingletonClass();

return _singleton;
}
The logic before the return statement is an example of lazy initialisation, where the singleton is only instantiated the first time GetInstance is called and never before it. Subsequent calls to GetInstance will then also return the same instance, hence we have an implementation of the singleton design pattern. In this particular case, we don't know if MySingletonClass is expensive to create, and we don't particularly care as we're using lazy initialisation to prevent multiple instances of MySingletonClass from being created.

If we now go back to the mainstream use for lazy initialisation, where we want to delay instantiation of expensive-to-create objects, you could adopt the pattern above where you conditionally instantiate an instance of an object. However, since .NET 4, you have an alternative option with the use of Lazy<T>. An instance of Lazy<T> wraps around your expensive-to-create object, you pass this instance around in your code and when ever the underlying expensive-to-create object is required, you can call the Value property on Lazy<T> which will instantiate the object and return it to you.

The following contrived example should make it more clear. Imagine you have a Customer class and an Order class. A single customer can have many orders, so we'll make use of composition and have the Customer class support a List of Order objects. The Customer class has one constructor that accepts a customer ID. Using the supplied ID, the constructor then goes and retrieves the orders for the customer from an order repository. Note that in reality your entity classes will usually be dumb and just support getter and setter properties and it'll be the responsibility of your data access layer/framework (like Entity Framework) to instantiate and populate your entities appropriately. Continuing with our contrived example, our initial attempt may therefore look like:


public class Order { }

public class Customer
{
public int Id { get; private set; }
public string Name { get; set; }
public List<Order> Orders { get; set; }

public Customer(int id)
{
Id = id;
Name = "Ms Foo Bar";

// Simulate getting lots of orders from an
// order repository
Orders = Enumerable<br /> .Repeat<Order>(new Order(), 200)<br /> .ToList();
}

public override string ToString()
{
return string.Format(
"I'm customer with id {0}", Id);
}
}
As the code indicates, it would be expensive to instantiate a Customer object if we didn't require the order information contained within it. This is where you would apply the concept of lazy initialisation. In this case, we'll make use of the Lazy<T> type. The following code shows how the Customer class would look if we lazily instantiate the Orders list using Lazy<T>.


public class Customer
{
public int Id { get; private set; }
public string Name { get; set; }
public Lazy<List<Order>> Orders { get; set; }

public Customer(int id)
{
Id = id;
Name = "Ms Foo Bar";

Orders = new Lazy<List<Order>>(() => {
// Simulate getting lots of orders from an
// order repository
return Enumerable<br /> .Repeat<Order>(new Order(), 200)<br /> .ToList();
}
);

Debug.WriteLine(this);
}

public override string ToString()
{
return string.Format(
"I'm customer with id {0}", Id);
}
}
As you can see, the constructor of the Customer class instantiates an instance of Lazy<T> that wraps around the List of Order objects. The constructor of Lazy<T> is passed a lambda expression that expresses what needs to be returned when the list of orders is requested for (our expensive logic). Notice I've also put a call to Debug.WriteLine so you can observe the output of the following code and see how this behaves.


var customer = new Customer(1);

Debug.WriteLine("Are orders instantiated? {0}",
customer.Orders.IsValueCreated);

// Ok, we now want the orders...
var ordersForCustomer = customer.Orders.Value;

Debug.WriteLine("Are orders instantiated? {0}",
customer.Orders.IsValueCreated);

Debug.WriteLine("Customer {0} has {1} order(s)",
customer.Id, ordersForCustomer.Count);
If you execute the code above using the updated Customer class, you'll find that instantiating a Customer object is no longer an expensive operation. The output you should see in your debug window is:


I'm customer with id 1
Are orders instantiated? False
Are orders instantiated? True
Customer 1 has 200 order(s)
Notice that when the Customer object was initialised, the runtime executed the constructor logic as expected (verifiable with the ToString output). We then check our Lazy objects IsValueCreated property to ensure it hasn't yet created an instance of the list and populated it. The property returned False as expected. On the next line, we explicitly call the Value property on the Orders property (our Lazy object) - this forces our lazy object to instantiate. We re-query the IsValueCreated property which now returns True and finally we output the order count to show that the orders have been successfully lazily-loaded.

Thứ Tư, 27 tháng 2, 2013

Quick Yammer & CRM Demo

Most, if not all of you, know that Microsoft has acquired Yammer in June 2012. Now Microsoft has released the integration between Yammer and Dynamics CRM as part of the Polaris release (formerly known as December 2012 Service Update). However, in order to demo this, you’ll need to sign up for a Yammer Enterprise account*. If you don't have such an account, then the integration will not work as

Thứ Bảy, 23 tháng 2, 2013

ASP.NET MVC Consolidating "Usings" in Views/Web.config

Something I came across yesterday that you may find useful as an ASP.NET MVC developer. If you find yourself having to include the same set of "usings" across many of your razor views, then you can consolidate them and put them in the Web.config that sits under the Views folder.

The specific config element you're interested in is system.web.webPages.razor/pages/namespaces. It's a case of just creating an entry for each of your commonly used namespaces and then you don't need to worry about adding @using's or fully qualified class names in your views to resolve commonly used types.


...
<br /><pages pageBaseType="System.Web.Mvc.WebViewPage"><br /> <namespaces><br /> <add namespace="System.Web.Mvc" /><br /> <add namespace="System.Web.Mvc.Ajax" /><br /> <add namespace="System.Web.Mvc.Html" /><br /> <add namespace="System.Web.Optimization"/><br /> <add namespace="System.Web.Routing" /><br /> <add namespace="MyMvcApp.Models.ViewModels" /><br /> </namespaces><br /></pages><br />
...
If you're using the WebForms (ASPX) view engine then the equivalent place to add your global usings is in the same Web.config but within the system.web/pages/namespaces element.

Thứ Tư, 20 tháng 2, 2013

It's been a while

At the moment I'm at the MVP Summit spending time with a bunch of great minds in the industry. One of the guys made me realize that it's been a while since my last post and asked if I could pick up posting blogs again. As my role has changed over time, I'm not spending too much time on coding anymore. There are a bunch of guys out there which are way more technical than I am, so I'm handing over

Applying the Chain of Responsibility Design Pattern

Earlier this week I made use of the Chain of Responsibility design pattern to solve a fairly straight-forward problem. I've always been careful when trying to apply design patterns, it's easy to get carried away and try to force a design pattern to a problem that doesn't really require it. In this case, I felt it was justified and hopefully you'll think the same!

The Context

I'll give some context to the problem before we go into exactly what the Chain of Responsibility pattern is. I was working on a HTTP service (built on ASP.NET Web API) which had an API controller action that accepted requests for some data stored in a persistent repository. My requirement was to inspect the incoming request object, and depending on certain characteristics of the request, log the request object data to zero or many different output locations. This is to enable reporting on the types of requests that the service receives. The output locations were disparate data stores such as an XML file, Excel file and SQL Server Database. The key point was that to log the request I had to inspect the content of the request, and depending on some criteria, log it to none or certain data stores. Furthermore, certain requests had to be ignored and therefore not logged.

Chain of Responsibility

When I read this requirement I knew immediately there was a design pattern for this type of problem. I had taken an Object-Oriented design pattern course at university around six years ago but couldn't quite remember the name of the pattern. After having a quick look on the GoF website, I eventually found it - Chain of Responsibility (CoR). CoR is a software design pattern that has been classified into the "behavioral" category of patterns - these are patterns that broadly deal with objects interacting with other objects. The idea is that you have multiple handler objects chained together just like a linked list data structure. An incoming request object is passed over to the first handler in the chain, the handler (depending on its "responsibility"), inspects the request and can either:
  1. Handle the request and not pass the request down the chain of handlers
  2. Handle the request but still pass the request down the chain of handlers
  3. Not handle the request and pass the request down the chain to the next handler
Note that before a handler sends the request object down the chain, it is also responsible for checking if it is actually linked to another handler. If a handler isn't linked to another handler, it is the last handler in the chain and therefore consumes the request.

Applying CoR to the Problem

In my case, the incoming data request to the API was my CoR request that required "handling" from a logging perspective. I implemented a separate concrete logging handler class for each of the concrete data stores (XML, Excel and SQL Server). Each logging handler inspected the request and logged the request if it matched the criteria for the handler before passing the request to the next handler. Therefore, in my case, the CoR handler behaviour corresponded to point two above.

The Implementation

Note that I've stripped down the code below (especially for each concrete handler) so that it is easier to see what's going on from a design pattern perspective.

The first step was to write an abstract base handler that defined the behaviour that each of my handlers will support. The HandlerBase class below is generic enough to be reused in any case where you require a CoR implemented. The single type parameter "TRequest" is the type of the object that will go through your chain (can be any .NET type).
public abstract class HandlerBase<TRequest>
{
    public HandlerBase<TRequest> Successor
    { 
        protected get; 
        set; 
    }

    public abstract void HandleRequest(TRequest request);
}
The HandlerBase class has one property, which allows users of a handler to set a successor to this handler (the next handler in the chain) and it has an abstract method that all derived classes will need to implement - HandleRequest. You will see further below how we use the Successor property when setting up our chain, and how each concrete handler (a class that derives from HandlerBase) uses the HandleRequest method on its successor to pass the request down the chain.

Next, I implemented each of my concrete handlers - that is, a handler for logging to an XML document, Excel document and SQL server.
public class LogRequestToXmlHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to xml document

        // Pass on the request to the next handler, if any
        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}
Notice how the concrete handler LogRequestToXmlHandler derives from HandlerBase and passes the type of the object that is going through the chain - ApiDataRequest. Also notice that because we're inheriting from an abstract base class containing one abstract method - we're forced by the compiler to override the HandleRequest method. This method accepts one parameter, the request object. It is in this method that you will place any specific handling logic for the request object - I've added some pseudo-code to demonstrate this. The last couple of lines inspect the Successor property (inherited from the base class), if it isn't null - then we call the HandleRequest on it, thus passing our request down the chain. If Successor returns null, then the current handler is the last in the chain and we do nothing - effectively consuming the request. For completeness, the other handlers are below.
public class LogRequestToExcelHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to excel document

        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}

public class LogRequestToDbHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to database

        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}
Now that we have our handlers, the final step is to setup our chain so that it's ready to handle requests. The code below shows how the handlers are chained together.
HandlerBase<ApiDataRequest> logToXmlHandler
    = new LogRequestToXmlHandler();

HandlerBase<ApiDataRequest> logToExcelHandler
    = new LogRequestToExcelHandler();

HandlerBase<ApiDataRequest> logToDbHandler
    = new LogRequestToDbHandler();

logToXmlHandler.Successor = logToExcelHandler;
logToExcelHandler.Successor = logToDbHandler;
The first step above was to initialise each handler that will be going into the chain. We then use the Successor property to chain the three handlers together. The beauty of using this pattern is that you can chain however many handlers you want and even make the chain configurable so that it is setup at runtime depending on some settings in a config file.

Now, when a new request came through my API, it was a simple case of invoking the HandleRequest method on the first handler in the chain and passing the ApiDataRequest object through as a parameter. This sent the object down the chain, allowing each log handler to inspect it and decide whether to log it to their individual outputs.
logToXmlHandler.HandleRequest(request);
* Update *

One thing that I missed in this post and is worth mentioning is a scenario where you don't want each concrete handler to decide whether to pass the request on down the chain. In this case, the request would go to every handler in the chain regardless. One way to accomplish this is to update the HandlerBase class as follows:
public abstract class HandlerBase<TRequest>
{
    public HandlerBase<TRequest> Successor
    { 
        protected get; 
        set; 
    }

    public void HandleRequest(TRequest request)
    {
        Handle(request);

        if (Successor != null)
            Successor.HandleRequest(request);
    }

    protected abstract void Handle(TRequest request);
}
The updated HandlerBase now implements a public HandleRequest method which first delegates the handling logic to an abstract method (Handle) which will be overridden by a concrete handler. Once a request has been handled, a test is made to check if there is a successor and if there is, then the request is passed on. What this now means is that each concrete handler will implement just one method, Handle, and not need to worry about whether to pass the request on or not - that is done automatically in the HandleRequest method. An example concrete handler is below:
public class LogRequestToXmlHandler : HandlerBase<ApiDataRequest>
{
    protected override void Handle(ApiDataRequest request)
    {
        // Check request and log it, if required
    }
}