Using SimpleMembership in MVC3

 

I have received a couple of questions over the past few weeks regarding how to properly get SimpleMembership to work with an MVC3 application. While it is pretty straightforward, the purpose of this post is to serve as a step-by-step “How To” setup SimpleMembership with an MVC 3 application from start to finish.

The following 4 simple steps will get you up and running with SimpleMembership in your MVC3 application in a matter of minutes. We’ll go into each step in more detail below.

  1. Create new Mvc3 Internet Application or use an existing one.
  2. Create your SqlServer, SqlExpress or SqlCompact4 database (we’ll be using SqlCompact4 in this example)
  3. Update Web.config with connection string to point to your database from step 2
  4. Install & Configure SimpleMembership.Sample package

Creating your MVC 3 Application

  1. Select File > New Project and Select ASP.NET MVC 3 Web Application.
  2. Pick your desired folder location and click Ok.
  3. Next, make sure Internet Application is selected and Razor is the View engine.
  4. In this case, we chosen to create a unit test project automatically for testing purposes.
  5. Choose OK to create your project.

Creating your database (SqlCompact4)

  1. Before we do anything else, we are going to create a SqlCompact4 database rather than using SQLExpress which is the default for new projects.
  2. To do so, right-click the App_Data directory and select Add > New Item.
  3. In the next dialog, select SQL Server Compact 4.0 Local Database, use “Database.sdf” as the filename and click Add.

Updating Web.config connection string

Now that our database is created, we need to update our connection string in Web.config to point to our SqlCompact4 database we just created.

  1. Open Web.config and locate the connection string named “Application Services”.
  2. Next, change the “Application Services” connectionString and providerName to the following:

<add name=ApplicationServices connectionString=data source=|DataDirectory|\Database.sdf providerName=System.Data.SqlServerCe.4.0 />

Installing & Configuring SimpleMembership

Now, that we have our application ready, SqlCompact database created and ready to go, now we can install SimpleMembership. For the sake of simplicity, I’m going to install the SimpleMembership.Mvc3.Sample package which include the sample account controller pre-wired for use with SimpleMembership.

  1. In Visual Studio, navigate to Tools > Library Package Manager > Manage NuGet Packages.
  2. Select Online from the left-hand pane and type in SimpleMembership in the search box at the top right.
  3. Select the SimpleMembership.Mvc3.Sample package and click Install.
  4. Next, delete the existing Controllers/AccountController.cs file that Visual Studio created for you.
  5. Rename Controllers/SimpleMembershipAccountController.cs to AccountController.cs
  6. Open App_Start/SimpleMembershipMvc3.cs and update it to point to the “ApplicationServices” connection string or your appropriate connection string.

That’s It!

You’re application is now ready to use SimpleMembership and you have a fully-functional AccountController.cs pre-wired to use the SimpleMembership API.

Enjoy!

Please post a comment if you have questions or run into issues.

The code is available here: SimpleMembership.Mvc3.Example.zip

SimpleMembership.Mvc3 – 1.1 Published

If you’re unfamiliar with SimpleMembership.Mvc3, please see this post.

Update: May 18, 2011 – Version 1.1 published to NuGet.org

This includes:

  • Minor fix to WebSecurityService to address bug reported by Phil Haack.
  • Added assembly reference to web.config.transform to reference WebMatrix.Data. Some users have reported exceptions being thrown trying to reference that namespace.
  • New SimpleMembershipAccountController which can be used as a drop-in replacement for the default AccountController in new Mvc projects. This controller uses WebSecurityService instead of the FormsAuthenticationService and MembershipService for authentication and membership. The SimpleMembershipAccountController has been moved to a new sample package: SimpleMembership.Mvc3.Sample It can be used as a drop-in replacement for the default AccountController in the Mvc3 Visual Studio project template. It uses the WebSecurityService from SimpleMembership.Mvc3 instead of the FormsAuthenticationService and MembershipService which come in the default project template.

 

SimpleMembership.Mvc3 NuGet Package

SimpleMembership.Mvc3 – 1.0

Enables the SimpleMembership API from WebMatrix/WebPages (i.e. WebSecurity) to be used with ASP.NET MVC3. This allows you to use the WebSecurity helper found in the WebMatrix.WebData namespace.

Update: February 28, 2011 – Version 1.0 released

This includes:

  • The App_Start convention from David Ebbo’s post.
  • An updated dependency on WebActivator 1.3.2 or greater (This allows us to use the new PostApplicationStartMethod in WebActivator which allows us to remove the need to modify global.asax.cs).
  • Removed need to modify global.asax.cs
  • Now, the call to WebSecurity.InitializeDatabaseConnection() is in the new Post App Startup method called Initialize() inside App_Start/SimpleMembershipMvc3.cs. This is where you’ll need to specify your connection string and user table.

Features

  • Includes a web activator and web.config transforms that enable the SimpleMembershipProvider
  • Includes an abstraction of the WebSecurity helper (IWebSecurityService) and an implementation (WebSecurityService) to enable use with DI/IoC frameworks such as NInject, etc.

Usage

  1. Modify the Initialize() method in App_Start/SimpleMembershipMvc3.cs to point to your connection string and user table.
  2. That’s It!

Using the IWebSecurityService abstraction

This package includes an abstraction of the WebSecurity interface (Services/IWebSecurityService) as well as an implementation of this interface (Services/WebSecurityService). This is useful for scenarios like using WebSecurity with Ninject or another IoC/DI framework to avoid hard references to WebSecurity and improve testability. To use this:

  • First, make sure you register WebSecurityService as an IWebSecurityService with your IoC container.
  • Next, remove the call to WebSecurity.InitializeDatabaseConnection from the Initialize() method in App_Start/SimpleMembershipMvc3.cs
  • Finally, uncomment the following lines and modify the call to InitializeDatabaseConnection() to point to your connection string and user table:
var webSecurityService = DependencyResolver.Current.GetService<IWebSecurityService>();

webSecurityService.InitializeDatabaseConnection(connectionStringName: "Default", userTableName: "Users", userIdColumn: "ID", userNameColumn: "Username", autoCreateTables: true);

Currently, the package includes the actual WebMatrix.WebData.dll assembly. I’m looking into changing the package to instead use powershell to add the reference to the project if it already exists on the user machine.

Enjoy!

Adam

ASP.NET MVC, Dependency Injection and The Bliss of Truly Decoupled Applications

In traditional software and web applications application layering is one of the tenets of good application design and architecture. It stems from the separation of concerns principle in computer science which is the process of separating applications and programs into distinct features that overlap in functionality as little as possible. Hence, the single responsibility principle and DRY concepts in software engineering and object-oriented programming.

Typically, in layered applications, a given application layer should only communicate with and depend on the layer directly below it.

Take the following diagram for example, taken from the Microsoft Application Architecture Guide v2 (I added the red arrow indicators that typically represent where dependencies are):

image

In this example, the Presentation Layer would talk to and depend on the Business Layer. The Business Layer would talk to and depend on the Data Layer. The Data Layer would talk to and depend on the database.

This is generally considered good application design despite there being dependencies between layers. However, traditionally, layer n-1 dependency  (one layer dependency) has been the normal and accepted practice. But experience tells us that all-too-often we find dependencies on more than just one layer. In fact, we may find dependencies between multiple layers…or worse….between all layers, ending up with something like this:

image

The application may work fine. In fact, it may work perfectly. But the net effect in the case of either diagram is that with each dependency, change becomes more difficult. Our apps become more difficult to maintain, more difficult to test, and more difficult to change which can result in longer development cycles, higher costs and increased risk of failure on our projects.

Usually, these dependencies come in the form of concrete class names. For example:

MyService service = new MyService();

As Scott Hanselman would say, “anytime you find yourself writing code like this, quit your job and go do something else.” No seriously, you should at least stop and acknowledge what this really is – a dependency on an implementation. Sure factory classes and singletons come in handy to remove the need to new things up. But, we still end up with a dependency – only now we’re dependent on the Singleton or the Factory.

Ideally, we want to declare a dependency on “some thing” without saying what that “some thing” is. Rather, we want to declare a dependency on a contract (an interface), rather than an implementation. Dependency Injection exists to help you do just that.

The goal of Dependency Injection (DI for short) is to separate behavior from dependency resolution, which is really just encapsulation – one of the main principles of computer science and object-oriented programming. I like to think of Dependency Injection as “intra-app SOA”; the end result being a highly decoupled application composed of “services” with explicit service boundaries and contracts (or service interfaces) where any given application layer has no knowledge of any other layers. It cares not the number of layers nor the implementation within each layer. Each layer simply depends on a contract and can be reasonably sure that at runtime there will be at least one implementation available to satisfy that contract. With Dependency Injection on our side, the above diagram might change to look something like this:

image

At first glance, this doesn’t look much different from the first diagram. We still have “dependencies.” However, now we are dependent on a contract, not an actual implementation. This provides enormous benefits to us as application developers because our application layers are now plug-n-play. They are hot-swappable like hard drives in a RAID configuration. We can change the implementation of a layer and as long as we implement the agreed upon interface, we can rest assured we won’t break something in another layer.

Of course, we still have to unit test our new layer to make sure we don’t have any internal bugs, but as long as other layers only depend on the interface (not the implementation) we know we can reliably swap out an implementation without affecting other parts of an application or system. Ideally, each implementation of an application layer becomes a “black box” to the other layers with which it interacts.

In the case of our MyService above. Instead of writing our code like: MyService service = new MyService();
Using Dependency Injection, we would instead write; IService service { get; set; }; as a property on our class or we would use constructor injection and have something like.

public class HomeController(IService service)
{

}

As you can see, we are now expressing a dependency on a contract (an interface) rather than an implementation and we are now “wired” for a Dependency Injection/IoC framework to resolve these dependencies for us without explicitly identifying them in our code.

You might say, “that’s all fine and good, but how do I make sure that my application is only dependent on contracts/interfaces?” More importantly, for existing applications that might not have been written this way, how do I find all the application dependencies and extract them into interfaces in order to move to a DI-friendly application architecture.

This is where being a .NET developer in this day and age makes your life much easier. Thanks to some new features in Visual Studio 2010, you can now answer those questions fairly easily. If you have one of the higher level VS2010 SKUs (Premium and Ultimate), you have the ability to create Application Architecture Layer diagrams. While you may have known that, you may not be aware that you can also validate an application against a layer diagram and have Visual Studio generate the dependencies between your layers so that you can see the dependencies between layers.

Using this feature, not only can you say, “my application should look like this” by creating an application layer diagram, but with the validation feature, you can ask the question, “does my application look like this?”

To get started with this feature, let’s take the following ASP.NET MVC project that I’ve setup as an example for this post. (I’ve circled the areas of immediate interest)

As you can see, I have actually organized my solution folders to mimic my application layering. We have a Repository/Data Access layer, we have a Services layer and we have a Presentation/UI layer. You’ll also notice that we have a Contracts project (or layer) which contains our interfaces.

So our dependencies go something like this:

  • Site (our ASP.NET MVC app) depends on an IUserService.
  • Our Services, depend on an IUserRepository and IUser.
  • Our Repositories depend on the IUser contract since that is the contract they return from their operations.

There are no dependencies between layers. They only depend on interfaces in the Contracts project.

You may have also noticed that there are four different “repository” projects and three different “services” projects. This is where the plug-n-play concept I discussed above comes in to play. ASP.NET MVC 2 comes with great support for Dependency Injection (which MVC 3 builds upon) which allows you to plug-in your DI/IoC framework of choice for all your DI needs. In my case, I’m using Autofac. ASP.NET MVC provides an extensibility point that allows you to say, “anytime my application needs something to satisfy a contract/interface, here’s where to find it.” That “where to find it” part is where an DI/IoC framework plugs-in to satisfy the dependencies of your application without having to declare explicit dependencies between your application layers and/or components.

Frameworks such as AutofacNinjectCastle WindsorStructureMap and Unity, all have some concept of a “registry” which is basically an Interface-to-Implementation mapping or dictionary. With our MyService example above, we would be able to register our implementation MyService as the service that satisfies all dependencies on IService. Then, any time the application needs an implementation of IService, it will ask the DI container to provide one from its registry.

I won’t go into the details of how these dependencies get registered with or resolved by the DI/IoC frameworks. I’ll save that for another post or for you to read about in your own research or digging through the attached sample code.

Instead, we’ll jump right into the benefits that using Dependency Injection provide.

So, in the diagram, we happen to have four different implementations of a DataAccessLayer.

  1. DatabaseRepository - persists data to a SQL database
  2. FakeRepository – fakes the peristence to an underlying data store (ideal for UnitTesting )
  3. MongoDbRepository - persists data to a MongoDb database
  4. XmlRepository - persists data to an Xml file

All four Repository projects implement the IUserRepository contract/interface that our Services layer depends on. This allows us to reliably swap out one for another without affecting any code in the services layer at all. So, it would be trivial to add another repository that persisted data to Oracle, SQL Azure, Amazon SimpleDB, Microsoft Access, Excel, a flat-file, what have you – just so long as the repository implements the IUserRepository interface, we’re good.

Likewise, we have three different implementations of our Services layer.

  1. CachingService – retrieves data from an IUserRepository and caches the results
  2. FakeUserService – a services that fakes retrieving data from an IUserRepository (again, ideal for unit testing)
  3. UserService – same as the caching service (just without caching)

These services all implement the IUserService contract/interface that our presentation layer (UI) depends on.

Now, on to creating an application architecture and validating these stated dependencies.

From the Architecture menu in Visual Studio, you select New Diagram.

image_thumb[64]

In the dialog box that opens, select Layer Diagram and give it an appropriate name.

image_thumb[65]

You should end up with a blank architecture diagram that looks like this:

image_thumb[66]_thumb

Now, using either the Toolbox or by right-clicking, we can begin adding layers to your diagram. After adding our application layers, our diagram should look like the following:

image_thumb[67]_thumb

Now, to validate our architecture (and dependencies), we first need to tell Visual Studio, what code/projects are in what layers. We start by dragging our projects (or solution folders) into the associated application layer. For example, in my sample solution, I would drag the entire DataAccessLayer solution folder into the Data Access layer on the diagram:

image_thumb[68]_thumb

Here’s what we should end up with when we’re done:

image_thumb[69]_thumb

It looks very similar to when we started, but now we have a small indicator in the upper-right-hand corner which tells us how many projects are associated with each layer.

Now for the magic!

Simply, right-click anywhere in the white space on the application layer diagram and click Generate Dependencies.

If what I told you above about how my application is architected is true, then you should get an updated diagram that looks like the following:

image_thumb[70]_thumb

Ah, now isn’t that diagram a breath of fresh air? In this diagram, Visual Studio is telling us there there are absolutely NO dependencies between the layers of our application! Rather, all application layers depend only on the Contracts project which is simply a collection of interfaces. This is the epitome of encapsulation and tells us that our application layers are decoupled from one another and can be swapped out for other implementations without risk to the rest of our application.

This is ideal for TDD scenarios and allows for simultaneous development on different application layers if we have already ironed out our contracts/interfaces. This means more parallel development can occur which can potentially reduce project timelines. And of course, with TDD on our side, we can reliably test individual layers and sign-off on them knowing that they are not dependent or affected by other layers/components whatsoever. End-result: higher-quality software developed in a shorter amount of time.

Now, if your application doesn’t look like this and looks more like the second picture with dependencies between every layer, don’t worry! Visual Studio can also help you find those dependencies so that you can factor out the concrete references into interfaces/contracts.

First, start by removing the dependencies from your diagram that you don’t want to have in your app – do this by rick-clicking on the dependency arrow and selecting Delete. Next, after you have removed all the unwanted dependencies, simply right-click anywhere in the whitespace of the diagram and select Validate Architecture. Visual Studio will proceed to build your projects and determine if your application actually validates against your stated (desired) architecture. If it does not, the violations will show up in the Error list window and you can start going through these dependencies and replacing the concrete implementations with contracts/interfaces. Additionally, application architects can use this functionality in conjunction with TFS to prevent code check-ins that violate an application architecture diagram.

With Visual Studio 2010, ASP.NET MVC 2 & 3 and the rich support for Dependency Injection, you can begin extracting interfaces from your concrete classes to remove the hard-dependencies in your apps, increase the maintainability of your apps. These features aren’t limited to MVC either. Many DI/IoC frameworks also work with ASP.NET WebForms as well as Windows Forms, WPF, and Silverlight. With these tools in your toolbox you too can begin enjoying the bliss that is a truly decoupled application that is easy to maintain, easy to test, easy to change and easy to replace when the next technology comes along!

Download the sample code: MvcDI.zip

For more reading on ASP.NET MVC and Dependency Injection I suggest you check out the following blogs:

http://weblogs.asp.net/scottgu/
http://hanselman.com
http://haacked.com
http://bradwilson.typepad.com/

Happy Injecting!

Recreating the MobileMe Gallery in Silverlight – Part 1 *Updated*

Originally, in Part 1 of my soon-to-be multi-part series on recreating the MobileMe Gallery in Silverlight I used a separate WCF project (under .NET 3.5) to create my Gallery Service to serve as a proxy between my Silverlight client and the Apple MobileMe service that provides MobileMe Gallery data in JSON format.

Since then, I have upgraded the project to Silverlight 4 and .NET 4 and have decided to move the service code into the Web project that hosts the Silverlight application. More importantly, I have changed the service to use the new config-free RESTful model available in WCF 4.

You can download the latest source from CodePlex here: http://silverlightmobileme.codeplex.com/SourceControl/list/changesets

Now, our web project looks like this:

Now, our service code is as simple as one file – GalleryService.cs which is as follows:
(Notice no .svc file needed anymore thanks to the WebServiceHostFactory in WCF 4)

using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace Gallery.Web.Services
{
	[ServiceContract(Namespace = "urn:silverlightmobileme.codeplex.com")]
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
	public class GalleryService
	{
		string galleryUrlFormat = ConfigurationManager.AppSettings["GalleryUrlFormat"];
		string albumUrlFormat = ConfigurationManager.AppSettings["AlbumUrlFormat"];

		[WebGet(UriTemplate = "/{username}",
				ResponseFormat = WebMessageFormat.Json,
				BodyStyle = WebMessageBodyStyle.Bare)]
		[OperationContract]
		public Stream GetGallery(string username)
		{
			// TODO: add exception-handling using WebFaultExceptions and HttpStatusCode enumeration
			var webClient = new WebClient();
			string photocastUrl = string.Format(galleryUrlFormat, username);
			return webClient.OpenRead(photocastUrl);
		}

		[WebGet(UriTemplate = "/{username}/{id}",
				ResponseFormat = WebMessageFormat.Json,
				BodyStyle = WebMessageBodyStyle.Bare)]
		[OperationContract]
		public Stream GetAlbum(string username, string id)
		{
			var webClient = new WebClient();
			string albumUrl = string.Format(albumUrlFormat, username, id);
			return webClient.OpenRead(albumUrl);
		}

	}
}

The magic of WCF 4 config-free RESTful services is handled in Global.asax.cs

using System.Web;
using System.ServiceModel.Activation;
using System.Web.Routing;
using Gallery.Web.Services;

namespace Gallery.Web
{
	public class Global : HttpApplication
	{
		public static void RegisterRoutes(RouteCollection routes)
		{
			//routes.Add("GalleryService", new Route(
			//    "GalleryService",
			//    new CustomRouteHandler("~/Services/GalleryService.svc")
			//));
			routes.Add("Default", new Route(
				"{username}",
				new CustomRouteHandler("~/Default.aspx")
			));
			RouteTable.Routes.Add(new ServiceRoute("GalleryService", new WebServiceHostFactory(), typeof(GalleryService)));
			RouteTable.Routes.Add(new ServiceRoute("ConfigService", new WebServiceHostFactory(), typeof(ConfigService)));
		}

		protected void Application_Start()
		{
			RegisterRoutes(RouteTable.Routes);
		}
	}
}

Here, after registering our main route for the gallery, we simply add two more routes (of type ServiceRoute), passing it the path we want to map to our services, then the ServiceHostFactory (which handles the config-free RESTful WCF), followed by the type of the service.

That’s it!

Now our service has nice RESTful service endpoints and there is no special WCF configuration needed and it just works.

Try out the new config-free RESTful service here: http://gallery.restazured.com/GalleryService/emily_parker

With WCF 4 config-free RESTful services, we also get handy helper pages for our service consumers to help them understand how to call our services and what type of response to expect.

Try it out here:

http://gallery.restazured.com/GalleryService/help
http://gallery.restazured.com/ConfigService/help

As you’ll see, this displays what operations are available and even provides sample responses. Now that’s RESTful!

Stay tuned for Part 2 where we’ll cover the details of the Silverlight project (now Silverlight 4) where we’ll be using MEF, MVVM and our config-free RESTful WCF services.