Monday, 8 February 2016

Azure - Web Apps Summary & Cheat Sheet

Over the past month I've been studying towards MCP, Microsoft Azure Developer Specialist certification. I have learned a lot, so I have decided to summarise and visualise the key points.

Features vs Tier


Azure web apps feature vs tier

  • Free - Shared and limited compute, all you get is an Azure URL, some CPU time and access to Kudu to view logs, console, environment information,  processes, web jobs, etc. 
  • Shared  - Shared, limited, but scalable compute, you can even have your own domain name pointing to it.
  • Basic - Dedicated and scalable compute, at this level you are paying per VM and not per web app (more on that later), hence the price jump. This tier is packed with features. 
  • Standard - Dedicated and auto scalable compute with backups and slots for partial traffic routing, quality assurance or seamless upgrades by swapping slots. 
If you are thinking of moving your web apps to the Azure and not sure if it makes sense financially, then you should read Penny Pinching in the Cloud: When do Azure Websites make sense.

What should you know about web apps?


Azure Web Apps Topology


  1. Slots - Standard tier unlocks slot feature. Each web app can have 4 slots and 1 production slot. These non-production slots don’t scale and they tend to reside on the main VM, in our case these slots will remain on WEBVM1. These slots act like production slots and you can have web jobs running inside them. This can be an issue if your application is not designed for multi job processing. To prevent your web job from running just update the config by adding WEBJOBS_STOPPED = 1 to the app settings. Slots are on the same server so don’t do performance testing against them as you will impact performance of the entire VM. If you need to do some performance testing then it would be better to create a new service plan and deploy your web app in to it, this will ensure isolation.
  2. App Service Plan - This is a very powerful feature and it becomes very handy once you go above shared tier. Beyond shared tier you get dedicated compute i.e. your own VM. App service plan = Websites, Features & VM(s) grouping. You pay for a service plan. However when it comes to shared tier you pay per website inside the app service plan. Once you go beyond shared service plan you start paying for VM(s) and not websites. This is important to remember as it can save you a lot of money! So it’s cheaper to pay for 2 websites on a shared service plan (as you not paying for VMs at that point), however it’s much cheaper to pay for 25 websites on a basic service plan as they will be hosted together on a VM.
  3. Dedicated VM - As mentioned above, you don’t get your own VM until you go beyond shared. This means that if you have bunch of websites on a shared tier they could have different IP addresses to each other. Once you upgrade to basic and beyond and if your web apps are inside the same app service plan they will be hosted on a same server and will have the same IP address.
  4. Scalability - When you scale your web app you are scaling the entire app service plan. This means that if you scale mywebsitea.com you are automatically scaling mywebsiteb.com. However you are not scaling any non-production slots. These slots will remain on the main VM, in our case these slots remain active on WEBVM1. To ensure that traffic gets distributed fairly ensure that Application Request Routing is disabled.
  5. Kudu - All web app slots come with Kudu. You can access it via https://{site name}.scm.azurewebsites.net. This tool allows you to execute PowerShell, view real time logs, processes, view environment config, etc.
  6. Web Jobs - Every web app comes with a web job. To see the trace logs just go to https://{site name}.scm.azurewebsites.net/azurejobs/#/jobs. Web jobs can be written in a lot of languages. They can be scheduled, queue triggered or executed on demand. These web jobs are stored inside the site/wwwroot/app_data/jobs and get executed inside the same application pool as the the main site. So if you are hosting mywebsite.com and it's using "application pool 1", well web job for that site will be using exactly the same application pool. Why is this significant? Performance and it seems that something in Azure hits some API that invokes the web job inside the IIS context. Just an interesting observation.


How does slot swap work?

Azure Web App Swap Analysis

"Swap" is not a best name for what actually happens, it should have been called reroute. Why reroute? Because files don't get copied anywhere, config doesn't swap either, all that happens is that host names get changed and specific settings get enforced, that is it. Let's take a closer look:
  1. IIS, App & Diagnostic config - In traditional IIS you could modify virtual directories, error pages, authentication, compression, etc (green box in the picture below) with Azure you can also configure diagnostics. 
  2. Target slot setting override - When you "swap" your config doesn't go anywhere, it stays in the same slot. However there could be a override if you have ticked "Slot setting". Let's say that mywebsite.com has an app setting WEBJOBS_STOPPED = 0 and mywebsite-staging.com app setting is WEBJOBS_STOPPED = 1. I've ticked "Slot setting", this way this setting will always remain the same in that slot. So when I click "swap" it will take mywebsite.com app setting for WEBJOBS_STOPPED and override app setting inside the mywesite-staging.com. Why? Because mywebsite-staging.com will soon become production and in production slot it must always be WEBJOBS_STOPPED = 0.
  3. Warmup - After the config has been overridden with some slot specific config app gets recycled and some external Azure client invokes the app by calling the root directory e.g. mywebsite.com/, this is done to warm up the app.
  4. Reroute - As soon as the website is warmed up IIS host names are changed at the site bindings level. 
  5. Source slot setting override - Now that we have a new production slot up and running the slot setting override is performed against the new staging site. This means that new staging will be down for few seconds while it's gets settings updated, recycled and it starts ups.
By now you should have learnt that app contents and config doesn't get swapped, it's just the host names that get swapped. If you have ticked "slot setting" it also performs specific config override.

For more detailed analysis of slot swap I throughly recommend reading How to warm up Azure Web App during deployment slot swap.

Bringing it all together 


Azure Billing, Resource and Containers Topology


  1. Azure Subscription - Resource and a billing container. You can create resources inside it that span across different regions.
  2. Resource group - Authorisation, billing and a resource container. You can put resources in to a resource group and give users access to just that resource group. 
  3. Sub resource group - Same as a resource group (see #2). 
  4. Service plan - Needs to be with in a subscription and a region. You can't have a service plan that spans across multi regions or subscriptions. 
  5. Region B - Can be used for disaster recovery and performance. To do this you will need to use Traffic Manager. 
  6. Traffic Manager - Used for traffic distribution, failover and routing users to closer region to reduce latency (performance). 
  7. Internal Load Balancer - Routes traffic to all of the available VMs.

Monday, 29 December 2014

Theory Of Constraints And Software Engineering (Improving the throughput)

About one year ago or so I was introduced to the Theory Of Constraints (TOC). It was one of the best things that have ever happened to me as a manager. It changed my view on everything,  It was all thanks to one of my colleagues coming back from a conference and ordering in a book called the "Phoenix Project", the only reason why I was excited about reading it was because of its funky cover (Figure 1).

Figure 1. Phoenix Project Book Cover
As soon as I started to read this book I was instantly hooked, I didn't know at the time that I was going to discover something very important.

In this article I will briefly talk about my understanding of TOC and how I have applied it at work.

Right, let's jump in.

Imagine for a second the following situation. You are an owner of a digital agency, your agency builds web applications only for e-commerce/marketing companies. The following disciplines work for your agency: 10 business analysts, 7 designers,  10 testers, 15 software engineers and 2 web developers. Due to type of work that this agency does (front-end heavy) it should be obvious to us that our constraint in this case will be our web developers. This means no matter how hard other disciplines will work the only work that will be actually shipped to our clients will be what web developers had time to work on. All other work that was done independently by other disciplines will be stored away, waiting for web developers to catch up. This means that your overall throughput is completely constrained by your web developers. 

Let's resolve above situation by using "TOC 5 Focusing Steps" (5FS):
  1. Identify - Find your constraint (you can use Kanban, Utilisation charts, etc), in our case web development is our constraint.
  2. Exploit - Now we need to find out exactly what process this discipline is following, what is making this disciplines life painful, is it a build server? Is IDE not working correctly? Are web developers too involved in the backend development and backend developers should be doing more? In other words offer all the help that you possibly can. Make sure that web developers have always some work to do, after all they are the constraint. 
  3. Subordinate - Make it all about your constraint, only do as much work as a constraint can handle and avoid at all cost the pile up of inventory, this means that disciplines before and after the constraint will be idle. This is not a problem, there will be a much bigger problem if these people are not idle! Now you will need to start to set work in progress limits with buffers, in TOC world it's known as "Drum-Buffer-Rope". 
  4. Elevate - Hire more people in, change the process, transfer some of the existing staff in to the constrained discipline, do what ever you can to break this constraint.
  5. Repeat - By now your constraint should have been broken, so you need to find your next constraint. Don't allow inertia to become a system constraint. 
This video does a great job demonstrating TOC. TOC also focuses on inventory and throughput accounting, I am not going to talk about throughput accounting but I am going to talk about inventory.

Inventory in software engineering is the following:
  • Work In Progress (anything that is being developed in the current iteration)
  • Unassembled or partially assembled work (POCs, Shelved code, Designs, Wireframes, Business requirements, etc)
  • Backlog items / Requirements / Bugs


Figure 2. Lots Of Inventory = Lots Of Waste
This is what happens when you have lots of inventory in the system:
  1. What was produced is no longer needed.
  2. What was produced was wrong.
  3. Need to juggle lots of work at the same  time (context switching / multi-tasking).
  4. What was produced needs to be relearnt again.
  5. It becomes extremely hard to keep track of versions, projects and roadmaps. More processes and bureaucracy will be added to keep everything under "control".
As inventory builds up, waste builds up and it compounds the problem.

One of the ways to remove inventory build up is by cutting out "hand-shake / handover" periods between different disciplines. For this to happen teams need to work together as one unit delivering shippable software every iteration. In the Agile world these teams are also known as feature teams (multidisciplinary teams) they produce inventory just-in-time.

After reading lots about TOC I as a Product Owner have decided to give it a try with one of my feature teams at work.

Here is how we have applied TOC and some other good practices:
  • We have acknowledged testers as our constraint, these guys had to do manual and automation testing (Identify).
  • We have helped them by identifying what problems they were facing most often, in our case it was a build server was taking too long to build and to publish the latest application (Exploit).
  • We have knowingly created a bit of inventory for the next iteration each time, this way testing had something to work on straight away as soon as iteration started, this ensured that they are busy at all times (Exploit).
  • To deliver to testing team faster we have broken our requirements down, this ensured continuous flow (Exploit).
  • Testing was in the loop at all times so there were no surprises with requirements (Communication).
  • We never undertook any work that was vague or unknown (Risk reduction).
  • If we couldn't estimate work or write down a good acceptance criteria for it (because it was unknown) we would create a time boxed investigation task (Risk reduction).
  • If there was a quality issue or something unknown came up during development, team would stop the line and get an answer immediately (Communication).
  • Certain type of work would be done in different parts of iteration, for example at the end of iteration testers would be regression testing, this was an ideal time for other disciplines to do some infrastructure work or training (Subordinate).
  • We did only as much work as testing team could handle (Subordinate).
  • We were looking to hire more testers (Elevate).

Figure 3. Stop The Line.

Above steps have really helped us to improve our throughput, but it also did way more than that. This team was:
  • One of the most efficient teams in the department.
  • Everyone always left on time / no one ever had to do overtime.
  • They have finished ahead of the schedule at worst they have finished on time.
  • As they have finished ahead or on time they had time to groom requirements and get ready for the next iteration (maybe even start work ahead of the schedule).
  • Team has gelled incredibly.
Of course none of this would not have been possible if I didn't have incredible people in the team, their personalities have played the key role.

Summary: 
  • Stop doing work upfront per discipline (creating inventory) and star to work together as one multi-disciplined team (feature team) by using continuous flow / just-in-time delivery.
  • Have your team deliver production ready software every iteration.
  • Break down your requirements in to small deliverables (continuous flow) to achieve full multi-disciplined team utilisation. 
  • Use Kanban board / Utilisation charts to visualise your constraints. 
  • Use TOC 5FS to increase your teams throughput.
  • Ensure that your constraint is never starved of work and is protected from distraction, inefficient processes and bureaucracy. 

Monday, 1 December 2014

Applied Domain-Driven Design (DDD), Part 0 - Requirements and Modelling

About a year ago I have written a series of articles about Domain-driven design, you can find the main article here. Looking back I've realised that I've committed the most typical mistake and started to code my business domain without requirements or any draft designs!

I am going to try and fix this, this is what I am going to do:
  • Identify User Stories 
  • Identify the Nouns in the user stories 
  • Identify the Verbs in the user stories 
  • Put together object interaction diagram
  • Put together object responsibilities diagram 
  • Put together class digram UML showing only interesting interactions 

So here are made up user stories:
  • As a customer I want to be able to put products that I want to purchase in to the shopping cart so that I can check out quickly later on
  • As a customer I want to see the total cost all for all of the items that are in my cart so that I see if I can afford to buy everything 
  • As a customer I want to see the total cost of each item in the shopping cart so that I can re-check the price for items
  • As a customer I want to see the total cost for all of the items in the shopping cart with total tax 
  • As a customer I want to be able to specify the address of where all of the products are going to be sent to
  • As a customer I want to be able to add a note to the delivery address so that I can provide special instructions to the postman
  • As a customer I want to be able to specify my credit card information during check out so that I can pay for the items
  • As a customer I want system to tell me how many items are in stock so that I know how many items I can purchase 
  • As a customer I want shopping cart to check that items are still available for purchase during a check out so that I can still purchase items that are in the cart
  • As a customer I want to receive order confirmation email with order number so that I have proof of purchase 
  • As a customer I want to specify invoice address for the order so that I can receive invoice for the order

Now I am going extract nouns and verbs from the stories above. I am looking for the nouns that will become my main objects and not the attributes.

Nouns: 
  • Customer
  • Item
  • Order
  • Shopping Cart
  • Address
  • Invoice
  • Delivery
  • Tax
  • Credit Card Information 

*Note: I've removed duplicates for better, more official names, for example Item = Product, Order = Purchase, etc.

Verbs:
  • Put products in to the shopping cart 
  • See total cost for all of the items
  • See total cost for each item
  • See total tax for my country 
  • Specify delivery address
  • Specify delivery note for delivery address
  • Specify invoice address
  • Receive invoice for the order
  • Sent invoice
  • Specify credit card information 
  • Pay for the items
  • Tell me how many items are in stock
  • Check that items are still available during check out
  • Receive order confirmation email 

By using above nouns and verbs we can put together a diagram such as this:
[Figure 1] Object Interaction Diagram 

Once we have object interaction diagram we can start thinking about object responsibilities. One of the most common mistakes is to push responsibilities on to the actor object i.e. Customer. We need to remember that objects must take care of themselves and objects need to be closed for direct communication and that you need go through the functions to communicate with them.

So let's follow above approach and assign responsibilities:

[Figure 2] Object Responsibilities Diagram 

Now that we have object interaction and responsibilities diagram in place we can start thinking about lower level UML class diagram:


[Figure 3] UML Diagram

Figure 3 shows methods, class names, dependencies, interfaces and composition. I've took a bit of time and reflected only on the most complex / interesting parts of the model. I will worry about attributes and other details later on, detail will naturally emerge when I start coding. Figure 3 is suppose to be a rough sketch, that is all, teams can whiteboard Figure 3 during a meeting, take a picture and distribute it to everyone in the team and get on with the actual coding. After a week or so picture will be forgotten and the parts of the above model (that have been useful) will live and breath in the actual code.

Now my made up user stories can be modelled in my many different ways and Figure 3 is just my interpretation of it. Key thing is to think about what you are building first, don't just jump in and start coding and don't get carried away with detail either (attributes, constructors, etc) focus on interesting and complex parts first.

Summary:
  • Don't start doing anything until you have requirements, if you don't have a BA in the company that's fine, you will have to do BA's job and identify requirements first.
  • Don't just jump in to the code soon as you have requirements, put together object interaction and responsibilities diagrams first. 
  • When you have identified your objects, interactions and responsibilities use UML class diagrams to put together a draft model (whiteboard sketch will do).
  • Don't try to model the reality of the world, model the reality of your organisation. Different companies will have different objects, in one company "address" might be an object and you might have "address type" coming of it (invoice, shipping, etc), in another company there will be "invoice address", "shipping address" and "seller address" object, that company might need these objects as these objects will inherit from the base "address" object. Remember it is all about your business domain and not the actual "reality".

Useful links:

Tuesday, 14 January 2014

Solution for MVC Ajax.BeginForm throwing SecurityPermission due to medium trust Level

I've written a very simple MVC 5 application and deployed it to my 1and1 hosting provider. Immediately I was struck by an error. I've forgotten that 1and1 like many other hosting providers enforce medium trust level.

I've gone to my local project and modified the config to simulate this problem locally. Line of code that threw an error was:
@using (Ajax.BeginForm("GetInTouch", "Home", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "makeContact"}))
{

}

Stack trace:
 
Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed

at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
    at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark)
    at System.Security.CodeAccessPermission.Demand()
    at System.Web.HttpContext.System.IServiceProvider.GetService(Type service)
    at System.Web.HttpContextWrapper.GetService(Type serviceType)
    at System.Web.WebPages.UrlRewriterHelper.IsUrlRewriterTurnedOn(HttpContextBase httpContext)
    at System.Web.WebPages.UrlRewriterHelper.WasRequestRewritten(HttpContextBase httpContext)
    at System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath)
    at System.Web.WebPages.UrlUtil.GenerateClientUrl(HttpContextBase httpContext, String contentPath)
    at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
    at System.Web.Mvc.Ajax.AjaxExtensions.BeginForm(AjaxHelper ajaxHelper, String actionName, String controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary`2 htmlAttributes)

I was shocked 1and1 hosting provider said that they support MVC 3 and 4, .NET Framework 3.5 and 4. All I did was build a super simple website with a contact form. What's happening?

Line System.Web.HttpContext.System.IServiceProvider.GetService(Type service) indicates that it's using some kind of a internal dependency injection. Dependency injection normally uses reflection to build objects, reflection is not supported in medium trust environments.

Taking a closer look at the stack trace we see that it's using System.Web.WebPages.UrlUtil.GenerateClientUrl(HttpContextBase httpContext, String contentPath). It's using Html.BeginForm(method, controller) to build the URL for the form.

Now, we identified the problem, where and why it's happening. So what's the solution? Not to use helpers? Create your own helpers? These are all possible solutions. Luckily, I am using Ajax helper so I can get away with the following for now:

@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "makeContact", Url = "Home/GetInTouch"}))
{

}

As URL is specified manually (Url = "Home/GetInTouch") it's not going to try and generate it. This still leaves us with other problems.

You can't use Html.BeginForm(action, controller) as it's going to try and resolve these URL's. If you go with Ajax solution above and client has no JavaScript nothing will happen, form action will point to "/". This is not great, at least now you have an answer and a partial solution.

If you have found a better way around this, please do comment.

Wednesday, 18 December 2013

Unit Of Work Abstraction For NHibernate or Entity Framework C# Example

Unit Of Work is another great pattern that every software engineer needs to have in his tool box. So what's a purpose of Unit Of Work?

 “Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.” – Patterns of enterprise application architecture, Martin Fowler

Sounds like a lot of work, managing object state, relationships, concurrency and transactions can be cumbersome. However we are in luck, modern ORM's like NHibernate and Entity Framework support implicit Unit Of Work. In NHibernate it’s part of the ISession and in Entity Framework it’s part of the Context.

NHibernate
using(ISession session = sessionFactory.OpenSession()) 
using(ITransaction tx = session.BeginTransaction()) 
{ 
        Customer customer = new Customer { FirstName = "Peter" };
        session.Save(customer);
        tx.Commit(); 
} 

Entity Framework
using (SomeContext context = new SomeContext())
{
    Customer customer = new Customer { FirstName = "Peter" };
    context.Customer.Add(customer);
    context.SaveChanges();
}

ORM's have built in Unit Of Work, ideally these need to be abstracted away. Abstraction will allow us to move to a different ORM platform in the future and yield cleaner architecture. Lets take a look at the abstracted example:
Customer customer = new Customer { FirstName = "Peter"};
this.repositoryCustomer.Add(customer);
this.unitOfWork.Commit();

When it comes to working with databases it's important to read and write within a transaction scope. This ensures that there are no data inconsistencies, performance issues and second level cache is used. Please read this article for more information. So we need to open a transaction, but when do we do it?
  1. Open transaction manually in the service layer - Default Unit Of Work interface doesn't support .BeginTransaction, I don't believe it should be controlled by the user. Although this is a clean option.
  2. Open transaction on the page context creation - This feels dirty, each time some one hits your website your ORM will open a connection and begin a transaction. Not great for performance and is dangerous. 
  3. Open transaction in the repository on the first read or write - Best option, it's automatic, and the only down side is that there will be transaction null check each time (singleton). But you get cleaner service implementation.
In this article I am going to be focusing on point 3.

NHibernate Abstraction

Configuration Singleton
public static class NHConfigurationSingleton
    {
        private static Configuration configuration = null;
        private static object lockObj = new object();

        public static Configuration Configuration
        {
            get
            {
                lock (lockObj)
                {
                    if (configuration == null)
                    {
                        string[] resourceNames;
                        string nHResource = string.Empty;
                        Assembly[] asmArray = AppDomain.CurrentDomain.GetAssemblies();

                        foreach (Assembly asm in asmArray)
                        {
                            resourceNames = asm.GetManifestResourceNames();
                            nHResource = resourceNames.FirstOrDefault(x => x.ToLower().Contains("hibernate.config"));
                            if (!string.IsNullOrEmpty(nHResource))
                            {
                                using (Stream resxStream = asm.GetManifestResourceStream(nHResource))
                                {
                                    configuration = new Configuration();
                                    configuration.Configure(new XmlTextReader(resxStream));
                                }
                            }
                        }
                    }
                }

                return configuration;
            }
        }
    }

Session Factory Singleton
    public static class NHSessionFactorySingleton
    {
        private static ISessionFactory sessionFactory = null;
        private static object lockObj = new object();

        public static ISessionFactory SessionFactory
        {
            get
            {
                lock (lockObj)
                {
                    if (sessionFactory == null)
                    {
                        sessionFactory = NHConfigurationSingleton.Configuration.BuildSessionFactory();
                    }
                }

                return sessionFactory;
            }
        }
    }


Unit Of Work
    
public interface IUnitOfWork : IDisposable
    {
        void Commit();
        void Rollback();
    }

public class NHUnitOfWork : IUnitOfWork
    {
        private ISession session;
        private ITransaction transaction;
        public ISession Session { get { return this.session; } }

        public NHUnitOfWork() { }

        public void OpenSession()
        {
            if (this.session == null || !this.session.IsConnected)
            {
                if (this.session != null)
                    this.session.Dispose();

                this.session = NHSessionFactorySingleton.SessionFactory.OpenSession();
            }
        }

        public void BeginTransation(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
        {
            if (this.transaction == null || !this.transaction.IsActive)
            {
                if (this.transaction != null)
                    this.transaction.Dispose();

                this.transaction = this.session.BeginTransaction(isolationLevel);
            }
        }

        public void Commit()
        {
            try
            {
                this.transaction.Commit();
            }
            catch
            {
                this.transaction.Rollback();
                throw;
            }
        }

        public void Rollback()
        {
            this.transaction.Rollback();
        }

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

            if (this.session != null)
            {
                this.session.Dispose();
                session = null;
            }
        }
    }

Repository
  
public class NHRepository<TEntity> : IRepoistory<TEntity>
        where TEntity : IDomainEntity
    {
        readonly NHUnitOfWork nhUnitOfWork;

        public NHRepository(NHUnitOfWork nhUnitOfWork)
        {
            this.nhUnitOfWork = nhUnitOfWork;
        }

        public void Add(TEntity entity)
        {
            this.nhUnitOfWork.OpenSession();
            this.nhUnitOfWork.BeginTransation();
            this.nhUnitOfWork.Session.Save(entity);
        }

        public void Remove(TEntity entity)
        {
            this.nhUnitOfWork.OpenSession();
            this.nhUnitOfWork.BeginTransation();
            this.nhUnitOfWork.Session.Delete(entity);
        }

        public void Update(TEntity entity)
        {
            this.nhUnitOfWork.OpenSession();
            this.nhUnitOfWork.BeginTransation();
            this.nhUnitOfWork.Session.Update(entity);
        }
        
        public IEnumerable<TEntity> GetAll()
        {
            this.nhUnitOfWork.OpenSession();
            this.nhUnitOfWork.BeginTransation();
            return this.nhUnitOfWork.Session.Query<TEntity>();
        }
    }

Entity Framework Abstraction

Unit Of Work
 
   public class EFUnitOfWork : IUnitOfWork
    {
        DbContext context;
        DbContextTransaction transaction;
        public DbContext Context { get { return this.context; } }

        public EFUnitOfWork() 
        { 
            this.context = new ECommerceEntities();
        }

        public void OpenTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
        {
            if (this.transaction == null)
            {
                if (this.transaction != null)
                    this.transaction.Dispose();

                this.transaction = this.context.Database.BeginTransaction(isolationLevel);
            }
        }

        public void Commit()
        {
            try
            {
                this.context.SaveChanges();
                this.transaction.Commit();
            }
            catch
            {
                this.transaction.Rollback();
                throw;
            }
        }

        public void Rollback()
        {
            this.transaction.Rollback();
        }

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

            if(this.context != null)
            {
                this.context.Database.Connection.Close();
                this.context.Dispose();
                this.context = null;
            }
        }
    }

Repository
 
 public class EFRepository<TEntity> : IRepoistory<TEntity>
        where TEntity : class, IDomainEntity
    {
        readonly EFUnitOfWork unitOfWork;

        public EFRepository(EFUnitOfWork unitOfWork)
        {
            this.unitOfWork = unitOfWork;
        }

        public void Add(TEntity entity)
        {
            this.unitOfWork.OpenTransaction();
            this.unitOfWork.Context.Set<TEntity>().Add(entity);
        }

        public void Remove(TEntity entity)
        {
            this.unitOfWork.OpenTransaction();
            this.unitOfWork.Context.Set<TEntity>().Remove(entity);
        }

        public IEnumerable<TEntity> GetAll()
        {
            this.unitOfWork.OpenTransaction();
            return this.unitOfWork.Context.Set<TEntity>().ToList();
        }
    }

Example usage (see SQL trace output below)
    
public class CustomerService
    {
        readonly IUnitOfWork unitOfWork;
        readonly IRepoistory<Customer> repositoryCustomer;

        public CustomerService(IUnitOfWork unitOfWork, IRepoistory<Customer> repositoryCustomer)
        {
            this.unitOfWork = unitOfWork;
            this.repositoryCustomer = repositoryCustomer;
        }

  public CustomerDto Add(string firstName, string lastName)
        {
            int existingWithSameName = this.repositoryCustomer.GetAll()
                    .Count(customer => customer.FirstName == firstName && customer.LastName == lastName);

            if (existingWithSameName != 0)
                throw new Exception("User already exists with this name");

            Customer customerNew = new Customer(firstName, lastName);
            
            this.repositoryCustomer.Add(customerNew);
            this.unitOfWork.Commit();

            return new CustomerDto(customerNew.Id, customerNew.FirstName, customerNew.LastName);
        }

    }

NHibernate SQL Trace Output
To see exactly what's going on i've decided to go through SQL logs. It seems to behave correctly, it connects, starts a transaction, performs required operations, commits transaction and closes all connections.
2013-12-17 23:24:24.09 spid51      ODS Event: Login connection 51
2013-12-17 23:24:24.09 spid51      ODS Event: Remote_ods : Xact 0 ORS#: 1, connId: 0
2013-12-17 23:24:24.09 spid51      Xact BEGIN for Desc: 3300000001
2013-12-17 23:24:25.19 spid51      ODS Event: language_exec : Xact 3300000001 ORS#: 1, connId: 0
2013-12-17 23:24:25.19 spid51         Text:select customer0_.Id as Id0_, customer0_.FirstName as FirstName0_, customer0_.LastName as LastName0_ from ECommerce.dbo.Customer customer0_
2013-12-17 23:24:25.35 spid51      Parameter# 0: Name=,Flags=0,Xvt=231,MaxLen=166,Len=166,Pxvar Value=INSERT INTO ECommerce.dbo.Customer (FirstName, LastName, Id) VALUES (@p0, @p1, @p2)
2013-12-17 23:24:25.36 spid51      Parameter# 1: Name=,Flags=0,Xvt=231,MaxLen=116,Len=116,Pxvar Value=@p0 nvarchar(4000),@p1 nvarchar(4000),@p2 uniqueidentifier
2013-12-17 23:24:25.36 spid51      Parameter# 2: Name=@p0,Flags=0,Xvt=231,MaxLen=8000,Len=10,Pxvar Value=ZanNH
2013-12-17 23:24:25.36 spid51      Parameter# 3: Name=@p1,Flags=0,Xvt=231,MaxLen=8000,Len=14,Pxvar Value=70ba671
2013-12-17 23:24:25.36 spid51      Parameter# 4: Name=@p2,Flags=0,Xvt=36,MaxLen=16,Len=16,Pxvar Value=E5EF2FD7-532B-4CEA-80F4-8B095D1F983A
2013-12-17 23:24:25.36 spid51          IPC Name: sp_executesql
2013-12-17 23:24:25.36 spid51      ODS Event: execrpc : Xact 3300000001 ORS#: 1, connId: 0
2013-12-17 23:24:25.36 spid51      ODS Event: Remote_ods : Xact 3300000001 ORS#: 1, connId: 0
2013-12-17 23:24:25.36 spid51      Xact COMMIT for Desc: 3300000001
2013-12-17 23:24:27.71 Server      ODS Event: Exit spid 51
2013-12-17 23:24:27.71 spid51      ODS Event: Logout connection 51
2013-12-17 23:24:27.71 Server      ODS Event: Close conn 0 on spid 51

Entity Framework SQL Trace Output
2013-12-17 23:27:06.21 spid51      ODS Event: Login connection 51
2013-12-17 23:27:06.22 Server      Connection 0x00000001EE6433F0 connId:1, spid:51     New MARS Session 
2013-12-17 23:27:06.22 spid51      ODS Event: Remote_ods : Xact 0 ORS#: 1, connId: 1
2013-12-17 23:27:06.22 spid51      Xact BEGIN for Desc: 3300000001
2013-12-17 23:27:08.06 Server      Connection 0x00000001F2F317A0 connId:2, spid:51     New MARS Session 
2013-12-17 23:27:08.06 spid51      ODS Event: language_exec : Xact 3300000001 ORS#: 1, connId: 2
2013-12-17 23:27:08.06 spid51         Text:SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[FirstName] AS [FirstName], 
    [Extent1].[LastName] AS [LastName]
    FROM [dbo].[Customer] AS [Extent1]
2013-12-17 23:27:08.56 spid51      Parameter# 0: Name=,Flags=0,Xvt=231,MaxLen=154,Len=154,Pxvar Value=INSERT [dbo].[Customer]([Id], [FirstName], [LastName])
VALUES (@0, @1, @2)

2013-12-17 23:27:08.56 spid51      Parameter# 1: Name=,Flags=0,Xvt=231,MaxLen=102,Len=102,Pxvar Value=@0 uniqueidentifier,@1 varchar(256),@2 varchar(256)
2013-12-17 23:27:08.56 spid51      Parameter# 2: Name=@0,Flags=0,Xvt=36,MaxLen=16,Len=16,Pxvar Value=4318564C-304D-4792-85C5-F0113A873700
2013-12-17 23:27:08.56 spid51      Parameter# 3: Name=@1,Flags=0,Xvt=167,MaxLen=256,Len=5,Pxvar Value=ZanEF
2013-12-17 23:27:08.56 spid51      Parameter# 4: Name=@2,Flags=0,Xvt=167,MaxLen=256,Len=7,Pxvar Value=2c22266
2013-12-17 23:27:08.56 spid51          IPC Name: sp_executesql
2013-12-17 23:27:08.56 spid51      ODS Event: execrpc : Xact 3300000001 ORS#: 1, connId: 2
2013-12-17 23:27:08.58 spid51      ODS Event: Remote_ods : Xact 3300000001 ORS#: 1, connId: 1
2013-12-17 23:27:08.58 spid51      Xact COMMIT for Desc: 3300000001
2013-12-17 23:27:08.61 Server      ODS Event: Close conn 1 on spid 51
2013-12-17 23:27:08.61 Server      ODS Event: Close conn 2 on spid 51
2013-12-17 23:27:08.61 Server      ODS Event: Exit spid 51
2013-12-17 23:27:08.61 spid51      ODS Event: Logout connection 51
2013-12-17 23:27:08.61 Server      ODS Event: Close conn 0 on spid 51


We can pass NHUnitOfWork or EFUnitOfWork in to CustomerService and it will work as expected. Do avoid calling Unit Of Work within the Repository i.e. this.repositoryCustomer.Commit(), I've seen this a lot around the web. Unit Of Work should not be bound directly to it.

*Note: Code in this article is not production ready and is used for prototyping purposes only. If you have suggestions or feedback please do comment.


References: