Extending ASP.Net Memberships with Access Points – Part 1

The beauty of ASP.Net is that some of the core framework components can be replaced by custom implementations by writing the appropriate Provider classes by using the Provider Model.

In the following series of article, I will show a customer implementation of the ASP.Net Membership Providers to extend the Memberships.

Reason of extension

The current Membership implementation is role-based i.e. the user should be in a role to be able to access a feature of your application.

For example, if we have a page with some UI elements whose access depends on role assigned to the user, we can imagine to write code as below:

bool has_access_role1 = this.Page.User.IsInRole("Role1");
bool has_access_role2 = this.Page.User.IsInRole("Role2");

if(has_access_role1) { 
    // do something with Role 1...
}

if(has_access_role2){
    // do something with Role 2...
}

There are a couple of important but subtle assumptions being made in this code snippet:

  • There is an assumption of knowing all the Roles, their names & behavior in the application
  • The implementation and responsibilities of that Role are baked into the application and if there is any future change in this, the code will also need to change

While this is acceptable in most scenarios, I would prefer having another level of abstraction which will remove some of these assumptions and code dependencies.

Introducing Access Points

The implementation I am showing below called as “Access Points” provides this abstraction and is a concept I have been working with in some of my other projects.

  • Each protected element is associated with a single entity called “Access Point” which has is a simple boolean (TRUE|FALSE)
  • Access Points are assigned to a Role or a User
  • When an Access Point is assigned to a Role, the User get assigned to that Access Point by virtue of being assigned to the Role
  • When an Access Point is assigned to a User, it an additional permission which can be set per-user basis

With this implementation, we should be able to re-write the above code sample as below:

var has_access_point1 = (this.Page.User as IAccessPointAware)
                .HasAccessPoint("AccessPoint1");
var has_access_point2 = (this.Page.User as IAccessPointAware)
                .HasAccessPoint("AccessPoint2");

if(has_access_point1){
    // do something...
}

if(has_access_point2){
    // do something more...
}

Some of the advantages this mechanism gives us are:

  • The application has a finite set of control points, which is governed by the developers of the application
  • The Application Administrators can create roles for the application and assign Access Points to that role as needed
  • There is no dependency between the code written in the application and the implementation of the roles for the application
  • With this, the Application Administrators can add/update/delete roles as needed without any impact on the application
  • If a single user needs a permission or access to a single element, the Application Administrator can assign that Access Point to the single user

Next steps

If this something that interests you, please follow on to the next part this series which covers:

  • Part 1 – an introduction to the Access Point concept
  • Part 2 – database changes needed to enable Access Points
  • Part 3 – code to enhance the ASP.Net Memberships and Roles
  • Part 4 – some common usage patterns and advantages
  • Part 5 – a simple UI implementation to show use of Access Points
  • Part 6 – an admin console to manage Access Points

Happy Coding!

References

4GuysFromRolla 2005, A look at ASP.Net 2.0’s Provider Modelhttp://www.4guysfromrolla.com/articles/101905-1.aspx

Rob Howard, Provider Model Design Pattern and Specificationhttp://msdn.microsoft.com/en-us/library/ms972319.aspx

Enabling DI/IoC for noobs – Part 1

The powers that be agree that Dependency Injection (DI) & Inversion of Control (IoC) patterns help applications become more component-based, easier to maintain & better designed and are open to unit testing & mocking.

But how does one really use DI/IoC in their application to get the advantages aforementioned?

The following series of article provides a step-by-step guide to structure code for working with DI & then implementing IoC for noob programmers.

This article is the first of this series & provides an introduction to DI.

What is Dependency Injection?

Dependency Injection (DI) is a mechanism to inject dependencies into code such that the piece of code can consume the injected dependency without having knowledge of the construction or lifetime of the injected dependency.
In other words, DI in object-oriented computer programming is a technique for supplying external dependency (ie. a reference) to a software component – that is, indicating to a part of program which other parts it can use (Wikipedia, 2010)

Let us understand the definition by breaking down the definition into smaller parts.

What is a dependency?

Consider the following lines of code:

public class AccountController{

    private readonly IAccountRepository _repository;

    public AccountController (
        IAccountRepository repository ) {

        if(repository == null)
            throw new ArgumentNullException("repository");

        _repository = repository;
    }

    public ActionResult Login( string userName,
        string password ){

        var isLoggedIn = _repository.DoLogin(userName,
                                 password);
        return isLoggedIn
            ? View("AccountInfo")
            : View("Login");

    }
}

In the above sample, we can say that the class AccountController has a dependency on a type implementing the IAccountRepository interface ie. for the AccountController to perform its functionality, it would need a valid instance of IAccounRepository to be passed.

One key aspect to note is that we are not passing the concrete class of IAccountRepository, but instead passing in an interface. The advantage of doing this is the AccountController is not dependent on the concrete class, but only an implementation of IAccountRepository. In other words, the AccountController has a dependency on the IAccountRepository implementation.

What is Injection?

In the code sample above, we now know that the AccountController has a dependency on the IAccountRepository. The manner in which we can provide this dependency is known as injection.

One of the simplest ways to do this is:

var account_controller = new AccountController(
       new WindowsAccountRepository());

We could have a WindowsAccountRepository implemented as:

public class WindowsAccountRepository
    : IAccountRepository
{
    public bool DoLogin(
        string userName,
        string password
    ){
        // some code to do login by checking against the Active Directory
    }
}

But then at a later date, if you decided that you would like to have a custom implementation for account management & want to store the information in a database, all you would need to do is create a concrete class for your repository implementing the IAccountRepository & inject that into the constructor of the AccountController like below:

public class CustomAccountRepository
    : IAccountRepository
{
    public bool DoLogin(
        string userName,
        string password
    ){
      // some code to validate against a database
    }
}

Consuming this new class would look like:

var account_controller =
    new AccountController(
        new CustomerAccountRepository()
    );

This way, the complexity of the implementation of IAccountRepository is abstracted away from AccountController. But, AccountController is able to use the behavior exposed via the interface while the consumer of the AccountController is free to inject a concrete implementation of IAccountRepository.

Wrap up

In this first article, we defined dependency injection & what it means using a simple code sample. We have seen how we can replace the dependency by injecting a concrete implementation at the time of consumption.

In the next article, we will look at writing unit tests on the code we have just written & explore the benefits of DI in the context of unit testing.

Comments & suggestion always welcome.

References:

Wikipedia 2010, Dependency Injection – http://en.wikipedia.org/wiki/Dependency_injection

An attempt at Enum.TryParse

It is well known fact that Enum.TryParse does not exist in .net 3.5 although it is available in 4.0

There have been some previous implementations already made here, here and here. I thought I should add my $0.02 into the mix & put out my own implementation, so here goes:

Note: line breaks added for clarity & to fit the layout

public static class Extensions{
    public static bool TryParse<T>(this T enum_class,
         string value, out T result){
         return Extensions.TryParse(enumClass, value, true, 
                 out result);
    }
    public static bool TryParse<T>(this T enum_class,
        string value,
        bool ignoreCase, out T result)
        where T : struct
        // cannot constraint by System.Enum type
    {
        result = default(T);
        var is_converted = false;

        var is_valid_value_for_conversion = new Func<T, 
             object, bool, bool>[]{
            (e, v, i) => e.GetType().IsEnum,
            (e, v, i) => v != null,
            (e, v, i) => e.GetType().IsEnum,
            (e, v, i) => Enum.GetNames(e.GetType()).Any(
                n => String.Compare(n, v.ToString(), i) == 0
                || (v.ToString().Contains(",") 
                     && 
                     v.ToString().ToLower()
                     .Contains(n.ToLower())))
                || Enum.IsDefined(e.GetType(), v)
        };

        if(is_valid_value_for_conversion.All(
             rule => rule(enum_type, value, ignoreCase))){
                    result = (T)Enum.Parse(typeof(T), 
                               value.ToString(), ignoreCase);
                    is_converted = true;
       }
      return is_converted;
} }

This code currently can convert the following:

Enum Converted from

enum SomeEnum { A, B, C }

“A” or “a”

enum SomeEnum : int 
{ A = 1, B = 2, C = 3 }

“A” or “a” or 1

[Flags]
enum SomeEnum {
  A = 1, B = 2, C = 4
}

“A” or “a” or “A, B” or “A, b” or “a, B” or “a, b”, 1

Drop a note if you find this useful.

WebsiteManager v1.0 Released!

Ladies & Gentlemen, presenting my first open-source application called WebsiteManager – finally released & ready for you good folks to use!

This version (v1.0) provides a UI to manage the ASP.Net Memberships & roles via a web application using ASP.Net MVC 3.5 (although you could use it on ASP.Net MVC 2.0 also)

I have a couple of useful ideas which I plan to implement in this application during the course of the new few releases.

So hang tight 🙂

Please feel free to download the latest bits from CodePlex, use it as you see fit. I would truly appreciate some feedback on this effort & open to any new ideas you would like to see put into the future releases.

Again – CodePlex is the place for all this information.

Have fun!

Referencing external files in MVC Views

Typically, new developers to ASP.Net MVC get stumped with having to deal with one important fact:  Page.ResolveUrl(...); is missing!!!

Don’t worry or fret – the new way of doing this is:

Url.Content(...);

Some sample usage is as below:

Resolving images:

<img src="<%= Url.Content("~/content/images/myImage.gif") %>" alt="My image" title="My image" />

Resolving JavaScript files:

<script language="javascript" type="text\javascript" src="<%= Url.Content("~/scripts/myscript.js") %>"></script>

Simple as that.

When you refer stylesheet files in your *.Master page, this link is directly reference without needing to use the Url helper as shown above.

So, you can continue refering stylesheet files like:

<link rel="stylesheet" type="text\css" media="screen" href="../content/site.css" />

The MVC framework will resolve the path correctly at run-time.

Hmm.

ASP.Net MVC & jQuery – utopia!!!

I finally got the chance to start working on ASP.Net MVC with jQuery & Linq.

My last project was based on the now “old” .Net 2.0  & we went with a complete MS technology stack including their version of AJAX. Adding third party controls to the mix didnot help & only added to the overall complexity of the system. 

MS Ajax – is surely past its sell by date.

When this library was first put out, I was truly excited & hoped it would be all it promised to be. For sometime, I really enjoyed it. But then once I got jQuery-ed, its bye-bye Ms. Ajax. Inspite of all her glitz & glamour, I lost my heart to the pure simplicity of jQuery. 

I have never been a big believer of third party controls – regardless of the claims of the component supporters.

True they save you a load of upfront effort & look cool. Unfortunately, in my experience, the project starts degrading in performance, maintainability & testability the minute a third party control starts appearing in your codebase.

Needless to say, after all that – MVC, jQuery & Linq – utopia!!!