I downloaded the Hanselminutes podcast nr 202, and only by reading in the title the word “WebformsMVC”, my interest was drawn.
I googled for it and found http://webformsmvp.com. A framework for using the MVP pattern in Webforms. I see the positive side, familiarity if you know webforms, using your control-libraries, but still get the benefits of testability and the benefits you get with a decoupled architecture.

In my previous post Multiple search criteria searching using Linq to SQL I talked about a way to implement multiple search criteria queries using LINQ to SQL.
Because I am doing some work using the ASP.NET MVC Framework, I looked into patterns to make a loosely coupled data layer. Ofcourse I checked out Rob Connery’s blog, he created the MVC Storefront (now Kona) the code can be found on MVC Sample Apps on Codeplex. Rob is leveraging the Repository pattern, this pattern provides dependency-free access to data of any type. I saw the screen cast where Ayende Rahien talks about ‘Filters and Pipes’.
Rob implements the filters in the MVC Storefront, I really like this approach, better than the approach in my previous post Multiple search criteria searching using Linq to SQL because it’s much cleaner, it is possible to ‘chain’ multiple criteria, but every criteria has it’s own extension method, thus following the single responsibility principle.
In my previous post in some cases I did too much in one method, I build up an IQueryable<post> for four search criteria, which breaks the Single Responsibility principle for one.

Using filters, which are extension methods that specify a filter on an IQueryable of something, makes it possible to let the calling party build up whatever they need. I know this can sound confusing, but I feel the following code example explains much better.

In my previous post, I called a few methods, and build up a IQueryable that way to satisfy every search criteria in the query.

15: Assert.IsNotNull(posts, "DataContext did not return posts when searching for 'mvc' in title");

16: Assert.AreEqual(posts.Count, 2, "DataContext did not return 2 posts when searching for 'mvc' in title");

17: }

Listing 1

Consuming filters Would not it be cool if we could use a fluent interface-like way to query the data, so it will be obvious to what we want to query?
Something like the code (also in a Unit test manner like the previous post) in listing 2:

1: [TestMethod]

2: publicvoid Search_For_mvc_in_Title_With_Paging_Test()

3: {

4: List<Post> posts = GetPosts().WithTitleLike("mvc")

5: .WhereTagsContain("")

6: .WhereBodyContains("")

7: .WithPaging(0, 5)

8: .ToList();

9:

10: Assert.IsNotNull(posts, "DataContext did not return posts when searching for 'mvc' in title");

11: Assert.AreEqual(posts.Count, 2, "DataContext did not return 2 posts when searching for 'mvc' in title");

12: }

Listing: 2

I think it is clear that the code in listing 2 is far more readable, than the code in listing 1. Another advantage is that it is easy to reuse every part of the query whenever it is needed.

Get all()
First I create a method that returns all Posts present in the database as an IQueryable<Post>. By the way, I am not using Dependency Injection, or Inversion of Control in this example, because it does not help in explaining the filters concept. BUT I think that when using this technique in a real world application, it is a good thing to use IoC (StructureMap, Windsor, Ninject, Unity, whatever…).

1: public IQueryable<Post> GetPosts()

2: {

3: var postsQuery = from p in repository.Posts

4: select p;

5: return postsQuery;

6: }

Listing: 3

Extension methods Leveraging extension methods, a .NET Framework 3.0 feature in combination with the IQueryable<T> interface, it is possible to create the filters. The class needs to be static and public, the extension methods also need to be static and public.
The first parameter specifies which type the method operates on and needs to be preceded by the ‘this’ modifier.

In listing 3 it is obvious that every method has its own responsibility, it is easily maintainable and very readable. I think this is an elegant solution for the problem I tried to solve in my previous post, I found this better technique and want to share.

In a recentpost, I talked about a project where the requirement is to create modules that can be used in an ASP.NET webapplication and in Sharepoint 2007, where I wanted to have separations of concerns. The way I solved this is: creating ASP.NET UserControl libraries (inside their own ASP.NET Webapplication project) that we package inside Sharepoint webparts. During development we test and debug the modules in a separate ASP.NET webapplication. We use pre-build events to copy the ascx files from the UserControl libraries to this webapplication and because we set a reference to the webapplications, the dll’s are available already. Scott Guthrie has a tutorial on his website that explains how we do this.

In the post I said I wanted to leverage Unity as our Inversion of Control Container and I was thinking about using the WCSF, because I wanted to use the MVP design pattern.
After some prototyping, I came to the conclusion using WCSF was not practical for our purpose. Still I wanted to use the MVP pattern, because of unit-testing and loose coupling needs. I could not use MVC, because of the Sharepoint requirements.

The Model-View-Presenter pattern is different from MVC or Model-View-Controller in the sense that with MVC the Controller is where the request comes in and the Controller is where you control (what’s in a name…) your View and what you get from the Model.
With MVP the request comes in at the View, the View than delegates it to the Presenter that will get data from the Model and returns it back to the View.

Pic 1.: Model View Presenter pattern

The solution I finally found to be working really good is using the MVP design pattern and Unity in the following manner.

Pic 2.:Model View Presenter Class Diagram

As you can see in picture 2 the Model, View and Presenter all are implementing an interface. Practicing Interface based programming sets the door wide open for leveraging an Inversion of Control container, or IoC container. In my case I am using Unity, because I am doing this project for a client who is heavily into using Microsoft tools. All Presenters are derived from the abstract class Presenter<TView>.

Pic 3.: Interfaces used in MVP diagram

Why the interfaces? Using Interfaces for all these parts of our component makes it easy to use an IoC container. Our objects are loosely coupled and we can switch out the concrete implementations easily, because we program against the interfaces. Say we want to test the Presenter and to avoid having a dependency on a data store or some service we want to switch the Model out for an implementation that returns the same hard coded objects each time. all we have to do is create this ‘mock’ Model that implements the IZaakModel interface (on Picture 3) and we are good to go.
To make this even more appealing: if we use an IoC container we only have to change the configuration in the container to start to use this other Model…

Because the Presenter (in listing 1) is derived from the Presenter<TView> abstract class, it is necessary to tell the Presenter of what type its View will be. Because we use the Interface again, all we have to do is let Unity (our IoC container) do the work to supply the concrete implementation for this Interface. On line 13 of listing 1 we see the Dependency attribute, in this case the attribute will be used by Unity to resolve the concrete implementation of the IZaakService interface for the property (Service) on which the attribute is decorated that is configured.

The Model The Model from picture 1 implements the Interface IZaakModel, and is responsible for getting the data if the Presenter asks for it and for letting the Presenter know that it has got this data and handing it over to the Presenter.

In listing 2 the Model is listed, is also depending on Unity for the resolving of the concrete implementations for interfaces. It implements IZaakModel and thus implements the LoadCurrentZaakById method and the CurrentZaak property. When the LoadCurrentZaakById (line 22, listing 2) is called it fills the CurrentZaak property calling a method on an object that implements the IZaakService interface (the private _datasource variable that is set by the ZaakModel constructor using Unity).

When the CurrentZaak property is filled the setter (line 30, listing 2) is used and in the setter the CurrentZaakChanged event is raised. Every object that subscribes to this event will recieve the change.

In listing 1 we can see on line 20 the Presenter has attached the event and will recieve this change. On line 26 of listing 1 the ShowCurrentZaakOnView method of the View is called.

The View
In ASP.NET a request will load an aspx page, the view is where the request starts, the view than delegates responsibility to the Presenter.

On line 50 of listing 3 the OnInit method of the UserControl (our view) is listed. Inside the body of this method we can see that we instantiate a variable named container (type IUnityContainer) and put a Container.Instance in it. On the next line (line 53) we fill the private member _presenter (the private member that is used in our property Presenter) by letting the container resolve the interface IZaakDetailsPresenter. On the next line (line 54) we tell the Presenter that it’s View is this control. We have to do this here, because the View is where the request comes in. So this is the first component of our App that is loaded. Because my requirement is to create modules that can be used in Sharepoint or in ASP.NET, I cannot use the Global.asax to resolve the concrete implementations.

The ascx, or html is very straightforward, so i am not showing it, because I feel it is in the way of what i want to tell. I hope it is clear enough without it.

The Container So how can the container variable that is of Type IUnityContainer, an interface, on line 52 know what concrete class to Resolve? and where does Container come from. What does Container.Instance do?
In a class called container I create a UnityContainer using the Singleton design pattern:

Singleton Using the singleton design pattern the registering of the concrete implementation to the interfaces will be done only once, as you can see in the module I am building there are more components that follow the same pattern, so using a singleton was in my opinion the way to go in this case.
I choose to use a simple version of the singleton, I make a class called container, this class has a private static variable called instance (of type IUnityContainer).
The class has a private constructor, so the class cannot be directly created. Furthermore the class has a public static property (type IUnityContainer) that can only get a single instance of a IUnityContainer, because in the getter we check if the private member called instance (type IUnityContainer) is null or has been filled already, if it is filled the instance it contains is returned, but if it is null a new UnityContainer is instantiated and using a Fluent Interface all Interfaces and their concrete implementations are registered inside it before we pass it to the instance variable, after that the instance it contains is returned.

On line 25 of listing 4 the RegisterType has a parameter and the following RegisterType methods of the fluent interface have not. With new ContainerControlledLifeManager() as a parameter into the RegisterType method we tell Unity to resolve the concrete implementation as a singleton. In the case of the Model I need it to be a singleton, because the model is the only place some state need to be held in my architecture.

Configuration file
Configuring the registration in a configuration file is also possible, in my case I did not wanted to do it, but I can understand that in some cases that is exactly what you want.

ConclusionOfcourse a lot more has to be considered when using this architecture, but I hope this article helps in understanding how you can use Dependency injection or Inversion of control and the Model view Presenter pattern to create maintainable and robust applications.

At the moment I am in the middle of the analysis phase for a project where the product will be constructed of several (User)Controls that contain certain blocks of functionality, these controls together will create the product.
Our first client needs this product to integrate with SharePoint 2007 (MOSS 2007), but my product manager makes it real clear that at least some of the ‘blocks of functionality’ or ‘components’ need to have the possibility be integrated in existing ASP.NET web applications.

So the challenge I face is creating controls that can be integrated inside SharePoint and custom ASP.NET web apps. Another challenge is that we really want to use the MVP, or MVC pattern, to increase the level of (unit)testability and maintainability.
Also with testability in mind I want to use some kind of IoC container (Inversion of Control), to make it easier to swap out certain functionalities for others (also a Need To Have requirement), be it for unit testing, or swapping out data store's .

Create a WebPart (derived from CompositeWeb.SharePoint.Web.UI.WebPart) that hosts UserControls (that are derived from CompositeWeb.SharePoint.Web.UI.UserControl), using the CompositeWeb.Sharepoint.dll and guidance published on the WCSF CodePlex site

SmartPart
For now I created both in a really simple form and find that the SmartPart has a real nice deployment model, you install the SmartPart using a installer and you only have to activate the Smartpart in the SiteCollection to make it available in the available Webpart’s list in SharePoint. You than make a folder with the name ‘usercontrols’ in the root of the sharePoint site, where you put the .ascx files you want to be hosted. The dll belonging to the UserControl and it’s dependencies are to be placed into the bin directory of the same SharePoint site. I read somewhere that the installer sets the site´s security to full trust, but I can not verify that.

WebPart derived from CompositeWeb.SharePoint.Web.UI.WebPart The Webpart solution gives a real nice compatibility model. You derive from these types and your webpart and UserControls work in SharePoint and in am ASP.NET webapp. This is achieved through the BuildItemWithCurrentContext method in the SPWebClientApplication class (CompositeWeb.SharePoint.dll). This method runs different code depending on the running HttpApplication implementation. You have to manually edit the global.asax file in the root of the SharePoint site. You have to edit the web.config manually to make several changes, one of them is to set the security to full trust! Part of the web.config changes is to add the PublicKeytoken for the webpart in an attribute of the Safecontrol element for the webpart. Furtermore you have to place the assemblies and their dependencies into the bin directory of the Sharepoint site. Of course you could automate these task by creating an installer, but I think it makes clear that there are lots of manual tasks to be done.

At this point in time I have not decided either way, but I will post when I have.

When building applications re-using components that contain functionality that is used in more than one place in that application is best practice. More than that it is one of the fundamentals of OO development.

What about with the MVC framework?
Can we use Controls, or UserControls? Because the MVC Framework does not use ViewState, events can not be used, so how do we use these Controls with the MVC Framework?
With the MVC Framework at this moment in time we can use the MVCToolkit, this Toolkit has UIHelpers, with these UIHelpers it is easier to create Textboxes, Dropdownlists, RadioButtons etc in the View.
But what if we have a grid with the same datasource and columns that we need on different Views? How do we go about in creating say a custom 'GridControl' UserControl that we can use on one or more in our MVC Framework application?

Creating a custom Grid UserControlFirst we create a new MCV View User Control Item, through a right-click 'Add > New Item...'.

New MVC View User Control

We name the Control: 'Grid'. Than we open the Code-Behind Grid.cs file and you will see that the UserControl does not inherit System.Web.UI.UserControl, but inherits from System.Web.Mvc.ViewUserControl.
Because we want to show data in a grid, we need a way to let the Control use the same data as the containing ViewPage.
For this purpose we can use (like the System.Web.Mvc.ViewPage) the System.Web.Mvc.ViewUserControl syntax to provide our control with the object that we want to bind the grid to.

1: using System;

2: using System.Web;

3: using System.Web.Mvc;

4: using HC.Data.AuditHistory;

5:

6: namespace HC.Web.AuditTool.Views.Controls

7: {

8: publicpartialclass Grid : ViewUserControl<AuditData>

9: {

10: }

11: }

Listing 1

All we have to do now is make sure our grid looks oke and shows the right data in the right place:

Now we open the first ViewPage in designmode and drag and drop the UserControl on the ViewPage. In the ViewPage we also make sure we inherit from ViewPage and use the ViewPage syntax:

1: using System.Web.Mvc;

2: using HC.Data.AuditHistory;

3:

4: namespace HC.Web.AuditTool.AuditTool.Views.Auditing

5: {

6: publicpartialclass List : ViewPage<AuditData>

7: {

8: }

9: }

Listing 3

In our Controller we fill the ViewData with data and call the View, so the ViewPage loads and holds the ViewData. Next the UserControl is loaded by the ViewPage and it's ViewData is filled by the ViewPage's ViewData.

1: using System.Web.Mvc;

2:

3: using HC.Data.AuditHistory;

4: using HC.Web.AuditTool.Models;

5:

6: publicclass AuditingController : Controller

7: {

8: [ControllerAction]

9: publicvoid Index()

10: {

11: AuditData auditData = AuditingDataModel.GetAuditData();

12: ViewData.Add("AuditHistory", auditData);

13: RenderView("List", auditData);

14: }

15: }

Listing 4

The result is a grid on a web page.
But the beaty is that whenever a view(page) uses the same object for data, the grid will work.

I hope I made clear that with the MVC Framework we lose ViewState and events, but we can still re-use our Controls, be it in a slightly different way than we are used to.