DevIntersection is the final stop in the .NET Rocks! road trip and runs from December 9th to the 12th in Las Vegas. In addition to conference sessions I’ll be doing an ASP.NET MVC 4 workshop on December 13th. Register by November 15th to receive a Windows 8 tablet!
The Warm Crocodile Developer Conference is a 2 day conference in Copenhagen, Denmark with a great selection of speakers and sessions. In the words of the organizers – “We want to create a brand, a conference brand that promises to deliver on set of great things, both people and content, but also, and just as much fun and partying and networking.” 
I hope to see you there!
MemFlex is a look at what is possible in an ASP.NET MVC application if you eschew the existing ASP.NET providers for membership, roles, and OAuth. MemFlex doesn’t use the existing providers, but does use classes from the .NET framework and DotNetOpenAuth to build a membership and roles system with some simple requirements:
- Support all the actions of the MVC 4 Internet AccountController (register, login, login with OAuth).
- Be test friendly (by providing interface definitions for both clients and dependencies)
- Run without ASP.NET (for integration tests and database migrations, as two examples).
- Work with a variety of data sources (two common scenarios for storing use accounts these days involve document databases and web services).
Here are parts of the project as they exist today.
The sample application is a typical MVC 4 Internet application where the AccountController and database migrations use the FlexMembershipProvider. There are classes provided for working with both the Entity Framework and RavenDB, and you can (almost) switch between the two by adjusting an assembly reference and the namespaces you use.
After you’ve defined what a User model should look like, the first part would be configuring a FlexMembershipUserStore to work with your custom user type.
using FlexProviders.EF;
namespace LogMeIn.Models
{
public class UserStore : FlexMembershipUserStore<User>
{
public UserStore(MovieDb db) : base(db)
{
}
}
}
The above code snippet, which uses EF, just requires a generic type parameter (your user type), and a DbContext object to work with. The UserStore is then plugged into the FlexMembershipProvider. You can do this by hand, or let an IoC container take care of the work.
var membership = new FlexMembershipProvider(
new UserStore(context),
new AspnetEnvironment());
Once the FlexMembershipProvider is initialized inside a controller, you can use an API that looks a bit like the traditional ASP.NET Membership API.
_membershipProvider.Login(model.UserName, model.Password
The FlexProviders part of the project consists of 4 pieces: the integrations tests, a RavenDB user store, an EF user store, and the FlexProviders themselves.
The FlexProviders project defines the basic abstractions for a flexible membership system. For example, the interface definition to work with locally registered users (for now, a separate interface provides the OAuth functionality):
public interface IFlexMembershipProvider
{
bool Login(string username, string password);
void Logout();
void CreateAccount(IFlexMembershipUser user);
bool HasLocalAccount(string username);
bool ChangePassword(string username, string oldPassword, string newPassword);
}
There is also a concrete implementation of a flexible membership provider:
public class FlexMembershipProvider : IFlexMembershipProvider,
IFlexOAuthProvider,
IOpenAuthDataProvider
{
public FlexMembershipProvider(
IFlexUserStore userStore,
IApplicationEnvironment applicationEnvironment)
{
_userStore = userStore;
_applicationEnvironment = applicationEnvironment;
}
public bool Login(string username, string password)
{
var user = _userStore.GetUserByUsername(username);
if(user == null)
{
return false;
}
// ... omitted for brevity ...
}
// ...
}
Of course since the membership provider requires an IFlexUserStore dependency, the operations required for data access are defined in this project in the IFlexUserStore interface. There is also an AspnetEnvironment class that removes hard dependencies on test unfriendly bits like HttpContext.Current.
public class AspnetEnvironment : IApplicationEnvironment
{
public void IssueAuthTicket(string username, bool persist)
{
FormsAuthentication.SetAuthCookie(username,persist);
}
// ...
}
It’s relatively straightforward to build classes that will take care of the data access required by a membership provider. For both Raven and EF, all you really need is a generic type parameter and a unit of work. For Raven:
namespace FlexProviders.Raven
{
public class FlexMembershipUserStore<TUser>
: IFlexUserStore where TUser : class, new()
{
private readonly IDocumentSession _session;
public FlexMembershipUserStore(IDocumentSession session)
{
_session = session;
}
public IFlexMembershipUser GetUserByUsername(string username)
{
return _session.Query<TUser>().SingleOrDefault(u => u.Username == username);
}
// ...
}
}
And the EF version:
namespace FlexProviders.EF
{
public class FlexMembershipUserStore<TUser>
: IFlexUserStore where TUser: class, IFlexMembershipUser, new()
{
private readonly DbContext _context;
public FlexMembershipUserStore (DbContext context)
{
_context = context;
}
public IFlexMembershipUser GetUserByUsername(string username)
{
return _context.Set<TUser>().SingleOrDefault(u => u.Username == username);
}
// ...
}
}
This project is a set of integration tests to verify the EF and Raven providers actually put and retrieve data with real databases. The EF tests require the DTC to be running (net start msdtc). The tests are configured to use SQL 2012 LocalDB (for EF) by default, while the Raven tests use Raven’s in-memory embedded mode.
None of the code is vetted or hardened and still needs some work, but if you find it to be an inspiration or have some feedback or pull requests, let me know.
There are no NuGet packages available, as yet.
I said in the last post that building a membership system is easy if you know exactly what you want. You can mostly rely on other pieces of the framework for the hard parts (creating secure cookies and cryptography, for example, but also relying on DotNetOpenAuth for the OAuth heavy lifting).
The hard part of building a membership system is when you try to build it for unknown customers and unknown scenarios. I don’t envy Microsoft in the sense that if they build a membership system that is simple, 60% of their customers will say it doesn’t work for their application. If they build a membership system that is sophisticated enough to work with most applications, 60% of their customers will say it looks like WCF. Somewhere there is a sweet spot that will make a majority of customers happy.
What I have here will work for most of the applications I’ve been associated with, provides some flexibility in the data store, and still remains, I think, relatively easy to understand.
Building a piece of software to manage users is easy, but only if you know exactly what you want. After all, most of the code inside the various existing ASP.NET providers consists of straightforward parameter validation and data access. While this membership code is simple in isolation, there is still value inside the existing providers. The providers have proven themselves in production for thousands of web sites.
Unfortunately, it is difficult to derive value from the existing providers and reuse just the parts you need when building a custom membership solution for an application. The providers entangle a number of responsibilities and require a relational database. This has always been a source of frustration when building YACMP (yet another custom membership provider). My typical approach is to start from scratch by deriving from the abstract MembershipProvider class.
However, starting with the abstract MembershipProvider class doesn’t give me any inherent benefits in an ASP.NET MVC or Web API application. There are no custom controls to drag from the toolbox that will automatically integrate with a custom provider, and other than the Authorize attribute (which works against the roles provider), there is no implicit dependency on Membership.Provider or Roles.Provider, which are the typical static gateways to membership and role features.
There are actually drawbacks to building custom providers with ASP.NET MVC. The provider model doesn’t easily cooperate with the dependency resolution features of MVC and Web API. Also, the API is a bit dated and doesn’t have the ability to work with OAuth or OpenID.
The solution to the OAuth problem in a new MVC 4 Internet application is to combine a new membership provider (the SimpleMembershipProvider) with some Web Matrix bits (the WebSecurity class) into something that works with OAuth and still allows a user to register locally with a password, but unfortunately still depends on a relational database and is complicated to understand, extend, and debug (search for MVC 4 SimpleMembership and you’ll find more questions on StackOverflow than anything else).
Given that the traditional provider model doesn’t provide many benefits for MVC and WebAPI, what would it look like to build a membership system and not start by deriving from MembershipProvider? That’s the topic for the next post.
However, there are a few issues to be aware of if you build an application on top of the existing code in the AccountController.
The InitializeSimpleMembershipAttribute (let’s call it ISMA) is part of the code generated by the MVC 4 Internet template. ISMA exists to provide a lazy initialization of the underlying providers, as well as potentially create the database for storing membership, roles, and OAuth logins. You’ll find it decorating the AccountController as an action filter, so it can jump in and initialize all the bits before the controller starts to interact with the security related classes.
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
// ...
}
As an action filter, ISMA hooks into OnActionExecuting to perform the lazy initialization work, but this can be too late in the life cycle. The Authorize attribute will need the providers to be ready earlier if it needs to perform role based access checks (during OnAuthorization). In other words, if the first request to a site hits a controller action like the following:
[Authorize(Roles="Sales")]
.. then you’ll have an exception as the filter checks the user’s role but the providers aren’t initialized. We’ll talk about concerns over the exception message details later.
My recommendation is to remove ISMA from the project, and initialize WebSecurity during the application start event.
The MVC 4 Internet project template uses EF code-first classes to manage user profiles, so it includes a DbContext derived class (UsersContext) and a UserProfile entity, both of which are defined in the Models\AccountModel.cs file.
If you plan on customizing the UserProfile class, make sure you let the application create the database for you. You can see the database creation code in the ISMA also.
If you create a database yourself, make sure to include all the tables needed for the WebSecurity class. There are not scripts published that I have found, but you can always generate DDL scripts after the application runs.

If you create an empty database and run the application to let WebSecurity create its own tables, it will not include any of your user profile customizations (it will only do that for you if the database doesn’t exist).
There is a strange tension in a new application because it’s not clear who is responsible for getting all the pieces to work together. WebSecurity can create the database schema it needs to operate, but can miss creating something you add to the UserProfile entity, which is code you can customize, but you wouldn’t know that at a first glance.
If you are using the Entity Framework for an application, my recommendation is to remove the DbContext derived class from AccountModel.cs and take ownership of the UserProfile class. You’ll need to fix places in the AccountController that are looking to use the context class, but replace those pieces of code with your own context class.
If you are not using the Entity Framework, you’ll want to remove the DbContext derived class in any case.
Because the Internet project template includes an Entity Framework DbContext class in the project, if you add your own DbContext to the project and try to enable EF migrations, you’ll be greeted with an error.
PM> enable-migrations
More than one context type was found in the assembly.
To enable migrations for [Context], use Enable-Migrations –ContextTypeName [Context].
The problem is easy to solve. As the error states, you can use the –ContextTypeName flag to specify your context class name. Note that you can only have migrations for one context in a project, so if you want to have migrations for both contexts you’ll need to move one to a different project. Again, my recommendation is to just remove the existing UsersContext the Internet project template creates, and take ownership of the user profile in your own context.
The previous ASP.NET membership providers were easy to work with from the Seed method in an EF migrations class. With this new approach you need to perform some additional configuration steps. I covered these steps in a previous post: “Seeding Membership and Roles in ASP.NET MVC 4”.
It’s possible to run into an exception message like the following (like when the ISMA code runs too late):
You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.
We don’t use an _AppStart.cshtml file in ASP.NET MVC, so look to add code to Application_Start in global.asax.cs instead.
A few people have written me to ask if the AccountController created by the Internet application template is the future of ASP.NET MVC coding. A representative sample appears below:
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Specifically, people are asking about the number of static method calls through WebSecurity and trying to figure out the impact on testing and extensibility, as well as the impact on impressionable young minds who might read too much into the code.
I’ve assured everyone the future is not full of static methods. Or, at least not my future.
In some upcoming posts we’ll explore an alternative approach to membership, roles, and OAuth in ASP.NET MVC 4, and see if there is an approach that is simple, testable, and extensible enough to work with more than a relational database for storage.
If you are new to ASP.NET MVC you might not know about ELMAH and MiniProfiler. These are two distinct OSS projects that you can easily install with NuGet, and both provide valuable debugging and diagnostic services. Scott Hanselman has blogged about both projects in the past (see NuGet Package of the Week #7, and #9), but this post will highlight some of the updates since Scott's post and still provide a general overview of the features for each project.
ELMAH gives you "application-wide error logging that is completely pluggable". In other words, you can easily log and view all the errors your application experiences without making any changes to your code. All you need to get started is to "install-package elmah" from the Package Manager Console in Visual Studio and ELMAH will be fully configured and available. Navigate to /elmah.axd in your application, and you'll see all the errors (this will only work for local requests, by default).
ELMAH will keep all the errors in memory, so an application restart will clear the log. If you want the error information to stick around longer, you can configure ELMAH to store information in a more permanent location, like inside of a database. The elmah.sqlservercompact package will add all the configuration you need to store the error log in a SQL Compact database file inside the App_Data directory of the app. There are also packages to log errors to SQL Server (elmah.sqlserver), Mongo (elmah.mongodb) and more. Most of these packages require you to go into the web.config file to configure simple connection string settings, and possibly setup a schema (see the files dropped into App_Readme for more details).
For ASP.NET MVC projects you might want to start by installing the elmah.mvc package. The elmah.mvc package will install an ElmahController so you can view the error log by visiting the /elmah URL. More importantly, elmah.mvc will install an action filter to log errors even when the MVC HandleErrorAttribute (the one that most applications use as a global action filter) marks an exception as "handled". The HandleErrorAttribute marks exceptions as handled and renders a friendly error view when custom errors are enabled in web.config, which will usually be true when an app runs in production. These handled exceptions are invisible to ELMAH, but not when elmah.mvc is in place.
MiniProfiler is a "simple but effective" profiler you can use to help find performance problems and bottlenecks. The project has come a long way over the last year. To get started with MiniProfiler, you can install the MiniProfiler.MVC3 package (which also works in ASP.NET MVC 4). After installation, add a single line of code to your _Layout view(s) before the closing </body> tag:
@StackExchange.Profiling.MiniProfiler.RenderIncludes()
Update:
You'll also need to add a handler so MiniProfiler can retrieve the scripts it needs:
<system.webServer>
...
<handlers>
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
</handlers>
</system.webServer>
Once everything is ready, you'll start to see the MiniProfiler results appear in the top left of the browser window (for local request only, by default). Click on the time measurement to see more details:

MiniProfiler can tell you how long it takes for actions to execute and views to render, and provides an API if you need to instrument specific pieces of code. The MiniProfiler install will also add a MiniProfiler.cs file in your App_Start directory. This file is where most of the MiniProfiler configuration takes place. From here you can enable authorization and database profiling.
Two great projects to check out, if you haven't seen them before.
The migrations feature of the Entity Framework includes a Seed method where you can populate the database with the initial static data an application needs. For example, a list of countries.
protected override void Seed(Movies.Infrastructure.MovieData context)
{
context.Countries.AddOrUpdate(c => c.Name,
new Country {Name = "India"},
new Country {Name = "Japan"},
// ..
);
}

protected override void Seed(CitationData context)
{
var resourceName = "Citations.App_Data.Countries.xml";
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream(resourceName);
var xml = XDocument.Load(stream);
var countries = xml.Element("Countries")
.Elements("Country")
.Select(x => new Country
{
Name = (string)x.Element("Name"),
}).ToArray();
context.Countries.AddOrUpdate(c=>c.Name, countries);
}
Jon Galloway has an overview of the new membership features in ASP.NET MVC 4. The Internet project template moves away from the core membership providers of ASP.NET and into the world of SimpleMembershipProvider and OAuth.
There is quite a bit I could write about the new features and the code generated by the Internet project template, but for this post I just want to cover a scenario I've demonstrated in the past - seeding the roles and membership tables. If you are using Entity Framework code-first migrations it's relatively easy to add some code to the Seed method of the migrations configuration to populate the membership tables with some initial roles and users. Just remember every update-database command will call the Seed method, so you have to write the code to make sure you don't try to create duplicate data.
First, the new project template creates an MVC 4 Internet application without any provider configuration, but for the membership features to work properly during a migration, it appears you need at least some configuration. The following code makes sure the SimpleMembershipProvider and SimpleRolesProvider are in place.
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider,
WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider,
WebMatrix.WebData"/>
</providers>
</membership>
Then inside the Seed method of the DbMigrationsConfiguration<T> derived class, you can have:
protected override void Seed(MovieDb context)
{
//context.Movies.AddOrUpdate(...);
// ...
SeedMembership();
}
private void SeedMembership()
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
var roles = (SimpleRoleProvider) Roles.Provider;
var membership = (SimpleMembershipProvider) Membership.Provider;
if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
if (membership.GetUser("sallen",false) == null)
{
membership.CreateUserAndAccount("sallen", "imalittleteapot");
}
if (!roles.GetRolesForUser("sallen").Contains("Admin"))
{
roles.AddUsersToRoles(new[] {"sallen"}, new[] {"admin"});
}
}