Microsoft MVC5 + ASP.NET Identity with Telerik OpenAccess Awesomeness

Microsoft’s new membership system ASP.NET Identity is (IMHO) absolutely fantastic! The system itself comes installed as the default provider in Visual Studio 2013 for ASP.NET templates and can be downloaded for use within Visual Studio 2012.

ASP.NET Identity is the next step in the evolution to what was previously known as the SimpleMembership and Membership providers. Previous versions have been extremely brittle; this new approach simplifies and segments the membership provider in such a way that it makes it incredibly easy to plug-in and remove the components as you require and more importantly simplifies development when implementing a separation of concerns in a Service Oriented Architecture. Anyone who has attempted to achieve this with WCF and the previous membership providers will know the difficulties and lack of clear process through which to accomplish this. Another major benefit is that the framework implements all the .NET Async goodness by default. While you could always create your own Async wrappers in the older providers it makes things easier to see this functionality implemented for you.

The problems with the original ASP.NET Membership provider were:

  1. Designed for SQL Server and you can’t change it. You can add profile information, but the additional data is packed into a different table, which makes it difficult to access by any means except through the Profile Provider API.

  2. The provider system enables you to change the backing data store, but the system is designed around assumptions appropriate for a relational database.

  3. Since the log-in/log-out functionality is based on Forms Authentication, the membership system can’t use OWIN.

As the Introduction to ASP.NET identity article goes on to say

Simple Membership did make it easier to customize user profile information, but it still shares the other problems with ASP.NET Membership, and it has some limitations such as:

  • It was hard to persist membership system data in a non-relational store.
  • You can’t use it with OWIN.
  • It doesn’t work well with existing ASP.NET Membership providers, and it’s not extensible.

So, how is ASP.NET Identity different? Well…..

1. Storage backend is completely separate

Complete and total separation of the storage mechanism used within the provider. For example implement your own storage back-end but use something other than the entity framework? Or you want to use some type of NoSQL implementation (such as Azure Tables) or even just an Xml file? Well all you need to do¹ is implement the IUser and the IUserStore interfaces, inject it into your UserManager and you’ve got your own custom storage provider.

Example.

protected void CreateUserManager()
{
    //Create a new user manager based on your User model, inject your UserStore and finally your ORM context
    UserManager<AspNetUser> Manager = new UserManager<AspNetUser>(new OpenAccessUserStore(new EntitiesModel()));

    //Now inject the validator
    Manager.UserValidator = new UserValidator<AspNetUser>(Manager)
    {
        AllowOnlyAlphanumericUserNames = false
    };

    //And set a property so you can use the UserManager when required
    this.UserManager = Manager;
}

//Public property to access your UserManager instance.
public UserManager<AspNetUser> UserManager { get; private set; }

Note that all you need to do to create a basic IUserStore and IUser is implement this.

public interface IUserStore<TUser> : System.IDisposable where TUser : Microsoft.AspNet.Identity.IUser
{
    System.Threading.Tasks.Task CreateAsync(TUser user);
    System.Threading.Tasks.Task UpdateAsync(TUser user);
    System.Threading.Tasks.Task DeleteAsync(TUser user);
    System.Threading.Tasks.Task<TUser> FindByIdAsync(string userId);
    System.Threading.Tasks.Task<TUser> FindByNameAsync(string userName);
}

AND THIS

public interface IUser
{
    string Id { get; }
    string UserName { get; set; }
}

2. General decoupling

Previously the provider implementation was extremely closely coupled between its various ‘bits’. The result would often cause confusion about which methods to invoke and under what circumstances (at least for me). Sometimes all you’d want to do is authenticate, sometimes you want to authenticate and sign in and sometimes you want to go straight to the database and just retrieve some bit of User info. Because of this change of implementation it’s been significantly easier to build a project using this provider and integrate it with WCF cleanly. In part this is because it’s now much easier to say, “Give me all claims for this user.” then “Authenticate the following claims.”. They are completely different subsystems and have no direct inter-dependencies.

3. Unit Testing

Clear interface based contracts between the various components of the framework make dependency injection and unit testing much simpler.

4. Claims based

While roles still exist within ASP.NET Identity the emphasis to a claims based authentication seams clear. Claims are useful because they abstract the individual elements of identity and access control into two parts. Unless you’ve got a reason not to, I suggest it makes sense to use claims rather than roles.


Finally I’ve gone ahead and built a generic Visual Studio project template extension which shows how to integrate MVC5 with ASP.NET Identity behind WCF webservices and utilizing Telerik OpenAccess ORM for the storage provider (Because OpenAccess kicks ass…) and deployed it to the Visual Studio Gallery for everyone to use or if you prefer just a straight download of the files.

The project itself demonstrates a number of things including:

  1. How to create a NetTCP WCF service without autogenerated proxy classes.
  2. How to use ASP.NET Identity in a WCF service
  3. How to use a different ORM as an alternative to the entity framework
  4. How to include System.ComponentModel.DataAnnotations in a portable class library for your Views.
    1. Which allows the ability to use them across your MVC, WCF, Windows Phone and Xamarin applications.

Hopefully someone else will find the template and source code useful!


  1. It’s not quite that simple (you might need to implement between 1 and like 10,000,000 interfaces), but almost!

Always use ChannelFactory when referencing WCF services (particularly for Azure)

Given the indeterminate nature of the IP addresses of Azure web roles (There are a number of exceptions to this but in general) you end up in a real pickle if you you use the Service Reference functionality built into Visual Studio that most of us regularly do.

(This thing)

Image

Truthfully, the way the proxy service references have always worked had its flaws despite its convenience.

The problem boils down to two things. First, if you’re correctly using WCF services you should be binding to DataContracts and Interfaces rather than any concrete implementations anyway. Secondly, you’re stuck with hard-coded values that live in your web.config, with what is inherently dynamic and often not known at compile time (ip addresses).

So how do you solve it?

Remarkably simply, it takes the form of the channel factory and provided you have both your datacontracts and your service interfaces referenced you can then do this.

Image

Download the example.

 

Can’t start the Windows Phone Emulator – The Windows Phone Emulator couldn’t start because the hypervisor isn’t running.

So I figured I’d document my first experiences with the Windows Phone 8 SDK.

First issue I ran into was an error “The Windows Phone Emulator couldn’t start because the hypervisor isn’t running.”

Image

While the information shown in the “more information” link helps its a bit verbose.

Basically enable “Execute disable bit” and “Intel Virtualization Technology” in the equivalent BIOS settings of your motherboard.

WP_20130927_001

and ensure you have the “Hyper-V” features turned on

windowsfeatures

That’s it. Should be working now!

Concatenating values with commas in arbitrary collection

On numerous occasions I have needed to concatenate a property of an entity in a collection with a comma and have typically resulted in code that requires a loop for each entity along with a removal of the extra comma once the loop is completed.

This has always been a pain and plain ugly

Today I stumbled across a new overload for String.Join (String.Join Method (String, IEnumerable<String>)) which is only available after .NET 4.0 .

This allowed me to come up with the following extension.

    
public static string ConcateWith(this IEnumerable<T> values, 
                                      Func<T, string> property, 
                                      string separator) 
{
    return string.Join(separator, values.Select(o => property(o)));
}

Nice eh?

Lines of code, per developer, per day

I have recently embarked on my largest ever development project. I am roughly 45,000 lines of code into the project (Only counting C#) and am expecting it to hit at least 50,000 by the time its completed.

At the beginning of each Monday I have logged and plotted the amount of lines of C# code completed in the prior week. I have only plotted C# lines because the tool I was using unfortunately only supported this. I have since upgraded to a program called Microsoft Line Of Code Counter and this provides a much more comprehensive report (and its free).

Although the project isn’t finished (And I will update once it is) a couple of interesting results have already surfaced.

  1. It appears that an individual programmers peak output on a completely blank canvas is still limited to roughly 400 lines of code per day.
  2. There appear to be clear peaks and troughs where there are productivity bursts and lulls.
  3. Its unlikely that many programmers could output significantly more than 100,000 lines of code per year.
  4. There gets a point where you’re no longer contributing significant amounts of code in a project but rather fixing what is already there.

However obviously all of this assumes that my work is representative of most programmers, that the type of work is similar (in this case developing a very straightforward business web app – I’m sure you wouldn’t get the same results in one of Microsoft’s or Google’s labs) and as I said above doesn’t take into account the fact that this only counts pure C# lines and none of the other files that were a significant part of this project (aspx, js, asax, css and others).

Here is current chart for anyone interested

Image

Image

(Note that roughly the first 3-4 weeks of this project were only on a part time basis)