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  

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

Tags: CQRS   MVC   mongoDb   Entity Framework  

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  

Upgrade to MVC 3 RC 2

Sun Dec 19 2010 by MarkP

Things move fast in the MVC world. After just recently upgrading to MVC 2.0, this site has now been upgraded to Release Candidate 2 of the ASP.NET MVC framework Version 3. One of the major additions to the framework is the option to use the new Razor View Engine when creating Views. It never felt right using Master Pages in MVC I suppose it was thought of as transitional phase from migrating from ASP.NET forms to MVC. The ASP.NET view engine can still be used if wanted but after upgrading from this to the Razor View Engine can see the benefits of switching. I know that a lot of development has been undertaken using the Spark View Engine due to it being more HTML friendly and improved readability. Razor has addressed a lot of these issues and will be interested as to how this will effect the number of users now implementing Spark.

One the first "gotchas" was distinguishing between encoded and non encoded HTML. Razor automatically encodes the text when using the @ prior to an HTML helper class. This caused me issues when trying the display the content of the blog text as this can include HTML markup. A way round this is to either use MvcHtmlString.Create method or as from RC 2 the Html.Raw helper method.
This also caused me an issue when trying the generate the Recaptcha control - this now returns a MvcHtmlString from a custom helper I created rather than a string.

In my previous version of the site I was using standard inline code to generate hyperlinks - this has now been updated to use Html.ActionLinks. This was an oversight in my part when initially developing the site but once implemented in Razor, implementing this way solved some of the compilation issues encountered.

Below is a brief overview of the steps used in upgrading the website application in Visual Studio 2010

  1. Added a new MVC 3 Web application to the main solution and selected Razor as the View Engine
  2. Removed any unwanted files created when the application was added.
  3. Copied all View, Controllers and associated directories from previous MVC 2 application to MVC 3 application.
  4. Copy any sections from my web.config to the web.config in the new MVC 3 application
  5. Renamed all Views to used the .cshtml extension.
  6. Renamed the Master Page to _Layout.cshtml.
  7. Removed all references to the Master Page content templates and use the @model directive to call the relevant layout pages in the Views
  8. Refactor all <%= %> and <% %> tags to use the correct Razor syntax (@) - this required quite a bit of work to ensure the syntax was correct.
  9. In the previous version I was using user controls (.ascx files) which I replaced using .cshtml files and Partial Views.
  10. Remove the previous MVC 2 website application and set the MVC 3 version as the website application

When deploying the site I had to ensure that all the new assemblies were included in the bin directory of the website. When running locally this is not an issue as the assemblies are automatically included in the GAC. My host provider Discountasp.net currently do not have these installed on their servers so these files had to be included for the website to work correctly.

After a few tweaks I got the site up and running and is working as expected. All I am hoping now there are not many changes when the full release version of MVC 3 is released.

Further Reading & Resources:
Haacked
Download MVC 3 RC 2
ASP.NET MVC 3: Layouts with Razor

Tags: MVC   Razor  

Site Upgrade

Fri Sep 17 2010 by MarkP

I recently had the time to upgrade this site as follows:

  • Targets the .NET 4.0 Framework
  • Upgraded to use ASP.NET MVC 2
  • The project files and source code were upgraded from Visual Studio 2008 to 2010
  • Source control was moved from Subversion to Git and the repository is now hosted on GitHub
  • Castle Windsor was upgraded to the current release

In general the upgrade was quite painless with Visual Studio 2010's update wizard. Moving from Subversion to Git was fairly straightforward and there are many tools out there to assist with this task.

I decided to use Git due to the fact I could host the source code on GitHub and also due to the improvements made to Git Extensions for Visual Studio, which simplified the process of using Git in the Visual Studio IDE. I heard a lot of good things about Git and have been very impressed since using it on another project.

Upgrading the site will allow me to learn the new features of C# 4.0 and also get to grip with ASP.NET MVC 2, which is long overdue.

Tags: MVC   ASP.NET   Visual Studio 2010   Git  

Site Improvements

Sun May 23 2010 by MarkP

Over the last month some minor improvements have been made to this site. One of the main issues was implementing a CAPTCHA system to prevent "spam attacks" when submitting form data. Initially I was a bit wary of using a CAPTCHA based system due to issues with accessibility and the negative feedback it tends to receive in general.

I reviewed a few alternatives which tended to rely on javascript, the basic premise being to distinguish between an actual form post orignating from the actual page rather than a faked post as implemented by many of the spam bots trawling the web.
Not being 100% convinced by this decided to research third party CAPTCHA systems that can be easily plugged into a website with very little configuration. After some "googling" I decided to implement Recaptcha onto the site.

All in all its a really neat plugin, my only issue being that I can never understand the audio that is generated, so may revisit this at a later date.

Another improvement was to include the facility to be able to retrieve my CV as a Microsoft Word docx or Adobe PDF file. Many employment agencies wanted to be able to retrieve a Word version of my CV so this option was added to the CV request form.

As the blog engine is generated using XML there was an issue relating to the HTML being stripped out when retrieving data from an XElement value in Linq. To work around this an extension method was created:

           1:  public static string PreserveHtml(this XElement xElement)
      
           2:  {
      
           3:              if (xElement == null) return string.Empty;
      
           4:   
      
           5:              var content = new StringBuilder();
      
           6:              foreach (XNode node in xElement.Nodes())
      
           7:              {
      
           8:                  content.Append(node.ToString(SaveOptions.DisableFormatting));
      
           9:              }
      
          10:   
      
          11:              return content.ToString();
      
          12:  }
      

This ensured the HTML in the description was preserved and formatted correctly in the RSS Feed.

Tags: MVC   CAPTCHA   XML  

The Future of ASP.NET - A Developers Perspective

Sun Apr 18 2010 by MarkP

In the development community there has been an ongoing debate in relation to the future of ASP.NET. Many developers are now torn between learning ASP.NET MVC or continuing to pursue the ASP.NET webforms route, utilising ASP.NET 4.0.

I have been following ASP.NET MVC since the early betas and were impressed that Microsoft had decided to go this route. It solved a lot of problems that I have come across from all my years of development and addressed many issues myself and fellow development team members could not always solve using ASP.NET webforms.

The key issues were always centred around Unit Testing, non compliant CSS or XHTML markup and having very little control over these elements (this becomes more apparent when your team has dedicated UI developers), and ASP.NET page events or the overuse of them. I have worked on many projects where this model has been abused or not fully understood. The issue on not adopting MVC for many developers is the amount of time and effort already spent in learning ASP.NET utilising webforms, the ease of creating web applications within a short time frame (using built in controls) and the availability of tools and knowledgebase available.

A true test of a new development framework relates to the number of job vacancies that appear over time, since the initial release. After trying a quick keyword search on Jobserve for the United Kingdom the following results were obtained:

  • ASP.NET and MVC - 113 live vacancies
  • ASP.NET (excluding MVC) - 839 live vacancies

What I have noticed is, is that this rate has been increasing gradually over the last few months, as more companies are seeing the benefits of using ASP.NET MVC as a software development framework.

As a developer I try to understand and adopt new technologies as soon as I can. I decided to focus on ASP.NET MVC but still intend to review ASP.NET 4.0 at the earliest opportunity. I am currently reviewing Visual Studio 2010 and as my hosting partner now supports ASP.NET 4.0, will look at implementing new C# 4.0 features on any further development of this internet site.
It requires a lot of additional work and time on my part but feel it pays dividends in the longer term. Therefore to summarise it is better to learn as many new skills as you can, I find sometimes potential employers will see this as a benefit as each method, be it webforms or MVC, has a potential business benefit and knowing both frameworks will make you as a developer more employable.

Tags: MVC   ASP.NET  

Introduction

Sun Apr 11 2010 by MarkP

Welcome to the M P Consultants Ltd website. The site is built around the ASP.NET MVC Framework, using C#. The site has recently been redeveloped to include a blog facility, built directly for the ASP.NET MVC framework.

Due to certain restraints in hosting, there were limitations into what "backend" would be used to persist the data, which also limited the choice of third party blog engines which could be used.

The solution eventually was based purely around XML, which is lightweight, of a defined structure and can easily be imported into a database solution at a later date if required.

The development is ongoing (the blog engine is still in beta) and additional facilities will be added over the coming months.

Key areas I have focused for the first phase were as follows

  • XML data used to store articles, is RSS 2.0 compliant
  • Links are Search Engine Optimised (SEO) and articles can be filtered by title, category, year and month
  • Comments
  • Implementation of a Tag Cloud
  • Caching
  • Archive and latest articles display
  • XHTML Strict Compliance

Improvements will be being made over the coming months with any updates being posted as and when they occur.

Tags: MVC   ASP.NET   XML