Unity.MVC3

Sat Mar 10 2012 by MarkP

As the final part of the upgrade of this site to MVC 3, I decided to change the IoC container from Castle Windsor to Unity. I have been using Unity is many projects recently so decided to use the knowledge gained to replace the container and also utilise the IDependencyResolver interface which replaces the Common Service locator class, which is new in MVC 3.

There is an interesting project on codeplex called Unity.MVC3 which simplifies the process further and also provides a simple way of disposing of objects per HttpRequest using the HierarchicalLifetimeManager(), which is especially useful when using ORMS such as Entity Framework where you need to dispose of the context object, if this is being injected into your classes.

The code now is greatly simplified for my implementation as follows:

  1. IUnityContainer container = UnityRegistrar.Register();
  2. DependencyResolver.SetResolver(new UnityDependencyResolver(container));

The RegisterControllers extension method is specific to Unity.MVC3.

  1. public class UnityRegistrar
  2.     {
  3. public static IUnityContainer Register()
  4.         {
  5. var container = new UnityContainer();
  6. container.RegisterType<IMailHandler, SmtpMailHandler>();
  7. container.RegisterType<IBlogCreator<XContainer>, XmlBlogCreator>();
  8. container.RegisterType<IResourceRepository, ResourceRepository>();
  9. container.RegisterType<IUserRepository, UserRepository>();
  10.             container.RegisterControllers();
  11. return container;
  12.         }
  13.     }

Downloads
Unity.MVC3
Unity IoC Version 2.1

Tags: Unity   IoC   MVC   Post Comment

Single Sign-on using Access Control Services 2

Sat Dec 17 2011 by MarkP

On a recent project I have been tasked with defining the architecture for a Single Sign-on (SSO) solution in a Windows Azure cloud based environment. In you are not aware a Single Sign-on solution is defined as a property of access control of multiple related, but independent software systems. With this property a user logs in once and gains access to all systems without being prompted to log in again at each of them. i.e. if an user has a Google account they can use this account to access other systems without having to register.

Windows Azure has built in functionality for SSO, using Access Control Services 2.0 (ACS). This supports common Identity Providers such as Facebook, Google and Windows Live as well as supporting business services such as ADFS and various protocols such as OpenId and OAuth. Microsoft have simplified the integration of this functionality using Windows Identity Foundation (WIF) via a tokenized authentication service and claims based identification of an user.

Micrsoft in general have made the process of using SSO a lot simpler via ACS, if you wish to allow access to your site via third party Identity Providers. I have seen sites already that only allow access by this means - accessing user information only provided by the token supplied. The real interesting scenario comes when you wish to integrate SSO with your own registration process to be use on multiple sites, in essence creating your own Identity Provider. To be able to do you need to have a good understanding of creating and validating SAML(Security Assertions Markup Language - a XML representation of claims) tokens as well as X509 certificates. WIF helps to make this process easier but there is still quite a learning curve in relation to understanding how all these technologies fit together.

I am currently at the stage of having a proof of concept working, built around MVC 3 and Entity Framework 4.3, being able to successfully post and validate SAML tokens across various sites, authenticating an user accessing the site via a custom registration process or a third party identity provider. There are still issues to resolve and some other technical and business challenges but in general I can see of lot of benefits using this approach, and once complete will negate to see to create seperate membership processes for each new application requiring authentication; the applications will only need to validate the token and parse the claims information, if required.

CQRS - whats all the fuss about?

Sun Aug 21 2011 by MarkP

If you haven't heard of CQRS - where have you been for the last year to six months? In the .NET world this pattern has been the lastest buzzword that will solve a multitude of issues (apparently) in relation to architectural and software design that has grown out of n-tier architecture. Its premise is to simplify the complexity inherent now in most systems based on this architecture especially when changes are required that tend to impact code in all the various layers. It also faciliates best practice (Single Responsibility Principle) and should lead to better performing systems.

CQRS - is an acronym for Command Query Responsibility Segregation or in laymens terms splitting the database reads (querying) from the CUD (Create/Update/Delete) commands using a messaging system. This is an architecture based around CQS (Command Query Seperation) where methods should either be a command that performs an action or query that returns data not both. The beauty of this architecture is to simplify the querying, as this is based on direct access to unnormalised data that maps directly to the view model objects used in the UI. This in turn simplifies the complexity of the query language to return the data as in most cases you are just returning direct data, so "SELECT * FROM ViewModel WHERE .." would suffice, no more need for complex object graphs or mapping relational data objects to DTO objects via a layered architecture.

The Command aspect of the architecture is slightly more difficult to grasp, but in general is relates to sending commands to a data store for Inserts/Deletes and Updates. When these commands are sent a messaging system picks up these changes and these changes are published to the Read only database or any other subscribers that require updating based on the event.

So thats the basic theory out of the way (see additional reading for further analysis) but how does this relate to real world applications or when trying to implement the architecture where migrating legacy applications with complex relational data structures? To see how this fits in I have decided to embark on a proof of concept application. The architecture to be used will be built around ASP.NET MVC 3.0 using the Razor view engine, MongoDb for the read only data store and SQL Server 2008 RC 2 for the Command data store. The issue is that we are dealing with a legacy application that has complex relational data which requires migrating so it would be unwise to amemd this structure at this stage. The Commands will be handled using Enitity Framework 4.1, due my knowledge in this area. In relation to the subscriber/publisher messaging mechanism I am still open to ideas on this. I am currently reviewing nServiceBus and will more than likely follow this route.

I am using mongoDb for the read only database as this will allow me to review a noSQL database and also see how scaleable this type of solution is. I looked at other noSQL databases (such as RavenDb and CouchDb) but mongoDb seemed better suited to my purposes. There are many discussions comparing these applications so it worth reading these before making a decision. It is also worth noting that you could just use a relational database or even XML data - it depends on your business case and what type of system you are developing.

My main concerns intially are bulk inserting data to mongoDb from SQL Server 2008. As mongoDb data is formatted as BSON (an extended JSON format to support binary data) I assume that I could easily create some form of routine in SSIS to be able to create this and then insert. From their documentation this is feasible using mongoimport. I am interested to see how the project progresses and to see how it all fits together but I feel its always worth reviewing new patterns (or old patterns revitalised) as soon as you can. The majority of new projects I see coming available require MVC skills now which was not so apparent over a year ago.The same I feel will happen to CQRS as it matures , more and more businesses with see the benefits developing applications over standard n-tier architecture.

Update
After reviewing Udi Dahans' blog post When to avoid CQRS, I may need to review if I require CQRS but theoretically seems to be suited to my business requirements as this stage. As this is only a proof of concept application and is defined to see how this pattern can work in my scenario I still feel it is worthwhile pursuing due to the experience that can be gained and the learning involved. I do think there has been confusion relating to CQRS, and there is concern it has reached "best practice" status. Maybe the reasoning behind this is the fact the n-tier architecture had led to complexity in software and developers/architects are now looking at alternatives to this approach based on the many issues that have arisen over the years when developing this way. My own opinion is that all projects need a specific architectural roadmap and all avenues need to be considered based on the business requirements - i.e. one size does not fit all.

Further Reading:
CQRS - Introduction for Beginners
mongoDb
Clarified CQRS

Using Quartz.Net in Windows Services

Mon Jul 04 2011 by MarkP

I was recently tasked to schedule an application using Windows Services for the current project I am working on. After researching the options available to me I decided to implement this using an open source project called Quartz.Net.

As with many .NET open source projects this is a port from the popular Java based scheduler. The basic premise of Quartz is based around the concept of scheduling jobs, which are fired, based on triggers assigned to the job. One of the most noticable things, was the use of CRON Unix expressions to be able to express schedules. Cron Expressions are used to define schedules in a clear and concise manner, as one line of text. e.g. to define the schedule to run every hour in office hours (9am-5pm) the following notation would be used "0 0 9-17 MON-FRI ? *". Further examples and tutorials can be found at Quartz.net

Testing and deploying Windows services is always a bit of a challenge espcially if the underlying service requires database or file access. I always ensure that I have sufficient logging in place to be able trace what the issue is. In this scenario, where the job ran quite a long running process I used both EntLib 5.0 to log the errors and custom logging which detailed the stages of the process once completed.

Text logs were created for the actual scheduling of the job and XML logs were created when the actual jobs were run. These were required in the UI so the user would be able to view if a job was successful or not and also display any relevant errors.

Another requirement was allow the user to manage the scheduling throught the UI .This was basically a CRON expression builder based on inputs entered by the user. One consideration that has to be accounted for, is that if the scheduler is amended, the windows service would have to be restarted for the new schedule to be implemented. This can be undertaken in C# code my accessing the ServiceController object and passing in the service name (see example).

Quartz is a very useful tool when scheduling jobs under window services and gived you the programmer a lot of flexibility and full control, in relation to scheduling jobs, rather than having to rely on the Timer object or scheduling jobs using third party applications.

Tags: Quartz.Net   C#   Post Comment

Html Helper for sharing links to Facebook

Wed Jan 12 2011 by MarkP

Over the last few days I have been working on this site to try and improve it whilst I had some time and also to improve my knowledge of the MVC framework. I had a requirement to be able to share my articles with social networking sites such as Facebook. Facebook has a javascript library which simplifies the process of displaying and sharing specific urls or pages on Facebook. Further information and details can be found at the Facebook Share site.

ASP.NET MVC has many built in HtmlHelpers that makes the displaying Html controls simpler and cleaner on the View and reduces the code required especially when the code needs to be dynamically created based on the model or route values. With this in mind a HtmlHelper was created to display the "Share Facebook" button on the page:

  1. public static MvcHtmlString FacebookShare(this HtmlHelper html,string type, string controllerName,string actionName, object routeValues)
  2.         {
  3. var tag = new TagBuilder("a");
  4. tag.MergeAttribute("name", "fb_share");
  5.             
  6. if(!string.IsNullOrEmpty(type))
  7. tag.MergeAttribute("type", type);
  8.  
  9. RequestContext ctx = html.ViewContext.RequestContext;
  10. UrlHelper urlHelper = new UrlHelper(ctx);
  11. tag.MergeAttribute("share_url", urlHelper.Action(actionName, controllerName, new RouteValueDictionary(routeValues), ctx.HttpContext.Request.Url.Scheme, ctx.HttpContext.Request.Url.Host));
  12. return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
  13.         }

This is displayed on the View using the following syntax (using Razor View Engine):

  1. @Html.FacebookShare("Facebook button type", "Controller", "Action", new {RouteValues})

At present the HtmlHelper is limited to Route Values only but could easily be extended to use optional parameters, such as Html attributes or the direct page link if required. The key requirement was to be able to pass in Route Values only and to be able to automatically create the link using MVC's built in methods such as the UrlHelper object.

Update
For Asp.NET MVC 3.0 you would use HtmlString rather than MvcHtmlString and return a new HtmlString(string value) rather than the static Create method exposed in the MvcHtmlString object.

Tags: MVC   Facebook   Post Comment