Author Archives: Tony

AttemptIt – An F# computation expression for Railway Oriented Programming

For a while now I’ve been advancing my F# knowledge in various ways, one of those ways was to create a computation expression. As well as that I also wanted to release a useful nuget package and to add more open source software to the world.

While learning F# I found this article on railway oriented programming which I found quite effective in my day to day development. Finding no existing code/nuget packages that already had this I decided to create me own.

AttemptIt

The ReadMe file is vary basic for now but it should give you the general idea I’m trying for. Essentially an “attempt” represents a computation that is either a success or a failure; this can then be evaluated in to a “result”.

The syntax for now should let you bind from other attempts and bind from other results.

A quick reminder of the syntax:

//Basic usage
let doThis = attempt {
    let! x = someFunc()
    let! y = someOtherFunc y
    return! finalFunc y
}

//Catching Exceptions
let exceptionHandler (e:exn) -> Fail e.Message
let tryThis = Attempt.Catch exceptionHandler doThis

//Evaluating
let result = Attempt.Run tryThis

The plans for the not so distant future are:

  • Add Async helpers (Async<Attempt<‘a,’b>> gets award to work with I find)
  • Extend the syntax (for, while etc)
  • Add customer operators (check out “doublemap” in the railway programming link)
  • Get Travis-CI building this
  • Add more tests

This is also my second publicly available F# project and any comments on the code would be grateful.

Keeping an F# console window open

I’m starting out in F# 3.0 and playing with a console app. Annoyingly the window keeps closing but on various videos it’s still open.

To get round this (like in a C# console app) you need to read from the input.

Like so

System.Console.ReadLine() |> ignore

This will wait until we enter something from the console and then ignore the result.

Thomas The Tank Engine style coding

If you’ve developed software using MVC before then you’ll know the importance of keeping your controllers thin (there are many blog posts by other people on this subject, google it).

I think we should therefore add a new term to our already rich nomenclature in reference to the code smell for fat controllers.

 

**EDIT**:

Although the new thomas has a thin controller so maybe we can use OldThomas and NewThomas?

 

UnitOfWork Attribute for WebAPI

In one of my previous post I mentioned the UnitOfWork concept and created an attribute for asp.net MVC which creates a transaction and wraps an entire request inside.  The MVC attribute closed it’s transaction after the view has rendered, this runs on the OnResultExecuted method.

In WebApi how ever there is no method that is fired after the response has been serialised. This may not seem like a problem; however, if you are returning a collection as IEnumerable<> from an ApiController or anything that lazily executes from you then then unit of work will closes it’s transaction BEFORE you’ve pulled back your data. So far the only way I’ve found to get around this problem is instead to return an IList<> which forces the execution.

Below is a the UniOfWork attribute I’ve been using for WebApi, it also rolls back the transaction if an exception occurs as oppose to the MVC way.

 

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
  public sealed class UnitOfWorkFilter : ActionFilterAttribute, IExceptionFilter
  {
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
      var unitOfWork = (IUnitOfWork)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUnitOfWork));

      unitOfWork.EndTransaction();
    }

    public override void OnActionExecuting(HttpActionContext actionExecutingContext)
    {
      var unitOfWork = (IUnitOfWork)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUnitOfWork));
      unitOfWork.BeginTransaction();
    }

    public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
    {
      var unitOfWork = (IUnitOfWork)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUnitOfWork));
      unitOfWork.RollBack();
      return Task.Run(() => { }, cancellationToken);
    }
  }

Thoughts on REST/HATEOAS Collections and the Range Header

Recently I’ve been building a lot of APIs (using the WebApi framework) and have been focusing on REST (that is proper REST with HATEOAS and other things); however I’ve been trying to come to terms in how to best represent collections, or more specifically paged collections.

I’ve been using the O’Reilly RESTful Web Services cookbook kindle edition as a reference on building REST Apis and in section 3.7 How to Design Representations of Collection (p59-60) it gives a solution to represent collections which includes links to the previous/next page and a total attribute along with the actual data. To me this doesn’t feel right; perhaps it’s because of the skip/take in the query parameter or maybe the returning data isn’t exactly a collection but a page of a collection (I’m probably been way to pedantic here). This way maybe fine for some people and still considered RESTful but I’d like to explore alternatives first.

Range Header

This stackoverflow question lead me to the use of the Range Header using a custom range unit (items seems to be quite a common example) which returns a Http Status code of 206 (Partial Content) and a Content-Range Header that includes the total number of items.

Do a count

This approach seems to be more RESTful than the book example and takes advantage of what Http specification  has to offer. I can send a HEAD request with the Range header of “items 0-0″ and get back just the Content-Range; in other words I can do a count and then determine the best paging size to apply (if I need to at all). Something that the previous solution doesn’t cater for.

Bundling single & multiple files in a view for MVC 3/4

If you have been following the development of asp.net mvc 4 you’ll be aware of the new bundling/minification feature; I won’t go in to detail how it works or how to use it as there are plenty of other sources for that.

I’m working on an existing MVC 3 project that is quite large has has a mixture of css, less and js dotted about with a minification system that works ok; so I was looking for a way to use the the new bundling feature in the existing project. Luckily the feature is available on nuget via the Microsoft.Web.Optimization package and there is a project called Bundle Transformer that extends the functionality.

The problem arises in registering a new bundle, the existing organisation doesn’t allow the use of the dynamic folder bundle and the front end devs want to avoid writing back end code as much as possible.

To solve this problem I developed a small bit of code that allows you to register a bundle right in the view (this is assuming you are following the Bundle Transformer documentation and have a “BundleConfig.cs” file in the App_Start folder):

 private static void RegisterBundle(string virtualPath, bool css, params string[] files)
    {
      var existing = BundleTable.Bundles.GetBundleFor(virtualPath);
      if (existing != null)
      {
        return;
      }

      var newBundle = new Bundle(virtualPath);
      foreach (var file in files)
      {
        newBundle.Include(file);
      }

      var nullOrderer = new NullOrderer();
      newBundle.Orderer = nullOrderer;

      if (css)
      {
        var cssTransformer = new CssTransformer();
        var cssMinifier = new CssMinify();
        newBundle.Transforms.Add(cssTransformer);
        newBundle.Transforms.Add(cssMinifier);
      }
      else
      {
        var jsTransformer = new JsTransformer();
        var jsMinifier = new JsMinify();
        newBundle.Transforms.Add(jsTransformer);
        newBundle.Transforms.Add(jsMinifier);
      }

      BundleTable.Bundles.Add(newBundle);
    }

    public static IHtmlString RegisterScript(string virtualPath, params string[] files)
    {
      RegisterBundle(virtualPath, false, files);
      return Scripts.Render(virtualPath);
    }

    public static IHtmlString RegisterStyle(string virtualPath, params string[] files)
    {
      RegisterBundle(virtualPath, true, files);
      return Styles.Render(virtualPath);
    }

    public static IHtmlString RegisterScriptUrl(string virtualPath, params string[] files)
    {
      RegisterBundle(virtualPath, false, files);
      return Scripts.Url(virtualPath);
    }

    public static IHtmlString RegisterStyleUrl(string virtualPath, params string[] files)
    {
      RegisterBundle(virtualPath, true, files);
      return Styles.Url(virtualPath);
    }

And now the front end devs can register a bundle in the view:

@BundleConfig.RegisterStyle("~/css/common-loggedin",
    "~/Content/less/global.less",
   "~/Content/css/transforms.css",
   "~/Content/css/ui-darkness/jquery-ui.custom.css",
   "~/Content/css/jquery.qtip.css" ,
   "~/Content/css/chosen.css" 
   )
	<link rel="stylesheet" href="@BundleConfig.RegisterStyleUrl("~/css/print","~/Content/less/print.less")" media="print" />

 @BundleConfig.RegisterScript("~/script/application",
        "~/Content/js/application.js"  , 
        "~/Content/js/thap/notifications.js"   
    )

The first parameter defines the bundle name, the rest are the files you want to include.

Project Euler: Problem 4

Problem:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.

Find the largest palindrome made from the product of two 3-digit numbers.

Source: http://projecteuler.net/problem=4


Solution:

Before we can being to solved the problem above we first must answer the questions raised by it. In other words:

  • Palindromic Number?

 

Palindromic Number?

A palindromic number a number that is a palindrome, which is just a word or phrase that is the same in either direction.

 

Code:

Source: https://bitbucket.org/TWith2Sugars/project-euler/src/dbd1afaa7fc6/python/4.py

def isPalindrome(n):
    return (n==n[::-1])

def findLargestPalindrome():
    largest = 0
    for x in range(100,1000):
        for y in range(100,1000):
            product = x*y

            if product > largest and isPalindrome(str(product)):
                largest = product
    return largest

print(findLargestPalindrome())

 

IsPalindrome

This method is what is responsible for checking if a number is a palindrome; the “[::-1]” is what takes the parameter and reverses it. That’s it!

 

Unit of Work, NHibnernate and Asp.Net MVC

In a previous post I mentioned for some projects I’m using a combination of NHibernate, unit of work and asp.net mvc; this post will give an example of how I set this up for a project and how to get mvc to automatically create instances of UoW, wrap our code in transactions and clean up after it’s self via ActionFilterAttributes. Some of the code I have is a modified version of this but probably not as nice.

Here is a list of the interfaces that’ll be created:

And classes that implement them:

And finally the mvc Attribute: UnitOfWorkFilter.

This maybe(is) a lot of work for for something that seems pretty straight forward but it allows the code to be decoupled and makes testing much easier.  For example a project I’ve been working on uses this workflow and has a windows service to do some back end processing; by creating a RequestState to work with a windows service the rest of the code doesn’t need changing (apart from the filter obviously.)

I’ll leave the code further down in the post so things don’t get messy.

Actually using this setup.

This post makes the assumption that your data access is all via nhibernate and you’re using the repository pattern or something similar. Your repositories will need access to the IActiveSessionManager. If you’re using a DI like Ninject it should pass it through for you.

In your repository you can access the nhibernate session like so:

this.activeSessionManager.GetActiveSession();

I personally have a property to do this for me:

    public ISession Session
    {
      get
      {
        return this.activeSessionManager.GetActiveSession();
      }
    }

From here on do what ever queries you need, all the repositories in the will share the same session during the same request.

Applying the attribute

You can either have the UnitOfWorkFilter attached to each controller/method or in the global.asax you can register is as a global filter.

 [UnitOfWorkFilter]
  public class UserController : Controller
{
}

or

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
      filters.Add(new UnitOfWorkFilter());

    }

That’s it!.

How it all fits together

Imagine you have a controller that gets you a list of users (UserController).

  1. You issue a GET to the controller action
  2. The UnitOfWorkFilter kicks in and starts a new transaction from the ActiveSessionManager (The same manager your repo’s use)
  3. The ActiveSessionManager checks for/creates a new nhibernate session to work with
  4. Your repos use this ActiveSessionManager/NHibernate session to get its data
    1. If you have more than one repo in the controller action then no new sessions are created, the same one is shared.
  5. The controller returns the users
  6. The UnitOfWorkFilter then commits the transaction and closes the current session
    1. If something goes wrong like an exception the the UnitOfWorkFilter rollsback the transaction – preserving the integrity of the database

Below is the code to implement this.

IUnitOfWork

  public interface IUnitOfWork : IDisposable
  {

    void BeginTransaction();

    void EndTransaction();

    void RollBack();
  }

IRequestState

  public interface IRequestState
  {
    T Get<T>(string key);

    void Store(string key, object something);
  }

ISessionProvider

The ISession is the NHibernate session.

  public interface ISessionProvider
  {
    ISession Create();
  }

IActiveSessionManager

  public interface IActiveSessionManager: IDisposable
  {
    ISession GetActiveSession();

    void ClearActiveSession();

    bool HasActiveSession { get; }
  }

UnitOfWork

/// <summary>
  /// An nhibernate specific implementation of the unit of work concept
  /// </summary>
  public class UnitOfWork : IUnitOfWork
  {
    private readonly IActiveSessionManager sessionManager;

    private ITransaction transactionScope;

    public UnitOfWork(IActiveSessionManager sessionManager)
    {
      this.sessionManager = sessionManager;
    }

    public void Dispose()
    {
      if (this.transactionScope != null)
      {
        this.transactionScope.Dispose();
      }

      this.sessionManager.Dispose();
    }

    public void BeginTransaction()
    {
      if (this.transactionScope != null)
      {
        throw new InvalidOperationException("Transaction already started; nested transactions are not supported");
      }

      this.transactionScope = this.sessionManager.GetActiveSession().BeginTransaction();
    }

    public void EndTransaction()
    {
      if (this.transactionScope == null)
      {
        throw new InvalidOperationException("No active transaction found");
      }

      if (!this.transactionScope.IsActive)
      {
        throw new InvalidOperationException("This transaction is no longer active");
      }

      try
      {
        this.transactionScope.Commit();
      }
      catch (Exception ex1)
      {
          this.RollBack();
      }
    }

    public void RollBack()
    {
      this.transactionScope.Rollback();
    }
  }

AspNetRequestState

  public class AspNetRequestState : IRequestState
  {
    public T Get<T>(string key)
    {
      return (T)HttpContext.Current.Items[key];
    }

    public void Store(string key, object something)
    {
      HttpContext.Current.Items[key] = something;
    }
  }

SessionProvider

Note that the session factory has not been configured, this is left up you to configure.

 public class SessionProvider : ISessionProvider
  {
    private static ISessionFactory sessionFactory;

    public SessionProvider()
    {
      if (sessionFactory == null)
      {
	    // Do your mhibernate configuration here
        var configration = new Configuration();
        sessionFactory = configration.BuildSessionFactory();
      }
    }

    public ISession Create()
    {
      return sessionFactory.OpenSession();
    }
  }

ActiveSessionManager

public class ActiveSessionManager : IActiveSessionManager
  {
    private const string sessionKey = "_currentSession";

    private readonly IRequestState requestState;

    private readonly ISessionProvider sessionProvider;

    public ActiveSessionManager(IRequestState requestState, ISessionProvider sessionProvider)
    {
      this.requestState = requestState;
      this.sessionProvider = sessionProvider;
    }

    public ISession GetActiveSession()
    {
      if (this.Current == null)
      {
        var newSession= this.sessionProvider.Create();
        this.Current = newSession;
        return newSession;
      }

      return this.Current;
    }

    public void ClearActiveSession()
    {
      this.Current = null;
    }

    public bool HasActiveSession
    {
      get { return this.Current != null; }
    }

    protected virtual ISession Current
    {
      get
      {
        return requestState.Get<ISession>(sessionKey);
      }
      set
      {
        requestState.Store(sessionKey, value);
      }
    }

    public void Dispose()
    {
      var session = this.Current;
      if(session != null)
      {
        session.Dispose();
        this.ClearActiveSession();
      }
    }
  }

 

UnitOfWorkFilter

 

public class UnitOfWorkFilter : ActionFilterAttribute
  {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      var unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>();
      unitOfWork.BeginTransaction();
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
      var unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>();
      unitOfWork.EndTransaction();
    }
  }

How to enable CORS in Asp.Net

CORS is a method of allowing calls from one domain to another that would otherwise be forbidden due to same origin policy. There are many ways to enable this to allow asp.net to respond to these types of request and the method below allows calls from any domain. This might not be right for every application but it’s a quick way to get started.

In the apps web.config add the following section:

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>

Clustering RabbitMQ Windows

I recently had to set up a RabbitMQ cluster in windows on AWS , these are just some notes so I can remember what I did. Hopefully it might help others too.

  • Open ports on the machines for the cluster
  • Set the port for the server.bat and service.bat (can be found in C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-{VERSION})
  • Set the .erlang.cookie file to be the same value on all machines (Can be found in c:/windows and c:/user/{USER})
  • Use the following commands to set up the cluster.

And that should do it.

I should really have written this down when I set it up and not 2 months later.