Category Archives: Code

Code examples.

Code Python

Project Euler + Python

For a while I’ve been meaning to play with python but I could never think of something to do with it; so I decided to try and solve as many problems in Project Euler as I can.

Here is my mercurial repository on bitbucket: https://bitbucket.org/TWith2Sugars/project-euler

This is my attempt at the first problem so far:

Problem: http://projecteuler.net/index.php?section=problems&id=1
source: https://bitbucket.org/TWith2Sugars/project-euler/src/813d5ec90687/python/1.py

result = 0
for i in range(1000):
    if i % 5 == 0:
	    result += i
    elif i % 3 == 0:
	    result += i

print(result)
Code

How I fixed FluentNHibernate.Cfg.FluentConfigurationException on MVC 3

Just to let you know this may not solve your version of this error (since it’s so vague) but it’s how I solved it in one of my projects.

On a previous post I mention I was using NHibernate in one of the projects I’m working on and as such we’re using FluentNHibernate.

I’ve created a class (let’s call it SessionManager) that handles creating the ISessionFactory instance (and stores it in a static field). The project is built with MVC 3 and makes use of the DI provider along with Ninject so this code snippet should look familiar. (It’s where you set up you DI – usually the AppStart_NinjectMVC3)

kernel.Bind<ISessionFactory>().ToConstant(SessionManager.CreateSessionFactory());

That is the line the caused the problems; not sure how but the aspnet compiler dies. In the end I changed ninject to use “ToMethod” instead:

kernel.Bind<ISessionFactory>().ToMethod(c => SessionManager.CreateSessionFactory());

Since the session manager handles creating the ISessionFactory like I mentioned earlier we don’t get multiple instances of ISessionFactory.

Asp.Net MVC Code

NHibernate leaking connections with UnitOfWork pattern and transactions

Recently I’ve been using NHibernate in a project at work along with the unit of work pattern in an asp.net mvc site. Only 1 instance of the UoW is created per request and disposed of at end of the request.

In fact here is a UoW class we’re using:

public class UnitOfWork : INHibernateUnitOfWork
  {
    /// <summary>
    /// The session factory
    /// </summary>
    private readonly ISessionFactory sessionFactory;

    /// <summary>
    /// The current transaction
    /// </summary>
    private readonly ITransaction transaction;

    /// <summary>
    /// Gets the session.
    /// </summary>
    /// <value>The session.</value>
    public ISession Session { get; private set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="UnitOfWork"/> class.
    /// </summary>
    /// <param name="sessionFactory">The session factory.</param>
    public UnitOfWork(ISessionFactory sessionFactory)
    {
      this.sessionFactory = sessionFactory;

      Session = this.sessionFactory.OpenSession();
      Session.FlushMode = FlushMode.Auto;
      transaction = Session.BeginTransaction();
    }

    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    public void Dispose()
    {
      transaction.Dispose();
    }

    /// <summary>
    /// Commits this instance.
    /// </summary>
    public void Commit()
    {
      if (!transaction.IsActive)
      {
        throw new InvalidOperationException("No active transation");
      }

     /transaction.Commit();
    }

    /// <summary>
    /// Rollbacks this instance.
    /// </summary>
    public void Rollback()
    {
      if (transaction.IsActive)
      {
        transaction.Rollback();
      }
    }
  }

As you can see in the constructor we create a new NHibernate transaction and dispose of it when the request ends (by calling the dispose method).

The problem with this is that it created a connection with an open transaction but never closed it. Any way to resolve this we removed the use of transactions (until such a time they are working or we’ve figured out a suitable alternative). Two changes where made to the dispose and commit method to clean up the session instance and make sure the data is flushed.

    public void Dispose()
    {
      Session.Dispose();
    }

    public void Commit()
    {
      Session.Flush();
    }

Note: This project also is using the Velocity cache provider and by removing the transactions / replacing the code the caching mechanisms still work.

Code

My first OSS project – DOAP

At work I’m developing a web api for a project that is to be used be several devices and possibly by 3rd parties; I was having a discussion with a few colleagues about the best way to secure this api and this eventually moved on to OAuth.  The choice we faced was do we go with the existing and finalised OAuth protocol or do we take a chance and jump on board with OAuth 2 and all the benefits  it brings, the choice was easy we needed or api to work on mobile devices, desktop apps and a whole host of non-web based apps.

Next step was to see if there was an existing library that allowed us to be a provider. Two that came up (did I mention this was a .Net project?) were DotNetOpenAuth and another one which I’ve just forgotten. I played about with both attempting to get it up and running but had some difficulty. Neither library suited my needs so I decided to try and build one my self; and I did 🙂

I had a read through the PHP implementation and read the protocol draft several times over and what I developed is my  best interpretation of it. The project I was working on required the use of the assertion/password/refresh grants and that’s all I’ve tested so far. Hopefully someone will give the others a try too.

Source: http://github.com/TWith2Sugars/DOAP

License: MIT

Dependencies: WCFRestContrib (only for the WCF helper attributes)

WCF

The project I’m working on has the api provided via WCF and obviously I had to get my OAuth implementation working with WCF (With a huge help from the fantastic WCFRestContrib library). Check out the example in the github repo to see a working version.

Why DOAP?

DotNet OAuth Provider of course.


There is no binaries yet, not until the draft is finalised or someone requests it. It’s easy to build any way as there are barley any dependencies.

I’ll make a post of how to set it up soon but until then hopefully the example is enough to get you going.

Asp.Net MVC Code

How to POST JSON data to an Asp.Net MVC 2 app with ValidateAntiForgeryToken

The title says it all really, earlier this week I was attempting to submit data in the form of JSON to a controller method that implemented the ValidateAntiForgeryTokenAttribute.

On the client side of things  I managed to get the validation input generated by Html.AntiForgeryToken into my JSON object but I just kept on getting the “A required anti-forgery token was not supplied or was invalid” exception.

After a bit of research I found the problem to lie in the Asp.Net MVC 2 source, if you look at the ValidateAntiForgeryTokenAttribute file specifically on line 56 (OnAuthorization method) you’ll see this:

string formValue = filterContext.HttpContext.Request.Form[fieldName];

The validation class always checks the form for the token but we don’t have any form data when we post JSON!

So my solution was to modify like so:

      string value;
      if (filterContext.HttpContext.Request.ContentType.ToLower().Contains("json"))
      {
        var bytes = new byte[filterContext.HttpContext.Request.InputStream.Length];
        filterContext.HttpContext.Request.InputStream.Read(bytes, 0, bytes.Length);
        filterContext.HttpContext.Request.InputStream.Position = 0;
        var json = Encoding.ASCII.GetString(bytes);
        var jsonObject = JObject.Parse(json);
        value = (string)jsonObject[fieldName];
      }
      else
      {
        value = filterContext.HttpContext.Request.Form[fieldName];
      }

What happens here is I do a check to see if the post is json, if so I then pull the string from the input stream and using a JSON parser extract the token.

Since we’re modifying the ValidateAntiForgery class we might as allow it to work  with (or restrict to) any http verb.

This is what I’ve ended up with (sorry about the formatting):

namespace Your.App
{
  using System;
  using System.Linq;
  using System.Text;
  using System.Web;
  using System.Web.Mvc;
  using Newtonsoft.Json.Linq;

  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
  {
    private string _salt;
    private AntiForgeryDataSerializer _serializer;
    private readonly AcceptVerbsAttribute _verbs;

    public string Salt
    {
      get
      {
        return _salt ?? String.Empty;
      }
      set
      {
        _salt = value;
      }
    }

    internal AntiForgeryDataSerializer Serializer
    {
      get
      {
        if (_serializer == null)
        {
          _serializer = new AntiForgeryDataSerializer();
        }
        return _serializer;
      }
      set
      {
        _serializer = value;
      }
    }

    public ValidateJsonAntiForgeryTokenAttribute(HttpVerbs verbs = HttpVerbs.Post):this(null, verbs)
    {
    }

    public ValidateJsonAntiForgeryTokenAttribute(string salt, HttpVerbs verbs = HttpVerbs.Post)
    {
      this._verbs = new AcceptVerbsAttribute(verbs);
      this._salt = salt;
    }

    private bool ValidateFormToken(AntiForgeryData token)
    {
      return (String.Equals(Salt, token.Salt, StringComparison.Ordinal));
    }

    private static HttpAntiForgeryException CreateValidationException()
    {
      return new HttpAntiForgeryException("A required anti-forgery token was not supplied or was invalid.");
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
      if (filterContext == null)
      {
        throw new ArgumentNullException("filterContext");
      }

      // We only need to validate this if it's a post
      string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride();
      if (!this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase))
      {
        return;
      }

      string fieldName = AntiForgeryData.GetAntiForgeryTokenName(null);
      string cookieName = AntiForgeryData.GetAntiForgeryTokenName(filterContext.HttpContext.Request.ApplicationPath);

      HttpCookie cookie = filterContext.HttpContext.Request.Cookies[cookieName];
      if (cookie == null || String.IsNullOrEmpty(cookie.Value))
      {
        // error: cookie token is missing
        throw CreateValidationException();
      }
      AntiForgeryData cookieToken = Serializer.Deserialize(cookie.Value);

      string value;
      if (filterContext.HttpContext.Request.ContentType.ToLower().Contains("json"))
      {
        var bytes = new byte[filterContext.HttpContext.Request.InputStream.Length];
        filterContext.HttpContext.Request.InputStream.Read(bytes, 0, bytes.Length);
        filterContext.HttpContext.Request.InputStream.Position = 0;
        var json = Encoding.ASCII.GetString(bytes);
        var jsonObject = JObject.Parse(json);
        value = (string)jsonObject[fieldName];
      }
      else
      {
        value = filterContext.HttpContext.Request.Form[fieldName];
      }

      if (String.IsNullOrEmpty(value))
      {
        // error: form token is missing
        throw CreateValidationException();
      }
      AntiForgeryData formToken = Serializer.Deserialize(value);

      if (!String.Equals(cookieToken.Value, formToken.Value, StringComparison.Ordinal))
      {
        // error: form token does not match cookie token
        throw CreateValidationException();
      }

      if (!ValidateFormToken(formToken))
      {
        // error: custom validation failed
        throw CreateValidationException();
      }
    }
  }
}

Also I had to copy over 2 classes from the MVC source. The “AntiForgeryData” and “AntiForgeryDataSerializer” since they are interal and my project wouldn’t compile without them.

Final note, if you’re having trouble with the Serializer you copied over (in the Deserialize method and casting to a Triplet) then this may be of some help (.Net 4.0 only):

                dynamic deserializedObj = formatter.Deserialize(serializedToken);
                return new AntiForgeryData() {
                    Salt = deserializedObj[0],
                    Value = deserializedObj[1],
                    CreationDate = (DateTime)deserializedObj[2]
                };
Code

Short Break

It’s been sometime since I’ve last posted an update to my blog so I thought I’d better get in gear and do something about it. So for now here is a reminder for those who use Memcached with Enyim.

USE THE [Serializable] ATTRIBUTE ON YOUR CLASSES.

I keep forgetting that.

Code

Asp.Net MVC 2 Routing SubDomains to Areas

I’ve been building an Asp.Net MVC 2 site with Tom on the new Thap site and we hit a stumbling point regarding sub-domains and areas; you can probably guess what the problem was from the title.

Any way after a bit of googling it looks like no one has figured this out, or that they arn’t sharing. So it’s time I shared the solution that worked for us. This requires no libraries or esoteric settings or anything like that, just a little bit of code that will end up making your routes look like this:

context.Routes.MapSubDomainRoute(
        "Admin_default", // Name
        "admin", // SubDomain
        "{controller}/{action}/{id}", // Url
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Defaults
        new[] { typeof(Controllers.HomeController).Namespace }); // Namespace

First we need to create a Route class that can handle subdomains, lucky for you I just happen to have one. What this class does is check the incoming request, if the sub-domain matches it then checks to see if the rest of the url matches the route you specified:

Update: Since publishing this post I’ve added an update to the code. The GetVirtualPath function  has been overridden to check if the area of the value matches the sub-domain . This was needed because it messed up the url generation for everything.

namespace Your.App
{
  using System.Web;
  using System.Web.Routing;

  /// <summary>
  /// A route class to work with a specific subDomain
  /// </summary>
  public class SubDomainRoute : Route
  {
    /// <summary>
    /// The subDomain to route against
    /// </summary>
    private readonly string subDomain;

    /// <summary>
    /// Initializes a new instance of the <see cref="SubDomainRoute"/> class.
    /// </summary>
    /// <param name="subDomain">The sub domain.</param>
    /// <param name="url">The URL.</param>
    /// <param name="routeHandler">The route handler.</param>
    public SubDomainRoute(string subDomain, string url, IRouteHandler routeHandler) : base(url, routeHandler)
    {
      this.subDomain = subDomain.ToLower();
    }

    /// <summary>
    /// Returns information about the requested route.
    /// </summary>
    /// <param name="httpContext">An object that encapsulates information about the HTTP request.</param>
    /// <returns>
    /// An object that contains the values from the route definition.
    /// </returns>
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
      var url = httpContext.Request.Headers["HOST"];
      var index = url.IndexOf(".");

      if (index < 0)
      {
        return null;
      }

      var possibleSubDomain = url.Substring(0, index).ToLower();

      if (possibleSubDomain == subDomain)
      {
        var result =  base.GetRouteData(httpContext);
        return result;
      }

      return null;
    }

    /// <summary>
    /// Returns information about the URL that is associated with the route.
    /// </summary>
    /// <param name="requestContext">An object that encapsulates information about the requested route.</param>
    /// <param name="values">An object that contains the parameters for a route.</param>
    /// <returns>
    /// An object that contains information about the URL that is associated with the route.
    /// </returns>
    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
      // Checks if the area to generate the route against is this same as the subdomain
      // If so we remove the area value so it won't be added to the URL as a query parameter
      if(values != null && values.ContainsKey("Area"))
      {
        if(values["Area"].ToString().ToLower() == this.subDomain)
        {
          values.Remove("Area");
          return base.GetVirtualPath(requestContext, values);
        }
      }

      return null;
    }
  }
}

The next step we take is to create a bunch of extensions methods to make mapping the sub-domain a bit easier. I lifted this code straight from the MVC source and made a tiny adjustment.

namespace Your.App
{
  using System;
  using System.Diagnostics.CodeAnalysis;
  using System.Web.Mvc;
  using System.Web.Routing;

  public static class RouteCollectionExtensions
  {
    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, null /* defaults */, (object)null /* constraints */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, defaults, (object)null /* constraints */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults, object constraints)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, defaults, constraints, null /* namespaces */);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, string[] namespaces)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, null /* defaults */, null /* constraints */, namespaces);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults, string[] namespaces)
    {
      return MapSubDomainRoute(routes, name, subDomain, url, defaults, null /* constraints */, namespaces);
    }

    [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",
        Justification = "This is not a regular URL as it may contain special routing characters.")]
    public static Route MapSubDomainRoute(this RouteCollection routes, string name, string subDomain, string url, object defaults, object constraints, string[] namespaces)
    {
      if (routes == null)
      {
        throw new ArgumentNullException("routes");
      }
      if (url == null)
      {
        throw new ArgumentNullException("url");
      }
      if (subDomain == null)
      {
        throw new ArgumentNullException("subDomain");
      }

      Route route = new SubDomainRoute(subDomain, url, new MvcRouteHandler())
      {
        Defaults = new RouteValueDictionary(defaults),
        Constraints = new RouteValueDictionary(constraints)
      };

      if ((namespaces != null) && (namespaces.Length > 0))
      {
        route.DataTokens = new RouteValueDictionary();
        route.DataTokens["Namespaces"] = namespaces;
      }

      routes.Add(name, route);

      return route;
    }
  }
}

The final thing to do is set up your routes in the AreaRegistration class

context.Routes.MapSubDomainRoute(
        "Admin_default", // Name
        "admin", // SubDomain
        "{controller}/{action}/{id}", // Url
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Defaults
        new[] { typeof(Controllers.HomeController).Namespace }); // Namespace

Look familiar?

The namespace section is used to distinguish between Identically name controllers, so if you have a home controller in two areas that line will stop any conflicts.

There is one last item to take note of, when you create a new action in a controller of an area you’ll need to specify the location of the view. If your using the MvcContrib like we do then the T4MVC template comes in vary handy. All the Actions in the areas now look something like this:

    public virtual ActionResult Index()
        {
            return View(this.Views.Index);
        }

Or if you’re not using the T4MVC then this:

    public virtual ActionResult Index()
        {
            return View("~/Areas/Admin/Views/Home/Index.aspx");
        }
Code

Find the transparent pixels in an image – WPF

Extracted from: http://random.tonywilliams.me.uk/post/392778744/find-the-transparent-pixels-in-an-image-wpf

The other day I had to create an image element that contained a png with transparent sections and have it display a hand cursor when the mouse was over the opaque sections.

The first thing I tried (and failed) was to have an image element with the cursor property set to “Hand” like so:

<Image Source="{Binding SomeImage}" Cursor="Hand" />

That obviously never worked so I was forced to look at each individual pixel and see if it was transparent. What I ended up with was a function that generated a bunch of coordinates.

This is that function:

private static Dictionary<Point, object> FindTransparentPixelCoordinates(BitmapSource source)
{
  var points = new Dictionary<Point, object>();

  // Convert the source if the pixel format is not what we expect
  if (source.Format != PixelFormats.Bgra32)
  {
    source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0);
  }

  int width = source.PixelWidth;
  int height = source.PixelHeight;
  var bytes = new byte[width * height * 4];

  source.CopyPixels(bytes, width * 4, 0);

  var position = 0;

  for (var y = 0; y < height; y++)
  {
    for (var x = 0; x < width; x++)
    {
      var byteOffset = position;

      // The pixel format is stored as 32-bits (4 bytes) with the last byte being the alpha

      if (bytes[byteOffset + 3] == 0)
      {
        points.Add(new Point(x, y), null);
      }

      position += 4;
    }
  }

  return points;
}
Code

Clickonce Manifest Problem with .Net 4

This post is a little test with the StackTack app. It’s about my question on StackOverflow regarding ClickOnce manifest problem.

Code

Share sessions between asp.net apps

From my StackOverFlow answer.

If you want to share sessions between different apps there are a few things you need to do.

First you’ll need to run the session state in SQL mode.
At this point I found out that the SQL session state takes the machine key and your _appDomainAppId to generate a key for your app to access it’s own session data. So we need to keep these the same between all your apps.

In the web configs of your apps you’ll need to use the same machine key. This can be any where inside the system.web tags E.G:

    <machineKey decryptionKey="EDCDA6DF458176504BBCC720A4E29348E252E652591179E2" validationKey="CC482ED6B5D3569819B3C8F07AC3FA855B2FED7F0130F55D8405597C796457A2F5162D35C69B61F257DB5EFE6BC4F6CEBDD23A4118C4519F55185CB5EB3DFE61"/>

Add an appSetting “ApplicationName” and give it name (this has to be the same for both apps)
You’ll then need to create a shared session module which will change the _appDomainAppId. The one below is what I use.

    namespace YourApp
{
  using System.Configuration;
  using System.Reflection;
  using System.Web;

  /// <summary>class used for sharing the session between app domains</summary>
  public class SharedSessionModule : IHttpModule
  {
    #region IHttpModule Members
    /// <summary>
    /// Initializes a module and prepares it to handle requests.
    /// </summary>
    /// <param name="context">An <see cref="T:System.Web.HttpApplication"/>
    /// that provides access to the methods,
    /// properties, and events common to all application objects within an ASP.NET
    /// application</param>
    /// <created date="5/31/2008" by="Peter Femiani"/>
    public void Init(HttpApplication context)
    {
      // Get the app name from config file...
      string appName = ConfigurationManager.AppSettings["ApplicationName"];
      if (!string.IsNullOrEmpty(appName))
      {
        FieldInfo runtimeInfo = typeof(HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
        HttpRuntime theRuntime = (HttpRuntime)runtimeInfo.GetValue(null);
        FieldInfo appNameInfo = typeof(HttpRuntime).GetField("_appDomainAppId", BindingFlags.Instance | BindingFlags.NonPublic);
        appNameInfo.SetValue(theRuntime, appName);
      }
    }

    /// <summary>
    /// Disposes of the resources (other than memory) used by the module that
    /// implements <see cref="T:System.Web.IHttpModule"/>.
    /// </summary>
    /// <created date="5/31/2008" by="Peter Femiani"/>
    public void Dispose()
    {
    }
    #endregion
  }
}

In the web config you’ll need to add this module:

      <add name="SharedSessionModule" type="YourApp.SharedSessionModule, YourApp, Version=1.0.0.0, Culture=neutral" />

Final thing to do is to allow the session cookie to pass between domains…like so

  var session = HttpContext.Current.Session;
  var request = HttpContext.Current.Request;
  var cookie = request.Cookies["ASP.NET_SessionId"];
  if (cookie != null && session != null && session.SessionID != null)
  {
    cookie.Value = session.SessionID;
    cookie.Domain = "yourappdomain.com";

    // the full stop prefix denotes all sub domains
    cookie.Path = "/"; // default session cookie path root
  }

And that should do the trick.