aspnet RoleProvider woes with StructureMap and NHibernate

June 24th, 2009

I just fixed a bug that has plagued me for the last 2 nights. NHibernate was throwing completely random exceptions, rolling back transactions with no real consistency other than always happening on requests made after the application had started and almost always within my RoleProvider. I couldn’t figure out what the heck was happening.

Some of the exceptions:

“Could not synchronize database state with session”

“Rollback failed - System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable.”

“Commit failed - System.NullReferenceException: Object reference not set to an instance of an object.”

“Could not synchronize database state with session - NHibernate.ADOException: There was a problem converting an IDataReader to NDataReader”

“System.ObjectDisposedException: Session was disposed of or closed Object name: ‘ISession’.”

I’m using StructureMap to Dependency Inject an NHibernate.ISession into my NHibernateRepositoryBase class, and inject the repository to my Service class. Because you can’t dependency inject into a AspNet RoleProvider I’m using the StructureMap ObjectFactory.GetInstance<T> to get me an instance of my IUserService. I was placing this in the constructor, setting a private field that was then accessed in all the overridden methods I am implementing.

And this was what got me.

The reason that the exceptions would happen on any requests made after the application had started was because AspNet Providers are created once per application and reused throughout the duration of the application. This meant when the instance was created it would have a reference to the NHibernate.ISession for that request, but since the ISession is closed in application_endrequest subsequent requests the RoleProvider was now referencing an ISession that was closed.

My solution was to remove the ObjectFactory.GetInstance<T> field assignments to within each method that needed the service, that way ensuring that the NHibernate.ISession for the current request would be used.

Luke Smith ASP.NET, Development, NHibernate, StructureMap

ASUS Eee PC 1000HE Review

March 21st, 2009

I’ve been on the lookout for a netbook for a few months. I’ve been tempted by the HP Mini-Note 2133, Dell Mini 9 and Dell Mini 10. Each had things I liked about them but none made me part with my cash.

The Dell Mini 9 looks great, but after seeing it in the shops and being able to get my hands on it the keyboard was far too small for me. So when the Dell Mini 10 was announced I thought “great, a larger screen and larger keyboard so it should be OK” but unfortunately you can’t upgrade the RAM, so you’re stuck at 1GB, not enough to comfortably run Windows 7.

In the end I was looking at the Asus Eee PC 1000H which lead my to spot the 1000HE. With a whopping 9.5 hours battery life, 1.66GHz Intel Atom CPU (the 1000H comes with a 1.6GHz), 10” screen, 120GB HDD, built in 1.3MP camera and multi touch trackpad temptation became too much. So I ordered one, along with a new 2GB stick of RAM to replace the standard 1GB.

First impressions were good, it looks great, it’s not too heavy and the screen is nice and bright. I booted up with the default XP installation to check that everything was working and then proceeded to install the Windows 7 Beta released a few months back.

Installing Windows 7 was amazingly quick, taking about 30-40 minutes in total (I installed via hosting the ISO image using the Microsoft Virtual CD-ROM utility under XP).

Windows 7 had no problems finding drivers, except for the LAN driver (you can download the XP driver from the ASUS website that works under Windows 7). Everything “just works”. CPU usage is currently sitting around 20% with Outlook, Live Writer, twhirl and IE8 open.

The keyboard isn’t full size, but is perfectly big enough even for my large hands. The only issue, as with getting any new keyboard, is the placement of some keys, Home/End/PgUp/PgDn are all function keys, which is annoying. It’s nothing that a few days of use won’t solve, so my fingers memorise the locations.

The one thing which I wish was present was a nipple. I really hate trackpads to control the mouse cursor. They can’t cost much to include, and theres enough room in the keyboard for one to be put. However I do like the multitouch functionality of the trackpad, especially for vertical scrolling.

Battery life appears excellent, I seem to be getting about 7 hours out of it with the wireless card turned on.

My next task was to install some software, Office 2007 and Visual Studio 2008, which because I don’t have an external DVD drive I had to do via sharing the DVD drive on my desktop over the network. VS2008 took about an hour, which tends to be the usual amount of time. However when installing Visual Studio 2008 SP1 I began getting issues with the graphics drivers, the machine became unusable and unresponsive with the graphics flickering and disappearing every few seconds. I left the install to run and it completed after about 2 hours.

Overall I’m very happy with the device. Netbooks are the perfect device for throwing in your rucksack for use when commuting, which I do alot of, and so the battery life is a real bonus with the Eee PC 1000HE. Windows 7 is perfect for netbooks, hopefully by RTM there will be some more performance boost and the graphics drivers will be improved.

Technorati Tags: ,

Luke Smith Hardware ,

Generating and enforcing that any link and request is lowercase with ASP.NET MVC

February 1st, 2009

This post is based off 2 other blog posts I found which helped me come up with my solution with some slight modifications on their code.

For my new project I’m having my URLs all lowercase, as some search engines interpret ‘/Home’ and ‘/home’ as two different locations. So the problem became “how can I enforce all my URLs get rendered as lowercase, and how do I force a request to a URL with an uppercase letter to redirect to the lowercase equivalent?”.

Because I’m using ASP.NET MVC I needed a way to get the Routing engine to render the URL as lowercase when using an ActionLink. Asking the question over on stackoverflow I got a solution that involved creating my own class that inherits from Route, which I’ve called LowercaseRoute, and overrides the GetVirtualPath method. I also created a MapLowercaseRoute extension method on the RouteCollection class that allows me to map a LowercaseRoute easily.


public class LowercaseRoute : Route
{
public LowercaseRoute(string url, IRouteHandler routeHandler)
: base(url, routeHandler)
{
}

public LowercaseRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
: base(url, defaults, routeHandler)
{
}

public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler)
: base(url, defaults, constraints, routeHandler)
{
}

public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
var virtualPath = base.GetVirtualPath(requestContext, values);

if (virtualPath != null)
{
virtualPath.VirtualPath = virtualPath.VirtualPath.ToLowerInvariant();
}

return virtualPath;
}
}

Next up is to ensure that any request to the site is enforced to be lowercased, and perform a 301 redirect if not. For this I’ve created a HttpModule, EnforceLowecaseRequestHttpModule, which I then register in the web.config. I could have put this directly into the global.asax file but I wanted to make it easily reusable on future projects.


public class EnforceLowercaseRequestHttpModule : IHttpModule
{
public void Dispose()
{
}

public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
}

private void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;

// If upper case letters are found in the URL, redirect to lower case URL (keep querystring the same).
string requestedUrl = ((application.Context.Request.Url.Scheme + "://" + application.Context.Request.Url.Authority + application.Context.Request.Url.AbsolutePath));

if (Regex.IsMatch(requestedUrl, @"[A-Z]") == true)
{
string lowercaseUrl = requestedUrl.ToLower();
lowercaseUrl += HttpContext.Current.Request.Url.Query;

application.Context.Response.Clear();
application.Context.Response.Status = "301 Moved Permanently";
application.Context.Response.AddHeader("Location", lowercaseUrl);
application.Context.Response.End();
}
}
}

Luke Smith ASP.NET, MVC

JavaScript variable generation for ASP.NET MVC

January 31st, 2009

RC1 of the ASP.NET MVC framework adds a new ActionResult, JavaScriptResult. This class takes a string and returns a response with the string with the required ContentType.

So now theres a built in (very simple) ActionResult for returning JavaScript what about generating the JavaScript string on the server to return?

One thing I do alot is to recreate service side enums on the client in JavaScript, so rather than checking values I can use names, which improves the readability of the javascript. However this requires both the server and the client to be kept in sync, which can be a pain.

To resolve this issue I’ve created a JavaScriptGenerator class which handles serialization of objects and Enum types as variables and generates the JavaScriptResult, as well as a helper method to take a controller name and action name and insert the required <script .. /> tag into the markup.

Note I’ve created my own JavaScriptHelper class, similar to HtmlHelper, that I extend with extension methods the are javascript specific. I’ve also got a bunch of other extension methods for registering variables in the html itself as well as adding the <script /> tag for a specified filename.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace LukeSmith.Web.Mvc.JavaScript
{
    public class JavaScriptGenerator
    {
        private StringBuilder builder;

        /// <summary>
        /// Initializes a new instance of the <see cref="JavaScriptGenerator"/> class.
        /// </summary>
        public JavaScriptGenerator()
        {
            builder = new StringBuilder();
        }

        /// <summary>
        /// Generates a javascript variable from enum.
        /// </summary>
        /// <param name="name">The name to give the javascript variable.</param>
        /// <param name="enumType">Type of the enum.</param>
        /// <returns>
        /// Current instance of the <see cref="JavaScriptGenerator"/>.
        /// </returns>
        /// <exception cref="InvalidOperationExceptions"></exception>
        public JavaScriptGenerator GenerateVariableFromEnum(string name, Type enumType)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (enumType.IsEnum)
            {
                Array values = Enum.GetValues(enumType);
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                Dictionary<string , object> dictionary =new Dictionary</string><string ,object>();

                foreach (var value in values)
                {
                    string enumName = Enum.GetName(enumType, value);

                    dictionary.Add(enumName, value);
                }

                builder.Append(string.Format("var {0} = {1};", name, serializer.Serialize(dictionary)));
            }
            else
            {
                throw new InvalidOperationException("Cannot generate JavaScript code when enumType is not an Enum.");
            }

            return this;
        }

        /// <summary>
        /// Generates a javascript variable from an object.
        /// </summary>
        /// <param name="name">The name to give the javascript variable.</param>
        /// <param name="value">The value.</param>
        /// <returns>
        /// Current instance of the <see cref="JavaScriptGenerator"/>.
        /// </returns>
        public JavaScriptGenerator GenerateVariableFromObject(string name, object value)
        {
            List<javascriptconverter> converters = new List</javascriptconverter><javascriptconverter>();

            return this.GenerateVariableFromObject(name, value, converters);
        }

        /// <summary>
        /// Generates a javascript variable from an object.
        /// </summary>
        /// <param name="name">The name to give the javascript variable.</param>
        /// <param name="value">The value.</param>
        /// <param name="converter">The <see cref="JavaScriptConverter"/> to use to convert the <paramref name="value"/>.</param>
        /// <returns>
        /// Current instance of the <see cref="JavaScriptGenerator"/>.
        /// </returns>
        public JavaScriptGenerator GenerateVariableFromObject(string name, object value, JavaScriptConverter converter)
        {
            List</javascriptconverter><javascriptconverter> converters = new List</javascriptconverter><javascriptconverter>();
            converters.Add(converter);

            return this.GenerateVariableFromObject(name, value, converters);
        }

        /// <summary>
        /// Generates a javascript variable from an object.
        /// </summary>
        /// <param name="name">The name to give the javascript variable.</param>
        /// <param name="value">The value.</param>
        /// <param name="converters">An <see cref="IEnumerable"/> of <see cref="JavaScriptConverter"/> to use to convert the <paramref name="value"/>.</param>
        /// <returns>
        /// Current instance of the <see cref="JavaScriptGenerator"/>.
        /// </returns>
        public JavaScriptGenerator GenerateVariableFromObject(string name, object value, IEnumerable</javascriptconverter><javascriptconverter> converters)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(converters);

            builder.Append(string.Format("var {0} = {1};", name, serializer.Serialize(value)));

            return this;
        }

        /// <summary>
        /// Generates the <see cref="JavaScriptResult"/>.
        /// </summary>
        /// <returns></returns>
        public JavaScriptResult Generate()
        {
            return new JavaScriptResult() { Script = this.ToString() };
        }

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString()
        {
            return builder.ToString();
        }
    }
}

And the code for the helper method
 


public static string ScriptInclude(this JavaScriptHelper javaScriptHelper, string actionName, string controllerName)
        {
            UrlHelper helper = new UrlHelper(javaScriptHelper.ViewContext.RequestContext);
            string url = helper.Action(actionName, controllerName);

            return string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>{1}", url, Environment.NewLine);
        }

Luke Smith JavaScript, MVC , ,

ASP.NET MVC

December 8th, 2008

WebForms are the existing technology in ASP.NET for web applications, which have been around since the beginning of ASP.NET. However, despite being mature and having a large developer base they aren’t ‘all that’. It’s been said that WebForms are “web development for VB Developers”, in that the drag ‘n’ drop and double clicking to add an event handler for a button eases the migration from Windows Development to the web. The problem with this is that WebForms brings a state-based system (via ViewState) to the web, that is fundamentally stateless. Added onto this the complex page-life cycle of the WebForms model and the lack of separating of concerns, WebForms isn’t really suitable for building maintainable and testable web applications.

ASP.NET MVC is built on the ASP.NET framework, so existing WebForms developers can make use of the existing classes and framework knowledge they possess (Forms/Windows Authentication, Membership Roles, Session/Profile state, Health Monitoring etc…). ASP.NET MVC projects also have the added benefit that they can include traditional WebForms pages and User Controls (though I wouldn’t recommend mixing the two if you can help it), so the transition can be made without throwing all your existing pages away.

By default ASP.NET ships with the WebForms syntax View Engine, however third party view engines can easily be used with a few additions to the web.config file and global.asax. The best ViewEngine I’ve seen is SparkViewEngine. This engine allows ‘the html to dominate the flow and the code to fit seamlessly’, losing the horrible <% %> tags which can make the default viewengine unreadable.

Overall I’m very impressed with the MVC framework, and how easy it is to pick up. The time its taken to learn has been minimal and hasn’t affected the time it’s taken to use it on my current project. I can see the benefits it will bring in the future, including having greater confidence of releases (due to unit testing) and the maintainability that the MVC pattern enforces via the separation of concerns.

Luke Smith , MVC

Linq2JS – A JavaScript library for writing Linq-like expressions

December 8th, 2008

It all started when I was having to convert some C# to JavaScript, so was needing quite a bit of collection manipulation. It’s frustrating going back to lots of for loops when you’ve been blessed with LINQ for a year.

So after 20 hours of solid coding one weekend (the first implementation was written in 10 hours with the second 10 tidying things up) I created Linq2JS. I’m very happy with how its turned out, however some things are still lacking (building an expression tree to improve the performance).

Over the past 2 weeks I’ve been documenting, writing unit tests and fixing bugs that the unit tests have uncovered (note to self: unit tests should be done first) and finally released the first fully tested version (1.2). The whole thing comes in at under 20KB minified, so it’s not huge even though there’s nearly 2000 lines of code in the un-minified version.

I’ve setup a wiki, where I will be hosting documentation for any future projects I do, and have made a start documenting all the functionality of Linq2JS.

 

Example

A brief example of using Linq2JS


var animals = [];
animals.push({ type: AnimalType.Dog, name: "Rover", age: 13, children: [] });
animals.push({ type: AnimalType.Cat, name: "Fluffy", age: 1, children: [] });
animals.push({ type: AnimalType.Dog, name: "Rex", age: 12, children: ["Rover"] });
animals.push({ type: AnimalType.Fish, name: "Goldie", age: 3, children: ["Scales", "Goldie"] });
animals.push({ type: AnimalType.Cat, name: "Fudge", age: 20, children: ["Digby", "Kitty"] });
animals.push({ type: AnimalType.Cat, name: "Digby", age: 2, children: [] });
animals.push({ type: AnimalType.Cat, name: "Kitty", age: 4, children: [] });
animals.push({ type: AnimalType.Dog, name: "Rover", age: 3, children: [] });
animals.push({ type: AnimalType.Fish, name: "Scales", age: 2, children: [] });
animals.push({ type: AnimalType.Fish, name: "Goldie", age: 1, children: [] });

var source = new Enumerable(animals);  // or = $e(animals)

var result = source.where(function(item) {
    return item.age > 9;
}).select(function(item) {
    return item.name + " is " + item.age + " years old";
}).execute();

Luke Smith JavaScript, Linq2JS

Model View Controller

December 4th, 2008

I’m giving a presentation next week at work about MVC (specifically Microsoft’s ASP.NET MVC Framework) so thought I’d dust off the blog and put some of my thoughts down regarding the topic.

First off, what is MVC? MVC stands for Model-View-Controller and is an architectural design pattern for developing applications. It’s not specific to the web, as desktop applications can also make use of the design pattern. The basis of MVC is to force the separation of the business logic from the UI. The greatest benefit of this in my opinion is the ability to enable Test Driven Development (TDD) easily.

The Model

The model is the term used to represent the data and information in the system, as well as the business rules of the application.

The View

The view is the UI elements of the application, what the user sees, whether they be textboxes and checkboxes on a webpage or a generated report from the application.

The Controller

The controller is what brings everything together. The controller responds to user input and interaction, manipulates the model (data and business rules) then chooses a view to render the model to. The controller should actually do very little work, it should delegate to perform business logic. This keeps the logic separate and more easily testable.

 

In a future post I’ll talk specifically about the ASP.NET MVC Framework.

Technorati Tags: ,

Luke Smith MVC

Out of Office issue with hosted Exchange2007

September 20th, 2008

1and1 have upgraded me to Exchange2007, which is nice. I’m liking the flagging features now available on my Windows Mobile device.

I ran into an issue, which 1and1 refused to help me solve due to it being ‘out of our scope of support’. They’re support is ‘will provide you the necessary settings for you to be able to setup your exchange account in your Outlook 2007’. As far as I’m concerned not being able to view the Out of Office options comes under they’re support.

My situation is I have my exchange server hosted with 1and1, and the domain not. I’m not sure if I would have the same issue whether I had the domain hosted with them or not.

When Outlook 2007 starts up it attempts to connect to autodiscover.lukesmith.net (as lukesmith.net is the domain of the email), which obviously didn’t exist as exchange isn’t at that domain and so certificate warnings were being shown, and OOF not working.

"Your Out of Office settings cannot be displayed, because the server is currently unavailable. Try again later".

All I was after from 1and1 support was the URL for the their exchange autodiscover so I could setup a CNAME record in my DNS settings for the domain. So after getting a reply (which was quite quick even if it wasn’t helpful) I broke out fiddler and watched the requests outlook was making. It turns out it was making the request to http://autodiscover.lukesmith.net/autodiscover/autodiscover.xml. So a few more tries and I discovered http://exchange.1and1.co.uk/autodiscover/autodiscover.xml was requiring authentication and after authenticating returning an xml response.

Adding the DNS record below fixed the issue of not being able to use Out of Office replies though I’m still getting the certificate errors. These used to occur when connecting to Exchange2003, but stopped after a while.

autodiscover.lukesmith.net CNAME exchange.1and1.co.uk

Luke Smith Exchange, Outlook

GeoJSON for Virtual Earth

September 9th, 2008

For my new project I decided to make use of GeoJSON, a standard for representing geo data in JSON format, rather than returning KML, georss to the client, or some custom format.

From a quick look online there wasn’t much in the way of using Virtual Earth with GeoJSON, I found one blog post that was the inspiration behind doing VEGeoJSON.

The VEGeoJSON library provides two functions (not much of a library)

  • addGeoJSON(data, onLayerCreated, onShapeCreated)
  • getGeoJSON(onGeometryCreated)

As a quick example of its usage

var v = new VEGeoJson(map);
var geoJson = v.getGeoJSON();

VEGeoJSON supports all the GeoJSON shapes; Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection.

 

Thanks to Colin Brown for giving it a quick test and talking me into putting it on CodePlex.

 

Luke Smith JavaScript, VEGeoJSON, Virtual Earth

Project Hush Hush

September 8th, 2008

I came up with a lightening bolt of an idea the other week while I was thinking of a small project to do to try out some new technology. This project has spiraled into a bigger project which I think could be quite cool and big - so there goes my evenings for the next few months.

The few people I’ve told the idea to seem to think it also sounds good, either that or they’re just humouring me so I waste my time on it. Either way it’s giving me a great chance to try out some technologies that interest me.

Hopefully it will encourage me to blog more, I’ll be sharing bits and pieces as I go along.

I discovered a free Subversion source control provider (assembla) so all my work is safely backed up remotely (maybe I should use the project management tools to keep a track of ideas). Ideally I’d like to do host the source control myself, only currently I can’t afford to change (or find one that matches (will match) my needs) hosting provider to a Virtual Private Server.

Luke Smith Development, Project Hush Hush