Monday, February 08, 2010
#
Previous entries in the series
One of the requirements of our multi-tenant application, is having the ability to replace or add new pages (or parts of pages) in the system for each of our modules.
While a customer may ask for an entirely new 'area' on the site (MVC2 covers this), the chances are they just want the addition of a single page or replacement of what is already provided in the stock product.
The obvious port of call for change of this kind are the views and partial views situated within the web application, and finding a way to add or override these on a per-module basis.
Throughout the following entry I'll assume we have access to a configuration provider that looks something like this:
public interface IConfigurationProvider
{
Configuration GetActiveConfiguration();
}
Where Configuration has the following simplistic structure (for demo purposes)
public class Configuration
{
public string Theme
{
get;
set;
}
public Module[] Modules
{
get;
set;
}
}
public class Module
{
public string Id
{
get;
set;
}
}
In other words, we have a way of querying for the 'currently active configuration' (remember, our active configuration is per-request because we're attempting true multi-tenancy), and our configuration consists of a single theme and a list of loaded modules.
Each module has an Id and we'll use this to infer a number of things by convention. (Again, this is just a demo, and you can do this however you like.)
I assume each module will provide a collection of views and partial views, and if a module is loaded *after* another module, and provides another view or partial view with the same name and path, it will replace the previously loaded view or partial view.
I was asked in a comment on a previous entry what my folder structure looked like, and this is where the folder structure starts to become important.

Every module's views come packaged in a single directory, with another directory called Views inside of it.
Underneath each of these Views directories, is the same folder structure you'd expect from a traditional ASP.NET MVC Website, with a directory per controller and a collection of views and partial views.
This means that both Core and ModuleOne can contribute or replace views for the actions from the "Home" Controller.
A thing of note, is that the web.config file that would ordinarily live in the Views directory in a traditional ASP.NET MVC application has been moved out into the Site directory above all the module directories - as this does things like give you Intellisense in your views (if I recall correctly) as well as actually facilitating the functionality in the ASP.NET MVC Framework.
Expanded, our project looks like this:

Assuming the partial view "Widget" is exposed somewhere on the Index page, the following desired scenarios present themselves:
Core Module loaded:
/Home/Index requested => Index served from CoreModule, with Widget from CoreModule
/Home/Extra requested => Page not found
Core + ModuleOne Loaded (in that order)
/Home/Index requested => Index served from CoreModule with Widget from ModuleOne
/Home/Extra requested => Extra served from ModuleOne
ModuleOne + Core Loaded (in that order)
/Home/Index requested => Index served from CoreModule with Widget from CoreModule
/Home/Extra requested => Extra served from ModuleOne
Enter the View Engine
This is all very well and good as our requirements are quite clear, but the next step is making the above happen!
ASP.NET MVC provides the facility to override the View Engine, which is the component that determines how views are rendered.
This can be used to simply load views in from a different location, or even to allow completely bespoke mark-up to be transformed into HTML (Ala the Spark View Engine).
By default, the framework will use System.Web.Mvc.WebFormViewEngine, which is what loads the views from the View directory using the default convention and returns a ViewEngineResult containing a WebFormView which eventually ends up being used to render out the view.
The WebFormViewEngine class itself is extendable, and by inheriting from it we can change the search paths it uses to locate the views and partial views.
Naturally this is the first place we look to solve our problem, as writing less code is always preferable if we can get away with it.
The set-up of WebFormViewEngine is that in the constructor we can give it a selection of search paths - which means for the life-time of WebFormViewEngine those search paths are set.
They can be modified per-request, but WebFormViewEngine inherits from VirtualPathProviderViewEngine which caches paths under which it has found files (or at least, reading the source it looks like it does!).
For performance purposes (per-configuration path caching), it would probably therefore be best implementing a ViewEngine from scratch, but as the main body of work is achieved through the return result of the view engine methods, this is not as daunting an experience as we might think.
This is what IViewEngine looks like when we first create it:
public class ModuleViewEngine : IViewEngine
{
public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
throw new NotImplementedException();
}
public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
throw new NotImplementedException();
}
public void ReleaseView(ControllerContext controllerContext, IView view)
{
throw new NotImplementedException();
}
}
First things first, ReleaseView doesn't need to do anything unless the views you return implement IDisposable, and for that the following code can be used.
public void ReleaseView(ControllerContext controllerContext, IView view)
{
IDisposable disposable = view as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
The next thing of note is that the searching logic for locating the files is the same regardless of whether the engine is looking for a view or partial view, so we can create the following method and forget about it for now:
private string ResolvePath(String requestedFile, ControllerContext controllerContext)
{
throw new NotImplementedException();
}
FindPartialView and FindView both return the same type, and with similar values - I won't go into detail because the procedure is well documented elsewhere, but my methods in this example look like this:
public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
String foundFile = ResolvePath(string.Format("{0}.ascx", partialViewName), controllerContext);
return new ViewEngineResult(
new WebFormView(foundFile),
this
);
}
public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
String foundFile = ResolvePath(string.Format("{0}.aspx", viewName), controllerContext);
return new ViewEngineResult(
new WebFormView(
foundFile,
masterName),
this);
}
Note: This example will not deal with absolute paths being specified, it will also not deal gracefully with the file not being found at all - this simply involves returning a list of the searched locations on failure and isn't worth discussing further here.
ResolvePath is entirely dependent on the logic you want to follow when searching for your per configuration module provided views, but a reference implementation might look like the following:
private string ResolvePath(String requestedFile, ControllerContext controllerContext)
{
String result = string.Empty;
// Reverse the module order so we search from most recently ordered first
var searchModules = mConfigurationProvider
.GetActiveConfiguration()
.Modules
.Reverse()
.Select(m => m.Id);
// Search through each module in turn
foreach (String module in searchModules)
{
// Try the controller specific view folder first
String controllerName = controllerContext.RouteData.Values["controller"] as string;
result = GetFilename(requestedFile, controllerContext, module, controllerName);
if (string.IsNullOrEmpty(result))
{
result = GetFilename(requestedFile, controllerContext, module, "Shared");
}
if (!String.IsNullOrEmpty(result)) { return result; }
}
// Error!
return null;
}
private string GetFilename(String requestedFile, ControllerContext controllerContext, String module, String controllerName)
{
String path = string.Format("~/Views/{0}/{1}/{2}/", module, controllerName, requestedFile);
String filename = controllerContext.HttpContext.Server.MapPath(path);
if (File.Exists(filename)) { return path; }
return null;
}
Where mConfurationProvider is the IConfigurationProvider mentioned earlier.
In this implementation, we reverse the order of the loaded modules to get the most recently loaded first, and then select just the module id.
That gives us a list of folders names to search through in order to find the view, first attempting to find the file within the folder for the current action, and then the shared directory (just like the default WebFormViewEngine).
If it's not found, we return null and cross our fingers and hope for the best.
Just to re-iterate, in the real world you need to add error handling for when a view is not located, and code to deal with absolute paths (although maybe you don't support them and don't need to write that code!).
Because we have the current configuration, we can perform the caching of file locations on a per-configuration basis - just remember to disable caching during testing and debugging!
Summary
I haven't gone into a lot of detail about the implementation of the view engine because it's beyond the scope of this blog entry - a lot of information about writing custom view engines can be found with a "Bing" (or Google search *cough*) and it was not my intention of repeating them.
What we have covered is how we might utilise the power of view engines and a set of folder conventions to allow modules to create/override views and partial views.
As with all of these entries, the actual implementation is up to you and your particular product needs and the code examples should not be taken as gospel.
Next entry we'll be getting even more technical and covering how we can allow the modules to provide actions for these added views - and even how to override controller actions that have already been defined in other modules.
Examples of this code can be found in the DDD8 code samples here.
Friday, February 05, 2010
#
The video is now up of my talk at DDD8, I've reviewed it and determined that while it's a bit fast ("Like listening to a podcast at double speed" according to @lukesmith) it's not too embarrassing.
Unfortunately the audio gets a bit out of sync towards the code, so you'll have to use your imagination until what I'm talking about shows up ;-)
Multi-tenant ASP.NET MVC Projects (Or 30 very different customers and a single codebase) - Rob Ashton - DeveloperDeveloperDevel from Phil Winstanley on Vimeo.
Thursday, February 04, 2010
#
Previous entries in the series
In the last entry, we covered the basics of what I consider multi-tenancy to be, and why we might perhaps want to write our ASP.NET MVC web application with multi-tenancy in mind.
The "ASP.NET MVC" component (or front-end) of your multi-tenant application probably only covers a small fraction of your entire codebase but is also the first and often only contact your customer has with your application, so ends up being their first point of call when asking for changes to your system.
It also ends up being the most awkward part of to change because that's the nature of using a framework like ASP.NET MVC which is designed primarily to be used in single-tenant scenarios.
Before getting into the technical details of how I implement a multi-tenant app in this environment, it's worth covering the components of our chosen framework and establishing where to start.
Disclaimer: This will not be an overly technical post, and I apologise to those that want me to just jump right in and start talking code. This will be the last introductory post in the series - promise :)
Getting to the point, this is how I personally split up the MVC application concepts into themes and modules.
| Themes |
Modules |
| CSS |
Views |
| Theme-specific images |
Partial Views |
| Theme-specific JavaScript |
Controller actions |
| Master pages |
Module-specific JavaScript |
JavaScript
Whether we like it or not, designers like to deploy JavaScript alongside their designs these days, most notably with libraries such as Niceforms and its associated brethren.
It therefore pays to make the distinction between functional and theme-specific JavaScript and allow both modules and themes to provide their own collections of scripts.
For shared libraries like jQuery etc, they can be made available as part of the core application, and modules and themes can take it for granted that it will be available for their use.
CSS
Most theming can be achieved by switching style sheets if the mark-up has been designed properly and this is an obvious candidate for theming support. Switching between style sheets is a trivial and well documented operation and can easily be achieved through the use of a HtmlHelper extension method.
I'll assume I don't need to write an entry on achieving the switching between either the CSS or JavaScript, although as with anything if prompted I'll cover the subject.
Master Pages
Sometimes the client wishes for major structural changes to the web application, and CSS changes may not be enough. For this we have master pages although because of the increased cost of having to maintain the extra mark-up they should probably only be used as a last resort.
I wrote a blog entry about the various methods of switching between the master pages at runtime a while ago so I won't be covering that again.
For my purposes over the coming posts, I assume that the structure of the master page IS a part of theming, and that we are using sub-master pages and separate child master pages across the site for different interfaces. I therefore use the OnPreInit method mentioned in the above entry for the greatest amount of flexibility.
Views + Partial Views
New modules will require either new views or the ability to override existing views, and thus I consider views to be a functional aspect of the application.
I have seen views and partial views used for theming in frameworks or products where actual functional module support was highly limited. I assume a multi-tenant system *does* have decent functional module support and thus they are part of modules and not theming.
Mark-up in the views should simply be kept as theme-agnostic as possible, as themes won't be able to change it.
I'll be covering this in this series, utilising the power of a custom view engine to find and replace views based on the currently active modules.
Controller Actions
These are obviously an important part of adding functionality to the application through the use of modules.
Because we have the ability to not only add new views, but to modify them - we also need the ability to add new actions and indeed replace existing actions (as modified views may accept modified view models!)
This is probably the hardest problem to solve and there are a few ways of solving it, this too will be coming in this series - using custom controller factories to compose or locate controllers dynamically based on the currently active modules.
In Summary
We have covered the components of an MVC web application and established where the boundaries lie between modules and theming support.
In the next entry I'll be covering how to utilise view engines to achieve the per-module views and partial views.
Monday, February 01, 2010
#
I'll be gratuitously "borrowing" a lot of material from my DDD8 slides in this post, it seemed like the right thing to do given that this series is a write-up and then continuation of that talk.
When dealing with more than one customer in the desktop market, it is customary to have a single product which is extendable through the use of plug-ins and an API, and often you can leave it up to your consumer base to write those plug-ins and add to your product in a manner they see fit.
In the web world it's a bit different, and you don't typically get that kind of behaviour (Facebook applications may or may not count, depending on how you look at it).
In a simple world, you'll have a single product which is used directly off the shelf by multiple customers:

When building web applications for a varied and paying customer base, It is likely that you have customers that are fickle and will want things done their way.
It often does not make business sense to turn good business down, and the business is what pays the hungry developer and thus when you finally get a customer who wants things done differently, the business tells the developer to jump and the business's required response is the proverbial "how high?".
Consider the above diagram then, and imagine Customer A asking for something 'just a little bit different' and think about what your options could be.
We'll get the obvious dusted out of the way first:

When I switched to the above code as a slide in my multi-tenant talk, I was greeted with laughter, but we've all known products which have ended up with such delightful nuggets in them.
It's blindingly obvious that it's not the right solution, and that as you progress down the route of making further modifications for either Customer A, B or C you'll end up with an un-maintainable mess of switches and flags. 'Nuff said.
You could then decide that you're going to keep that customer as a new product in its own right - that would remove the need for all those on-off switches.

This should very obviously be a big no-no as maintaining that then bespoke product and keeping it up to date with any changes then made to your core product is going to be nothing more than a giant headache.
As you get more customers, the number of developers you'll need to hire will increase almost in direct proportion to the number of codebases you have to maintain! (Again, I've seen this done - so don't think I'm just pointing out the obvious for the sake of it)
Let's move onto the more-often used approach, of branching from a base product for your different needs, and utilising the power of a source control system to keep changes in sync between your code-bases.

Customer A can be kept up to date by merging changes from the core product, and Customer B/C can get additional features from Customer A's branch if and when they desire it.
At first glances, it seems like this solution fits our needs - and indeed it can work well in a lot of given scenarios. The problem comes when you scale this solution up to more than this small example - as few of us are (un)lucky enough to be able to deal with only three customers and remain financially viable!
Here is a small example of 30 customers sharing 15 code-bases!

Yowsers!
How do you keep track of who has what features?
How do you test all of those different branches of code?
How do you deploy those branches of code?
How do you make a new version of the product and serve it to a customer?
How many developers do you need to manage that process?
It's never as simple as it looks, and you end up with not only the above problems, but you end up with the additional problems of what happens when a branch becomes radically different and you're unable to merge changes around.
There is too much developer interaction here - and your skilled staff end up having to spend most of their time creating new branches/pushing changes around instead of spending their time doing what they're actually trained to do - writing code.
Adding a new customer shouldn't be about changing code, it should be about manipulating configuration, and modifying a customer shouldn't be about changing code, it should also be about manipulating configuration.
In other words, problems should only be solved once - and configuration should be used to give or take features to and from customers.
Enter multi-tenancy...
The core concept of a well written multi-tenant application is that you should have a single code base, and a number of configurations - where each configuration tells the runtime what functionality should be available and what the look/feel should be.
Before continuing, I'd like to define a few of the terms I'll be using throughout this series of blog entries.
- Module: A discrete set of functionality
- Theme: The look and feel
- Configuration: A selection of modules, and a single theme
This is a personal leaning, and I know that some people would set this up differently. Each to their own, we've got to draw lines somewhere!
Anyway - as far as I'm concerned, Multi-tenancy gives us some of the following benefits:
Deployment becomes a simple case of installing your application onto a server, and setting up the configurations for that application.
When a request comes in, context is determined by some means (auth credentials, the hostname, whatever), and the relevant configuration is selected from that context.

This is a very simple way of working, and if you design your application correctly, it becomes obvious that your hosting/maintenance costs can be reduced.
You can have multiple servers with the exact same codebase installed on them, and with all the configurations available to them (In other words, identical). Scaling up becomes a simple matter of adding more of those identical servers - and if you're really smart you can load balance across your VPSs and power them up/down as required.
You no longer need to worry (too much) about the fact that you have all of those customers, and you can concentrate on the health of your system as a whole.

Some more benefits:
- You add a feature once, and deploy it to your customers through the use of configuration
- You can fix a bug, and deploy the fix once
- Potentially easy management of your infrastructure (This actually comes through good design, and multi-tenancy just aids in that goal)
- Developers get to spend their time coding new features/fixing bugs
- New customers can have a site created in minutes and start to give feedback immediately
Everybody is a winner and we all get to go home and have pie and punch.
In the next entry, things will hot up as I'll start to look at ASP.NET MVC and determine the components that we can use to aid us in creating a multi-tenant application.
Sunday, January 31, 2010
#
I spoke about this chestnut briefly at DDD8, and I want to start expanding on the subject.
My plan is over the next few weeks to start talking more about multi-tenancy in our web-apps, and to get everybody else doing the same - speaking to other developers after my talk I realised that we're not alone, people are working on solutions but they're just not talking about it.
By getting some dialogue going, I hope we can generate a public description of what is good and what is bad about attempting to build multi-tenant applications on top of ASP.NET MVC, and what our possible avenues of achieving this can be.
The suggested topics I aim to cover in this series of blog entries will (to begin with) be somewhere along these lines: (As I've already written most of the material!)
- What is multi-tenancy and why do we want it?
- The building blocks of a multi-tenant application in ASP.NET MVC
- How I integrated MvcEx into NerdDinner to give it some multi-tenant capabilities
If there is anything else you think I should cover as part of this series, then let me know by either Twitter or the comments field below.
I am loathe to go into detail on what I consider to be the other 90% of the multi-tenancy story - your domain, the rest of your codebase, managing your databases/configurations etc, as you can get all of that information from people who are far more versed in the subject than I.
But, if pushed on a particular subject I guess I will describe how I deal with those issues in the codebases I have control over, and you'll have to take it (as you should take anything written on these pages) with a pinch of salt.
Wow.
That was a wonderful day, and the sessions I ended up going to were:
- @ICooper's session on MVC Architecture (preaching the choir but good to be re-assured)
- @robashton's session on Multi-tenant ASP.NET MVC (obviously)
- @holytshirt's session on Mono (Good to see this project is advancing well)
- @garyshort's session on JClosure (Lovely!)
- @blowdart's session on the crystal maze
The last session was interrupted constantly by the MVPs and associated crowd because Barry is leaving the UK and heading off to MS to learn how to spell :)
There isn't much specifically to talk about really, it's been said by everybody. The event was well organised, the post-event meal was also surprisingly kept in control and the post-event drinks ... well I'd had no sleep the previous night so I left early. I believe fun was had by all however.
My talk? I think it went okay - I was a bit nervous presenting on a subject that doesn't get talked about openly all that much, and worried the audience might throw a few massive spanners in the works (although I am open to change, I don't want to be told outright I'm wrong in the middle of a talk!)
I spoke a bit fast, and had a minor emergency at the start when realising I needed an adapter for my laptop, but was saved by the team whose job it was to babysit me and massive thanks goes to them for saving my presentation :)
My slides can be found here, and demo code can be found here.
The nerd dinner multi-tenant example can be found on the MvcEx codeplex site (http://mvcex.codeplex.com) - but I'll be hoping to improve it beyond its "suitable for demo" stage and do some blog entries on the rationale behind some of the decisions/concepts found within over the coming weeks.
It's not perfect, it's not anywhere near done and as I keep telling people, it's just for reference purposes (at present), feel free to make suggestions, contributions and etc and we'll get there in the end. Multi-tenancy is the future you know?
Friday, December 18, 2009
#
I can't for the life of me get this to work, and [SetCulture] appears to be working fine - so I can only assume it's a bug.
I've posted to the mailing list and started off the process of working out whether it is a bug or not, but for now - I need to have my tests running in the right culture, without any side effects on the other tests once a test has been complete.
Here is my hack to do that:
public class CultureContext : IDisposable
{
private CultureInfo mOldCulture;
public CultureContext(String cultureName)
{
mOldCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureName);
}
public void Dispose()
{
System.Threading.Thread.CurrentThread.CurrentUICulture = mOldCulture;
}
}
The usage is as follows, within a test do:
using (new CultureContext("fr-FR"))
{
// Test code here
}
This will ensure that your test runs with the ui culture of "fr-FR", before resetting it to whatever it was before the test began. Not pretty, but it'll do until I work out if it's user error or a bug preventing NUnit from doing what I want it to do!
Friday, December 11, 2009
#
Developer Developer Developer Day 8 has been announced, and I'm going to propose a couple of sessions, and hopefully use one of them to talk about an open source project I've been cooking for a month or so now :)
Click here for details!
Sunday, November 01, 2009
#
When developing a web application that's designed for re-deployment in a number of different environments (such as a blogging engine/forum system/etc), it's helpful to be able to re-skin and re-structure the application without modifying any application files.
To a very large extent, this can be achieved through the use of an alternative set of cascading style sheets and this works for a large number of people. However if you take a look on programming websites such as Stack Overflow the question of how to change the master page at runtime is still an oft-asked one.
In ASP.NET Forms the solution was to simply subclass Page, override PreInit and change the MasterPage property based on some application variable. The master page specified by the corresponding ASPX file could even be read out and used to determine which themed master page to use. (A useful function if you had multiple master pages used throughout the site).
public class ThemedPage : Page
{
protected override void OnPreInit(EventArgs e)
{
if (this.MasterPageFile.EndsWith("MasterOne.Master", StringComparison.InvariantCultureIgnoreCase))
{
// TODO: Some logic here to find the right master page based on theme!
this.MasterPageFile = "/Views/Shared/MasterThree.Master";
}
base.OnPreInit(e);
}
}
In ASP.NET MVC the playing field has been altered somewhat, and there are a number of options to consider when creating an application with dynamic master pages.
The most championed solutions found on the afore-mentioned programming websites are to either pass the master page name into the View() method when returning a ViewResult , or to create a custom view engine which specifies the master page.
Passing the master page name into the View method
When returning a ViewResult via any of the built in methods (Controller.View()) the option is provided to pass in the name of as master page - and the default view engine will look for a master page with that name in the ~/Views/Shared directory.
Alternatively you can modify the ViewResult before returning it from your action method - which is probably the preferred option in most cases as you probably don't want to be passing in the name of the view all the time too.
public ActionResult SomePage()
{
return View("SomePage", "MasterTwo");
}
public ActionResult SomeOtherPage()
{
var view = View();
view.MasterName = "MasterTwo";
return view;
}
It is obvious however from these two examples that this is an un-maintainable solution; having to specify the master page on every single action is going to get tedious and if you decide to change this solution for a different one later on you're going to have to go back and modify all of those method calls.
This leads us nicely on to the next possible solution, of having this work done for us globally by the controller.
It would be possible to pass in the name of a different master page by using a helper somewhere that knew the details of the current theme and therefore the names of the master pages it uses.
Overriding OnActionExecuted on the Controller class
Rather than specify the master page name as the result of every single Action method, you could either create a base controller or override OnActionExecuted on a case-by-case basis.
OnActionExecuted gives you a chance to modify the result after an action has been invoked, which means you can take the ViewResult which was returned by an action and set the MasterName on it in this location.
You could even detect whether the MasterName property had been set, and not override it if an action has already explicitly set it.
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
var action = filterContext.Result as ViewResult;
if (action != null && String.IsNullOrEmpty(action.MasterName))
{
action.MasterName = "MasterThree";
}
base.OnActionExecuted(filterContext);
}
This gives you the power of being able to specify a master page per controller and still have the flexibility of overriding it per action.
It's still not ideal though, there is a certain amount of manual work required in doing this that you wouldn't want if you were going to be developing a large system with a substantial number of controllers or actions.
Custom View Engine
Moving further up the processing chain, the Custom ViewEngine allows the application to specify the master file for any request.
For the purposes of this example I'll derive my custom view engine from the standard built-in WebFormViewEngine as it requires the least work to get up and running.
public class ThemedViewEngine : WebFormViewEngine
{
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
if (string.IsNullOrEmpty(masterName))
{
masterName = "MasterOne";
}
return base.FindView(controllerContext, viewName, masterName, useCache);
}
}
This is registered in place of the built in view engine like so:
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new ThemedViewEngine());
Now let's take a look at that code - passed in to the method we're overriding (FindView) is a string called masterName. This is where that string ends up if you use either of the two previous two methods to specify the master page.
It follows on therefore that just like the last example you can do a check here to see if a master page has already been specified by the previous two methods, and specify one if one has not been set already.
ViewPage - OnPreInit
All of the above methods completely ignore the master page directive set in the view itself - which is in my opinion a little bit bonkers.
By specifying a master page in the ASPX view, you allow the compiler to verify that the right ContentPlaceHolders are overridden and therefore if you enable compilation of your views you get a check that your view are valid.
Consider for example the site that has a number of base master pages, one of my personal sites for example has three master pages which are used in different circumstances and each of them have different ContentPlaceHolders because they're for use in completely different functional situations.
The application is probably unaware of these directives (and indeed should be probably be de-coupled from such concerns as whether a page is using a particular master page or not) and therefore shouldn't be making the decision as to which master page to use!
ASP.NET MVC is built on top of ASP.NET Forms however, so it turns out that we can ignore the delightfully helpful methods given to us in ASP.NET MVC and skip right back to our original solution of overriding OnPreInit on the base Page class.
Knowing that ViewPage is inherited from the ASP.NET Forms Page, so we can create ThemableViewPage
public class ThemedViewPage<T> : ViewPage<T> where T : class
{
protected override void OnPreInit(EventArgs e)
{
if (this.MasterPageFile.EndsWith("MasterOne.Master", StringComparison.InvariantCultureIgnoreCase))
{
// TODO: Some logic here to find the right master page based on theme!
this.MasterPageFile = "/Views/Shared/MasterThree.Master";
}
base.OnPreInit(e);
}
}
public class ThemedViewPage : ThemedViewPage<Object> { }
Note: I create a generic version and a non generic version so we can use it on non strong-typed pages (Some people use these, I don't know why!)
We can use the same theme code we used in the original example to solve the problem - and best of all, it is still compatible with the previous three methods - so if a different master page is specified by either an Action, a Controller or the ViewEngine this logic will still work.
The only caveats that I can see are that this method is quite dependent on the default WebFormView implementation, and that every view needs to be set up to inherit from this custom ViewPage .
Summary
Switching between master pages is still a bit of a fuzzy topic, and the options given to us in ASP.NET MVC are a bit inadequate. There is still the question as to whether we should be attempting to do this at all given how powerful CSS is - but if you really need to, this blog entry should give you a helpful pointer in the right direction.
In the projects I own technically where this sort of functionality is going to be requested, I'll be sticking to the OnPreInit method until something better comes up.
Technorati tags: ASP.NET, ASP.NET MVC, Master Pages, Themes
Wednesday, October 28, 2009
#
I've just had a fun evening trying to come up with a half-suitable solution for this problem and thought it worth documenting here although my next entry isn't due for a couple of days.
As previously mentioned, we run a legacy classic ASP system for most of our clients and we're in the process of writing a replacement system in .NET.
This week we finished the user acceptance testing on the first deployable .NET application - a small interface built as a replacement for a small portion of that classic ASP system and needed therefore to build it to a live server.
The servers are fairly locked down as you'd expect and a change request had to be submitted to get .NET Framework 3.5 installed along with the .NET 2.0 runtime. I installed some routine security updates at the same time and rebooted the servers one at a time whilst testing that the legacy sites still worked.
All seemed great until the next day when a very tired CTO turned up asking if he could get some sleep tonight because he had been receiving Nagios alerts all night telling him that the live sites were failing over.
Looking at the logs we could see that the application pools for most of the legacy sites had been recycling every hour and freezing for a vast majority of that hour - and with a bit of creative debugging the problem was isolated to the CreateObject calls to a pile of both in-house and third party managed COM objects installed on the server.
Rather than failing gracefully and logging an error, for some reason the calls were simply backing the server up and causing it to stop responding to requests.
I had a hunch that this was to do with the new version of the runtime we had installed and set about trying to prove that this was the case.
When an un-managed process (in this case our IIS worker process) is started up, it is obviously done so without initializing the .NET framework. If you then attempt to load a managed assembly into that process (in this case our COM object), the most recent version of the framework will be loaded into that process.
At the moment, only one version of the .NET Framework is capable of being loaded into a single process, and this is determined on a first come first served basis. 99% of the time if you load a .NET 1.1 assembly into a .NET 2.0 process, things will work fine because there are few breaking changes between the two runtimes - however there are cases where this does not hold true and as people always say "your mileage may vary".
In IIS, the application was set up as being a .NET 1.1 website - but I wasn't convinced that this had much to do with anything and decided to try out a little hack based on my previous experience with desktop application development, COM and the different .NET runtimes.
When you deploy a .NET application, you can supply a configuration file with various overrides/version-mappings/etc alongside that application with the convention <applicationname>.exe.config. This means that you can also supply a configuration file for an application you don't "own" and modify that way it works on your machine.
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v1.1.4322"/>
<requiredRuntime version="v1.1.4322"/>
</startup>
</configuration>
Some of the suggestions on the internet were to stick this in a web.config file at application root, but:
- I've read elsewhere that this is not supported in web applications
- I had a feeling that this directive would be ignored because the web.config file would only be read when a .NET resource was requested.
I decided that my nail was much bigger, and instead created an inetsrv.exe.config, a w3wp.exe.config and a dllhost.exe.config with the above directive in and placed them in system32/inetsrv and system32 respectively.
Restarting IIS and hitting my test page with all the CreateObjects (my fail case) yielded in a success and my next step was therefore going to be to find something that didn't involve forcing all IIS processes and god knows what else to run with .NET 1.1 and .NET 1.1 only.
As previously mentioned, which runtime loaded into the worker process depends entirely on who first requests that a .NET assembly be loaded into process. The alternative in the desktop world and certain other places would be to manually invoke the .NET runtime with an explicit call to CorBindToCurrentRuntime or similar.
I decided the best approach would be to force the IIS worker process to do this for me by invoking some .NET code in the context of the application. This would then use the framework version specified in the application and solve all the problems.
A few options were considered such as:
- Creating a global.asax to get executed when application starts
- Creating a web.config file as outlined in a few of the responses to questions like this on the internet
- Creating a dummy aspx file which could be requested by global.asa on application startup
1 and 2 wouldn't work because no requests are ever made to the server through the aspnet extension, so 3 seemed to be the only reasonable solution.
The following aspx file was created on the server:
<%@ Page Language="vb" AutoEventWireup="false" %>
<p>Hello World</p>
And the following code added to global.asa:
if not Application("hasInitializedNet") then
Dim reqUrl
reqUrl = "http://" & Request.ServerVariables("LOCAL_ADDR") & "/default.aspx"
Dim objXmlHttp
Dim strHTML
Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
objXmlHttp.open "GET", reqUrl , False
objXmlHttp.send
strHTML = objXmlHttp.responseText
Set objXmlHttp = nothing
Application("hasInitializedNet") = true
end if
The application was restarted and voila, the page was requested when the first user hit the server and the right version of.NET was loaded into the application from the start.
I can't think of a neater way that would allow us to still have our .NET 3.5 applications on the same machine and this solution is good enough for now (Until we get another pair of servers in for the new systems).
Feel free to leave any better suggestions in the comments!
Technorati tags: COM, ASP.NET, .NET Runtime, ASP