Recent Articles
Repository and Unit of Work for Entity Framework (EF4) for Unit Testing
If you are not familiar with the Unit of Work pattern you should firt look at Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (9 of 10). It's a great article that demonstrates what the Unit of Work pattern can do.
Unfortunately, that article uses a different version of Entity Framework. I am using the default tools that come with Visual Studio and didn't want to modify the project too greatly so for me, the code wasn't usable. I also wanted to expose the IQueryable interface which as a side effect also simplified my Repository design.
By using a Repository Pattern you'll find unit testing is now possible and quite easy to write. This illustration (taken from asp.net) shows the differences between No Repository and the Repository Pattern. Notice how there are no Unit Tests in the No Repository section also note the "Alternative Persistence Medium" node (this is where our MemoryRepository comes in).

The Unit of Work
The job of the Unit of Work class is to manage the lifecycle and context of your Repositories. The class is pretty simple to create, implement IDisposable, add all your Repositories and give it a Save method.
This is what Northwind's Interface and Unit of Work class looks like:
(for the Repository code, check out my previous post: Generic IQueryable Repository for Entity Framework 4)
public interface INorthwindUnitOfWork : IDisposable { IRepository<Category> CategoryRepository { get; } IRepository<Customer> CustomerRepository { get; } IRepository<Employee> EmployeeRepository { get; } IRepository<Order> OrderRepository { get; } IRepository<Order_Detail> Order_DetailRepository { get; } IRepository<Product> ProductRepository { get; } IRepository<Shipper> ShipperRepository { get; } IRepository<Supplier> SupplierRepository { get; } void Save(); } public partial class NorthwindUnitOfWork : INorthwindUnitOfWork { private readonly NorthwindDataContext _context; private readonly IRepository<Category> _categoryRepository; private readonly IRepository<Customer> _customerRepository; private readonly IRepository<Employee> _employeeRepository; private readonly IRepository<Order> _orderRepository; private readonly IRepository<Order_Detail> _order_DetailRepository; private readonly IRepository<Product> _productRepository; private readonly IRepository<Shipper> _shipperRepository; private readonly IRepository<Supplier> _supplierRepository; public IRepository<Category> CategoryRepository { get { return _categoryRepository; } } public IRepository<Customer> CustomerRepository { get { return _customerRepository; } } public IRepository<Employee> EmployeeRepository { get { return _employeeRepository; } } public IRepository<Order> OrderRepository { get { return _orderRepository; } } public IRepository<Order_Detail> Order_DetailRepository { get { return _order_DetailRepository; } } public IRepository<Product> ProductRepository { get { return _productRepository; } } public IRepository<Shipper> ShipperRepository { get { return _shipperRepository; } } public IRepository<Supplier> SupplierRepository { get { return _supplierRepository; } } public NorthwindUnitOfWork(NorthwindDataContext context) { _context = context; _categoryRepository = new EntityRepository<Category>(_context); _customerRepository = new EntityRepository<Customer>(_context); _employeeRepository = new EntityRepository<Employee>(_context); _orderRepository = new EntityRepository<Order>(_context); _order_DetailRepository = new EntityRepository<Order_Detail>(_context); _productRepository = new EntityRepository<Product>(_context); _shipperRepository = new EntityRepository<Shipper>(_context); _supplierRepository = new EntityRepository<Supplier>(_context); } public void Save() { _context.SaveChanges(); } #region IDisposable Methods private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { _context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion }Unit Testing
(In this example I'm using Moq as my Mocking Framework)
I start by creating a method called GetMockCategoryRepository that creates a new MemoryRepository object and returns returns an IRepository<Category>. This will mimic the behavior of our Category Repository with an in memory list, allowing us to test without hitting the database.
private IRepository<Category> GetMockCategoryRepository() { var value = new MemoryRepository<Category>(); value.Add(new Category { Category_ID = 1, Category_Name = "Beverages" }); value.Add(new Category { Category_ID = 2, Category_Name = "Condiments" }); value.Add(new Category { Category_ID = 3, Category_Name = "Confections" }); return value; }Then in my test, I create a Mock INorthwindUnitOfWork, setup the CategoryRepository method to return my MemoryRepository and initialize a new NorthwindService object. For the Assert, we just need to check the count of items returned from the service is the same as our Repository!
[TestMethod] public void NorthwindService_GetCategories_returns_category_names() { // Arrange var mockUnitOfWork = new Mock<INorthwindUnitOfWork>(); var mockCategories = GetMockCategoryRepository(); mockUnitOfWork.SetupGet(x => x.CategoryRepository) .Returns(mockCategories); var northwindService = new NorthwindService(mockUnitOfWork.Object); // Act var categories = northwindService.GetCategories(); // Assert Assert.AreEqual(mockCategories.All().Count(), categories.Length); }Well, that's all you need. You are now ready to full unit test your Services, Controllers or anything else that accesses your database.
Generic IQueryable Repository for Entity Framework 4 (EF4)
Anyone who has tried to create tests with Entity Framework (EF) knows that EF is not very unit test friendly. I needed something simple, reusable and unit testable. this generic repository was the result.
The goal of this project was high reusability, ease of implementation and to be unit tests friendly.
There are a lot of Repository Pattern's out there that hide a lot of the underlying functions of your data access layer (in this case LINQ). Well, I really like LINQ to SQL and didn't want to hide any of that. Plus, if you really need encapsulation it should be done in your service layer and not your repository layer.
Some Quick Examples
remember to add "using System.Linq"
IRepository<Log> logs = new Repository<Log>(new MyDataContext()); // use LINQ var items = from l in logs.All() where l.LogType == "Error" orderby l.LogId descending select l; // load an item var item = logs.All().Single(l => l.LogId == 1); // update an item item.TimeStamp = DateTime.Now; logs.Update(item); logs.Save(); // create an item item = new Log { TimeStamp = DateTime.Now, LogType = "Information", Message = "This is a new Log!" }; logs.Add(item); logs.Save(); // delete an item logs.Remove(item); // Eager Loading items = from l in logs.All("Details") select l;Repository Code
The code is pretty simple, it just looks long because of all the Argument Validation...
public interface IRepository<E> { IQueryable<E> All(); IQueryable<E> All(string includes); void Add(E entity); void Remove(E entity); void Update(E entity); void Save(); } public class Repository<E> : IRepository<E> where E : EntityObject { protected readonly ObjectContext context; protected readonly ObjectSet<E> objectSet; public Repository(ObjectContext context) { #region Argument Validation if (context == null) { throw new ArgumentNullException("context"); } #endregion this.context = context; this.objectSet = context.CreateObjectSet<E>(); } public virtual IQueryable<E> All() { return objectSet; } public virtual IQueryable<E> All(string includes) { ObjectQuery<E> value = objectSet; if (String.IsNullOrEmpty(includes)) { foreach (var includeProperty in includes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { value = value.Include(includeProperty.Trim()); } } return value; } public virtual void Add(E entity) { #region Argument Validation if (entity == null) { throw new ArgumentNullException("entity"); } #endregion objectSet.AddObject(entity); } public virtual void Remove(E entity) { #region Argument Validation if (entity == null) { throw new ArgumentNullException("entity"); } #endregion if (entity.EntityState == EntityState.Detached) { objectSet.Attach(entity); } objectSet.DeleteObject(entity); } public virtual void Update(E entity) { #region Argument Validation if (entity == null) { throw new ArgumentNullException("entity"); } #endregion objectSet.Attach(entity); context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); } public void Save() { context.SaveChanges(); } }Unit Testing
Being able to write Unit Tests is a must and was one of the main goals of creating this repository. With this class, writing unit tests has become much more simple by creating a MemoryRepository.
public class MemoryRepository<E> : IRepository<E> where E : EntityObject { protected readonly List<E> objectSet = new List<E>(); public virtual IQueryable<E> All() { return objectSet.AsQueryable(); } public IQueryable<E> All(string includes) { return All(); } public virtual void Add(E entity) { objectSet.Add(entity); } public virtual void Remove(E entity) { objectSet.Remove(entity); } public virtual void Update(E entity) { } public void Save() { } }Here's an example test that shows how to populate the MemoryRepository.
[TestMethod] public void MemoryRepository_can_Add_entities() { // Arrange IRepository<Category> value = new MemoryRepository<Category>(); value.Add(new Category { Category_ID = 1, Category_Name = "Beverages" }); value.Add(new Category { Category_ID = 2, Category_Name = "Condiments" }); value.Add(new Category { Category_ID = 3, Category_Name = "Confections" }); // Act int result = value.All().Count(); // Assert Assert.AreEqual(3, result); }Be sure to check out Part 2: Repository and Unit of Work for Entity Framework (EF4) for Unit Testing
Setting up Visual Studio 2010 and IIS Express
Why use IIS Express over the Visual Studio Development Server (Cassini)?
I've seen Cassini run inconsistently on different machines, which resulted in the developers having to setup IIS on their local machines which also didn't end up working because they weren't all running the same OS.
Cassini doesn't support the <system.webServer /> node in your config file, which can also give inconsistent results when deployed.
Here are the reasons Scott Guthrie gives:
- It’s lightweight and easy to install (less than 10Mb download and a super quick install)
- It does not require an administrator account to run/debug applications from Visual Studio
- It enables a full web-server feature set – including SSL, URL Rewrite, Media Support, and all other IIS 7.x modules
- It supports and enables the same extensibility model and web.config file settings that IIS 7.x support
- It can be installed side-by-side with the full IIS web server as well as the ASP.NET Development Server (they do not conflict at all)
- It works on Windows XP and higher operating systems – giving you a full IIS 7.x developer feature-set on all OS platforms
more from Guthrie: http://weblogs.asp.net/scottgu/archive/2010/06/28/introducing-iis-express.aspx
Installation
- Be sure you have Microsoft Visual Studio 2010 Service Pack 1 installed.
- Download IIS Exress from Microsoft's Web Gallery.
Enabling IIS Express in your Web Application
Right click on your Web Application and select Use IIS Express...

When you run the Web Application you should now see the IIS Express tray icon.

Extra Credit
By default, IIS Express will bind to the localhost host name. For most people this is not a big deal, but if you to make this accessible to other computers on the network, you'll have to add a second host name binding.
I run a few Virtual Machines on my box that have older browser version (ie6, etc.) and this is how I gain access with them.
To do this, right click on the tray icon and select Show All Applications and click the application you just created.

After clicking on the Config link (opens the applicationhost.config in Visual Studio) scroll down to the <sites /> section. You'll see a node that looks like this:
<site name="MvcApplication1" id="2"> <application path="/" applicationPool="Clr4IntegratedAppPool"> <virtualDirectory path="/" physicalPath="C:\DEV\MvcApplication1\MvcApplication1" /> </application> <bindings> <binding protocol="http" bindingInformation="*:5791:localhost" /> </bindings> </site>Add a binding for your computer's name. In my case my computer is mobile5.
<site name="MvcApplication1" id="2"> <application path="/" applicationPool="Clr4IntegratedAppPool"> <virtualDirectory path="/" physicalPath="C:\DEV\MvcApplication1\MvcApplication1" /> </application> <bindings> <binding protocol="http" bindingInformation="*:5791:localhost" /> <binding protocol="http" bindingInformation="*:5791:mobile5" /> </bindings> </site>Optional*: Open your project's properties and set your Start URL to http://mobile5:5791. Check the box "Override application root URL" and insert the same value http://mobile5:5791/
(if IIS Express is currently running you will have to stop it for the changes to take effect)
Final Thoughts
That should be it. You should now be running your Web Application under IIS Express. Other PCs or VMs should be able to view your projects via the additional binding.
* Skip the optional step if the project is used by multiple developers or opened on multiple machines.
** Additional bindings may require you to run Visual Studio as an Administrator or add entries into your host files.
Data, Context and Interaction (DCI) & Windows Workflow (C#)
Disclaimer: This article assumes you already know the following: C#, WF4 and Extension Methods.
Lately I have been reading a bunch about Data, Context and Interaction (DCI) and a lot of my current project have involved using Windows Workflow Foundation (WF4). Recently I've come to the realizaion that a WF4 Activity can also be the perfect DCI context because both are basically use cases.
I've taken some sample code written by Christian Horsdal about DCI in C# and applied to to a Workflow. He's has some very good posts about DCI and C#, I'd recommend checking them out if you want to learn more.
The Data
First we'll have a look at the data models we'll be using.
We've got our base Account class and our derived classes CheckingAccount and SavingsAccount.
public abstract class Account { public double Balance { get; protected set; } public void Withdraw(double amount) { Balance -= amount; } public void Deposit(double amount) { Balance += amount; } public void Log(string message) { Console.WriteLine("Log: {0}", message); } }public class CheckingAccount : Account, TransferMoneySource, TransferMoneySink { public CheckingAccount() { Balance = 1000; } public override string ToString() { return "Balance " + Balance; } }public class SavingsAccount : Account, TransferMoneySource, TransferMoneySink { public SavingsAccount() { Balance = 1000; } public override string ToString() { return "Balance " + Balance; } }The Interaction
In our Data Models, you'll notice there's a TransferMoneySource and TransferMoneySink on each of our derived account classes. Those are the Roles these accounts can play, they can be both the Source or Sink when transfering money.
The Roles are defined as Interfaces and provide just the minimum amount of data to perform that Interaction.
In C# one way of providing the DCI Interaction is through the use of extension methods (eg: the TransferTo method below).
public interface TransferMoneySink { void Deposit(double amount); void Log(string message); } public interface TransferMoneySource { double Balance { get; } void Withdraw(double amount); void Log(string message); } public static class TransferMoneySourceTrait { public static void TransferTo(this TransferMoneySource self, TransferMoneySink recipient, double amount) { if (self.Balance < 0) { throw new ApplicationException("insufficient funds"); } self.Withdraw(amount); self.Log("Withdrawing " + amount); recipient.Deposit(amount); recipient.Log("Depositing " + amount); } }The Context
For the Transfer Money use case, we're going to Withdraw money from one account and Deposit it into another using the TransferTo extension method we created above. This use case requires three things: the Source, the Sink and the Amount.
Written as a WF4 Activity, it will look like this...
public sealed class TransferMoneyActivity : CodeActivity { [RequiredArgument] public InArgument<TransferMoneySource> Source { get; set; } [RequiredArgument] public InArgument<TransferMoneySink> Sink { get; set; } [RequiredArgument] public InArgument<double> Amount { get; set; } protected override void Execute(CodeActivityContext context) { var source = Source.Get(context); var sink = Sink.Get(context); var amount = Amount.Get(context); source.TransferTo(sink, amount); } }Executing the Activity / Context (use case)
Transfering $100 from the CheckingAccount to SavingsAccount can be as simple as this.
var savingsAccount = new SavingsAccount(); var checkingAccount = new CheckingAccount(); var arguments = new Dictionary<string, object> { { "Source", checkingAccount }, { "Sink", savingsAccount }, { "Amount", 100 } }; WorkflowInvoker.Invoke(new DemoActivity(), arguments);And now that our Context is a standard WF4 Activity, we can easily incorporate it into our larger Workflows.

Unobtrusive Data-Binding for Knockout.js
If you're a web developer who has yet to see Knockout, go take a look. I'll wait... Knockout is an incredible library, I just love it. Though I prefer to keep my presentation layer clean and now it's sprinkled with little bits of code for the data-binding. And that is how this Plugin came to be. It solves that problem with an easy way to Unobtrusively Data-Bind your presentation layer.
Obtrusive example (taken from knockoutjs.com)
You'll notice in this example, information about how to perform the data-binding is married to the presentation layer.
Choose a ticket class: <select data-bind="options: tickets, optionsCaption: 'Choose...', optionsText: 'name', value: chosenTicket"></select> <p data-bind="template: 'ticketTemplate'"></p> <script id="ticketTemplate" type="text/x-jquery-tmpl"> {{if chosenTicket}} You have chosen <b>${ chosenTicket().name }</b> ($${ chosenTicket().price }) <button data-bind="click: resetTicket">Clear</button> {{/if}} </script> <script type="text/javascript"> var viewModel = { tickets: [ { name: "Economy", price: 199.95 }, { name: "Business", price: 449.22 }, { name: "First Class", price: 1199.99 } ], chosenTicket: ko.observable(), resetTicket: function() { this.chosenTicket(null) } }; ko.applyBindings(viewModel); </script>Unobtrusive Example
But now the data-binding has been completely separated from the presentation layer.
<!-- file: ticket.html --> Choose a ticket class: <select id="tickets"></select> <p id="ticketOutput"></p> <script id="ticketTemplate" type="text/x-jquery-tmpl"> {{if chosenTicket}} You have chosen <b>${ chosenTicket().name }</b> ($${ chosenTicket().price }) <button data-bind="click: resetTicket">Clear</button> {{/if}} </script>and the javascript file...
// file: ticket.js var viewModel = { tickets: [ { name: "Economy", price: 199.95 }, { name: "Business", price: 449.22 }, { name: "First Class", price: 1199.99 } ], chosenTicket: ko.observable(), resetTicket: function() { this.chosenTicket(null) } }; $('#tickets').dataBind({ options: 'tickets', optionsCaption: "'Choose...'", optionsText: "'name'", value: 'chosenTicket' }); $('#ticketOutput').dataBind({ template: "'ticketTemplate'" }); ko.applyBindings(viewModel);The Advantages / Why
Complete separation of code from your presentation layer -- There are many reasons why you might want this: Code can be kept in separate js files (think of caching), designers can now modify the html without worry of breaking it, etc. Elimination of magic strings-- Complex data-binding can be difficult to maintain with magic strings, especially when you start using functions or events. In the following example, I took the data-bound element from above and added a click event. Without the Unobtrusive approach, you'd have to encode that function into your magic string.
$('#tickets').dataBind({ options: "tickets", optionsCaption: "'Choose...'", optionsText: "'name'", value: "chosenTicket", event: { change: function(evt) { console.log(evt); } } });Download it
Well that's pretty much it. The Plugin is small at only 544 bytes (360 bytes gzipped). Download it and play with it. Let me know if you find any bugs. You can download it here: github
Joel is a Chief Architect / Senior Developer who has been working in the industry since 1996.