Archive for the ‘general stuff’ Category.

Role Based Access Control in ASP.Net MVC

Currently I am looking at access control systems, and how best to integrate them with ASP.Net MVC framework. While this framework already provides support for role based access control (RBAC), using the membership classes. I need to implement this on a legacy database, and some how integrate the old system with asp.net forms authentication. This post is about how I realised this, and acts a potential solution. If you can think of a better way, of find any devastating flaws, let me know. ;-)

The scenario is simple, we have four roles defined for the system. They are Students, Graduates, Staff and Administrators. Some staff can be graduates, (or even Students). Administrators are, of course staff! So how you model this? We already know of one bitwise trick from Michal’s post, so let us see how we can use bitwise operations to make this a reality!

First let us revise the results of the bitwise AND operations. You can check Wikipedia for full details.

1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
1 & 1 = 1

Converting these back to decimal 1001 is 9 and 0101 is 5. So 9 & 5 = 8. If we convert each of these bits to represent a role in our system, we can come up with a table like this.

Bit 1 0 (false) Student
Bit 2 0 (false) Graduate
Bit 3 0 (false) Staff
Bit 4 1 (true) Admin

So a user of the system with a role number of 8 is an Admin, but in our case, an Admin is also a member of staff, and in fact, a member of staff could also be a student or a graduate. This is where using bitwise operations can really help model such a situation. To get it working, a staff member who is a student will have bits 1 and 3 set to true, while a graduate who is also a staff member will have bits 2 and 3 set to true. We can represent these roles in decimal as User(Staff & Graduate) = 6, while User (Staff & Student) = 5. Get the picture?

Let’s look at a simple real world example. First we have a User class, with a Role property of the type int. The reason we use an integer, is that is can be easily stored in the database.

    1     public class User {

    2 

    3         public string Name { get; set; }

    4         public int Role { get; set; }

    5         public bool IsInRole(Role role) {

    6             //todo

    7             return false;

    8         }

    9     }

We also need to create an enumeration, with a Flags attribute. The flags attribute tells the compiler that this enumeration can be treated as a bit field. We then define a value for each role. The reason for using exponents of 2 should become clearer later.

    1     [Flags]

    2     public enum Role {

    3         Student = 1,    // 0001

    4         Employer = 2,   // 0010

    5         Staff = 4,      // 0100

    6         Admin = 8       // 1000

    7     }

The menu of our website needs to be generated depending on the user role. The menu selection code below should generate the correct menu depending on the user role.

    1     <div class="LeftMenu"> 

    2 

    3         <% if (user.IsInRole(Role.Student)) %>

    4             <% Html.RenderPartial("StudentMenu"); %>

    5 

    6         <% if (user.IsInRole(Role.Graduate)) %>

    7             <% Html.RenderPartial("GraduateMenu"); %>

    8 

    9         <% if (user.IsInRole(Role.Staff)) %>

   10             <% Html.RenderPartial("StaffMenu"); %>

   11 

   12         <% if (user.IsInRole(Role.Admin)) %>

   13             <% Html.RenderPartial("AdminMenu"); %>

   14 

   15     </div>

Ok, so let see where the magic happens! If we AND (&) the user assigned role, with the role required, and we compare this result to the role required, we can determine if a user is in the role. Summarised, the end result of the AND operation needs to equal that of the role required. In user class we have the method:

    1         public bool IsInRole(Role role) {

    2             Role userRole = (Role)this.Role;

    3             return ((userRole & role) == role);

    4         }

Looking at some binary examples, we can see how it works. In the first example, an admin user wants accesses a graduate item.

Role Required Staff(4) 0 1 0 0
User Role Admin (8) 1 0 0 0
Result of & Access Denied (0) 0 0 0 0


It is clear that we have a problem here, because we said that admin could be both staff, and staff may also be graduates. What we need to do is add up the roles, so that this user will access both admin and staff content. Assigning the user the role of Admin and Staff is easy. All we do is:

    1             User user = new User();

    2             user.Role = (int)Role.Staff;

    3             user.Role += (int) Role.Admin;

And the resulting table is:

Role Required Staff(4) 0 1 0 0
User Role Admin + Staff (12) 1 1 0 0
Result of & Access Granted (4) 0 1 0 0

Now we can easily draw our menu depending on the roles assigned to a user. Adding or removing roles for a user is also easy, just add it or subtract it. I wrote a little project to go with this so you can test it our your self. Thanks to Michi for introducing this, and Dan for helping work it out!

Download the Roles sample project You’ll need to use nUnit to test it.

FluentNhibernate and Stored Procedures

I am evaluating FluentNHibernate (FNH), to see if it is suitable for a project I am working on. Disappointingly, FNH does not support Store procedures of the box. Of course, FNH is under the BSD licence, so I am sure those who are confident enough can implement this for the rest of us! This post will show how I got FNH to work with stored procedures, and can hopefully be followed as a working example.

FNH extends NHibernate, and automagically generates XML mapping files for your objects. Unfortunately, to get stored procedures to work, you need to take a step backwards, and create good old fashioned hbm.xml files, doing the mappings manually.

Firstly , let us look at the results of the stored procedure that we want to map.

ID enDescription cyDescription IsActive
1 Swansea Abertawe True
2 Cardiff Caerdydd True
3 Newport Cas Newydd False

The class that will use this data is called lookup.

The code for this class is:

    1 namespace Entities {

    2     public class Lookup  {

    3         public virtual int Id { get; set; }

    4         public virtual string EnDescription { get; set; }

    5         public virtual string CyDescription { get; set; }

    6         public virtual bool IsActive { get; set; }

    7     }

    8 }

 
This object will be used to populate a simple drop down list, so that a user can select their county.

When I started using FluentHNibernate, I wanted to totally avoid using XML mappings, so I skipped chapters 3 and 6 of Hibernate in Action. My first mistake! So for those attempting this, it may be worth your while understanding Hibernate mappings before you proceed. (You may also ask why I have the Java Book and my code is in C#, that is because I am quite used to working in different programming languages, so those who prefer examples in .Net examples check NHibernate in Action.)

Let’s move on to creating the mapping file.

IMPORTANT: When you add the mapping file to your project, make sure you set the Build Action to Embedded Resource!

I have created a Lookup.hbm.xml file, and the source is below:

    1 <?xml version="1.0" encoding="utf-8" ?>

    2 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"

    3                    namespace="Entities">

    4     <class name="Lookup" table="dbo.sp_GetLookups" >

    5         <id name="Id" column="Id">

    6             <generator class="native" />

    7         </id>

    8         <property name="EnDescription" column="enDescription" />

    9         <property name="CyDescription" column="cyDescription" />

   10         <property name="IsActive" column="IsActive" />

   11         <loader query-ref="dbo.sp_GetLookups"/>

   12     </class>

   13 

   14     <sql-query name="dbo.sp_GetLookups" >

   15         <return alias="dbo.sp_GetLookups" class="Lookup">

   16                 <return-property name="Id" column="Id"/>

   17                 <return-property name="EnDescription" column="enDescription"/>

   18                 <return-property name="CyDescription" column="cyDescription"/>

   19                 <return-property name="IsActive" column="IsActive"/>

   20         </return>

   21         exec dbo.sp_GetLookups

   22     </sql-query>

   23 </hibernate-mapping>

 

To put it quite simply, lines 5 to 13 map my Lookup class to the columns in the stored procedure, while lines 16 to 20 map the results from the stored procedure my lookup class. Line 22 names the stored procedure. I am not sure if this is the best way to achieve the mappings, so any feedback would be appreciated.

Once your object is nicely mapped, you then need to update your fluent configuration. All you need to do is tell FNH to load hbmMappings from the current assembly. See the snippet below:

   1    .Mappings(m => {

   2            m.HbmMappings.AddFromAssembly(Assembly.GetExecutingAssembly());

   3            m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());

   4     })

 

To retrieve the list of lookups, I do the following, which populates my results variable with a list of all my lookups.

    1    var sessionfactory = CreateSessionFactory();

    2    var session = sessionfactory.OpenSession();

    3    var results = session.GetNamedQuery("dbo.sp_GetLookups").List();

 

And that is it, the results variable now contains the list of lookups that I can use to populate my list control.

Looking for the perfect job? Looking for the best developers?

careersstackoverflow
As an active user of Stackoverflow I came across their new career service. It’s brand new and their vision is to find the perfect employer for each developer. Pretty good idea I think. STO has a lot of bright brains, which can be a huge profit for corporations looking for great staff.

Amongst other job platforms, it stands out by providing developer specific details such as First computer, Favorite technologies, Likes, Dislikes, etc. Currently they’re offering a 3 year membership for only USD29.00. Once inside, you sit back, drink tea and wait.

Since their launch Stackoverflow provided me a lot of answers to my questions, which no other site achieved so far. That’s why it’s time to give back to them. I decided to subscribe for the 3yr membership.

Want to hire me?
http://careers.stackoverflow.com/michal

Testing code changes, bugfixes, new features, …

When you implement a new feature somewhere, when you change just some bits of your code, when you fix a bug, or you just change a common text in an app… What do you do afterwards? Do you really check the result or do you trust yourself that it works fine 100%. It is an interesting thing to talk about… Continue reading ‘Testing code changes, bugfixes, new features, …’ »

Flex Style Introspection

If you have ever used the Flex introspection method describeType(), you certainly have noticed it doesn’t output any style metadata. The only way I found so far was to instantiate the UIComponent type I’m looking at and call the function regenerateStyleCache(false). The entire list of available styles is then accessible via the properties inheritingStyles and nonInheritingStyles. Generating the style cache is computation-intensive so like most reflection and introspection operations make effective use of it :)

Some code example after the jump… Continue reading ‘Flex Style Introspection’ »

Publishing Flex applications to Google Code SVN repository

I’ve been struggling with this one a couple of times, so I thought I should share how I solved it.

Problem:
You are hosting or contributing to an open-source project on code.google.com using SVN as source control.
You would like share Flex applications (and View Source) by accessing their public SVN URL.
Applications pages (HTML) show raw text.

Solution:
Make sure you set the SVN property svn:mime-type for each file:

  • *.html: “text/html”
  • *.css: “text/css”
  • *.zip, *.swf, *.png: “application/octet-stream”

bit.ly, tinyurl & co. Does the planet really needs short URLs?

Over the last couple of years I was wondering almost everyday why the hell someone would want to use a short URL. Although I consider myself as a geek, freak & nerd I’ve never had the desire to create a short URL. Why? Maybe it’s laziness :) Maybe I am not web 2.0 enough…

However, today I’ve found someone (no one less than Jeff Atwood from Codinghorror) who seems to share the same thoughts though. He’s even calling them the web destroyers and writes about how Twitter made them more popular than ever. Enjoy the read!

Ruby Development Toolkit for Eclipse IDE | RDT

I’ve been looking into Ruby and Rails recently since I deployed Redmine at my company to support our software development projects. For those who don’t know Redmine, this is a great piece of open-source software, offering a complete web collaborative solution for project management including source control, wiki, issues tracking, ldap authentication…

Today, I just found out there is a Ruby Development Toolkit (RDT) plugin for my favourite IDE… Eclipse! Sweet! The toolkit is downloadable via Eclipse Software Update, the remote site URL is:

http://updatesite.rubypeople.org/release

Features supported are syntax highlighting, on the fly syntax check, graphical outline, Test::Unit view/runner, Ruby application launching, content assist, source formatter, Ruby debugging, Type Hierarchy view, Ruby specific Search, Refactoring, and much, much more…

Web Dev Bros with WordPress 2.7 now

We upgraded the blog to the latest version and added some new widgets. The site was down one day because we forgot to upload a missing file … Sorry for that.

We are trying to do add some posts the next days to get this up and running again. I want to welcome Julien and we can’t wait to see a post from him :-)

Methods for hiding/obfuscating emails in your website

Hiding your emails on your website can be very tricky and the method should be chosen wisely. Yeah, its our war against email harvesters! Just now i have read the outcome of an interesting study made by Silvan Mühlemann. In his research he used nine different methods to obfuscate the email on his page. He created an email address for each method and was keeping track of the incoming spam for 1.5! years. Here is the outcome:

obfuscation methods
(source: Nine ways to obfuscate e-mail addresses compared)

Amazing! The simplest methods using CSS had the best results. No Spam at all. There is just one question: How long will it take for the harvesters to adapt their algorithms to this research results?

(If you’re interested to see the detailed implementation of those methods just check the original article. I have skipped it.)