Posts tagged ASP.NET MVC

Status of SimpleMembership.Mvc3 and SimpleMembership.Mvc3.Sample

I have received a couple of questions and requests over the past 6 months or so regarding my plans to update both the SimpleMembership.Mvc3 and SimpleMembership.Mvc3.Sample packages.

In short, I’m planning on updating these but I just haven’t gotten to it yet. I’ve been very busy lately with some other projects such as Expansive and my C# wrapper for the DNSimple REST API.

However, in preparation for these changes I have started a Trello board here: https://trello.com/board/simplemembership/4f23419c0fa7e50d34585d9e

I’m using this to track requests I have received and to communicate the status of the features that have been requested.

Please feel free to comment on them or vote or request new features.

However, these being open source projects on GitHub, please also feel free to fork them, add your desired features and submit a pull request to me to merge your changes back into the trunk.

Both projects can be found on GitHub using the following links:

I am going to try to get these changes done soon, but I just haven’t been able to dedicate any time to them yet.

In the meantime, thanks again for your interest, feedback, questions and requests regarding SimpleMembership.

Stay tuned…

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!

Create your own branded url-shortener in under 10 minutes using ASP.NET MVC 2

Overview

These days, URL shortener services like bit.ly are a dime a dozen. However, the latest craze are branded, shortened URLs like amzn.to instead of amazon.com, nyti.ms instead of nytimes.com, tcrn.ch instead of techcrunch.com, huff.to instead of huffingtonpost.com.  You’ve probably seen URLs like these floating around Twitter, Facebook, IM and even email. These abbreviated domains offer the same benefits of a short URL provided by a service like bit.ly (ideal for use on Twitter, etc.) without sacrificing the branded experience and marketing that is achieved by using a “full-size” URL. They are the “compact car” of URLs and they are your friend!

Hence the reason for new services like bitly.Pro. In case your unfamiliar, bitly.Pro is a new service offered by bit.ly that allows companies and individuals to brand their shortened URLs using their own abbreviated domains. Amazon.com already uses http://amzn.to. The New York Times uses http://nyti.ms. Many other companies are using bitly.Pro as well. You may already have your very own abbreviated domain that you’d like to use to brand your shortened urls. If not, go get one. So, like me, you figure you’ll head on over to http://bitly.pro/signup to sign up for the free beta only to find out that the beta is closed to new users at this time. (Update: bitly.Pro beta has re-opened and you can signup here: http://bit.ly/a/pro_request).

But wait…before you begin cursing bit.ly about their closed beta, allow me to present a quick solution that still allows you to brand your shortened links and track traffic to your branded service. It won’t give you the analytics regarding how your content is begin distributed across Twitter, Facebook, etc. (although you could build that in fairly easily), but for someone who just wants a simple branded url shortener solution, it will fit the bill.

So, without further ado, here’s the simple ASP.NET MVC-based solution that provides a simple bitly.Pro-like solution of your very own. Best of all, you can get it going in under 10 minutes. Of course, you could build the same solution entirely with javascript and an html page, but where’s the fun in that?

Getting Started

The easiest way to get started is to head over to http://www.asp.net/ and use the Web Platform Installer to install Visual Web Developer 2010 and ASP.NET MVC 2.

Once you’ve got these installed, fire up VS2010 and add a new “ASP.NET MVC2 Empty Web Application.”

You should end up with something that looks like this:

The Controller

The first thing we want to do is setup a controller to handle our requests, so right-click the Controllers directory in the Solution Explorer and select Add > Controller.

We’ll name ours “HomeController” and, since we won’t be doing anything with an actual model, we’ll leave the box unchecked that prompts us to create actions methods for Create, Update and Delete scenarios.

Our HomeController is going to be very simple and will look like this:

using System.Web.Mvc;

namespace bitlyProSimple.Controllers
{
	[HandleError]
	public class HomeController : Controller
	{
		public ActionResult Index(string linkid)
		{
			Response.StatusCode = 302;
			Response.RedirectLocation = (string.IsNullOrWhiteSpace(linkid)
								 ? "http://anderly.com"
								 : string.Format("http://bit.ly/{0}", linkid));
			return new ContentResult();
		}

	}
}

Our controller is going to accept a string (the linkid) and then contstruct a 302 redirect to bit.ly to finish the job. This allows us to simply use the bit.ly analytics when you have a bit.ly account.

As you can see, we are using bit.ly, but you could very well use any other URL shortener service. Essentially, what we’ll be doing is mapping requests that match the format http://[yourdomain]/[linkid] to our HomeController which will accept the linkid as a parameter and then prepare to forward our request to bit.ly. So in my case, my abbreviated domain is http://ander.ly. So, I’ll be mapping any requests that match the http://ander.ly/[linkid] format to be forwarded to http://bit.ly/[linkid].

In case there isn’t a link id, we will simply redirect to the blog home page.

Wrapping Up

Last but not least, we need to head on over to Global.asax.cs to setup our Routes and we’ll be done.

Open up Global.asax.cs and replace the default route of:

{controller}/{action}/{id}

with

{linkid}

That’s it!

Fire up the solution and test it out for yourself. Don’t forget to bookmark the location of this post: http://ander.ly/bGSr9K

Now any requests that come in that match the format http://ander.ly/[linkid] will be sent to our HomeController which will extract the linkid and construct a new bit.ly URL of the same format and do a simple redirect for the user.

With this solution, we can simply use the existing bit.ly URL shortener service without having to roll our own and we can simply replace bit.ly in any shortened URLs with our very own branded abbreviated domain.

Now you too can start branding the links you share.

Let the shameless self-promotion begin!

Source Code

bitlyProSimple.zip