Fluid interface for data access with SQL Server

While working on my current project I came up with this simple fluid interface used for data access with SQL Server. My current project doesnt use any ORMs for reasons that would wage war, so I won’t go into those details. I came up this with fluid interface to reduce the mundane ADO.NET code and to reduce repetition.

As with an ADO.NET Command object, this code executes non query or return a scalar or a  data reader.  My goal was to try and reduce as much code as possible especially with the data reader. I wanted to not use strings and ordinals and keep the code simple, so with a bit of experimenting I managed it with a class called “DynamicDbDataReader” which is a DynamicObject.

As a generic library, I had to allow for connections to be supplied / configured by allowing a connection instance to be supplied, a connection string or my preferred method, the name of the connection string that existing in the config file which I would keep as a string constant and pass it into the method.

The parameters that are supplied are done using a string for the parameter name and the object containing the parameter value. Method chaining is used to add more that one parameter and the data type is inferred automatically. All parameters are input only.

Example: Running a stored procedure with many parameters that does not return a result set (ExecuteNonQuery)

With.StoredProcedure("SomethingTo_Insert")
   .UsingConfiguredConnection("SomeConnectionStringName")
   .WithParameter("id", something.Id)
   .And.WithParameter("name", something.Name)
   .And.WithParameter("desc", something.Description)
   .And.WithParameter("severity", something.Severity)
   .And.WithParameter("systemKey", something.SystemKey)
   .ExecuteNonQuery();

Example: Running a stored procedure that returns a scalar which in this case is a boolean (ExecuteScalar)

 
bool result = With.StoredProcedure("Somthing_Exists")
                .UsingConfiguredConnection(DatabaseConnections.SomeDatabase)
                .WithParameter("name", name)
                .ExecuteScalar<bool>();

Example: Running a stored procedure with no parameters that does not return a result set using (ExecuteNonQuery)

With.StoredProcedure("SomethingTodo")
   .UsingConnection(sqlConnection)
   .WithNoParameters()
   .ExecuteNonQuery();

Example: Running a stored procedure that returns a data reader with parameters

dynamic reader = With.StoredProcedure("Somthing_SelectAllWithOtherStuff")
                    .UsingConfiguredConnection(DatabaseConnections.QueryStore)
                    .WithParameter("searchId", organsiationId)
                    .ExecuteReader(CommandBehavior.CloseConnection);

while (reader.Read())
{
    response.Something.Add(new SomeSummaryInfo
    {
        Id = reader.Id,
        Forename = reader.FirstName,
        Surname = reader.LastName
    });
}

reader.NextResult();

while (reader.Read())
{
    response.Tasks.Add(new OtherSummaryInfo
    {
        Id = reader.Id,
        Name = reader.Name,
        SomeId = reader.SomeId,
        SomeOtherName = reader.OtherName,
        DisplayOrder = reader.DisplayOrder,
    });
}

Example: Running a sql statement that has no parameters

With.SqlStatement("DELETE FROM SomeTable")
    .UsingConfiguredConnection("DatabaseName")
    .WithNoParameters()
    .ExecuteNonQuery();

In the event that a field name is spelt wrong when working with the dynamic reader, a ColumnNotFoundException will be thrown. The dynamic reader has methods on it for “Read()” and “NextResult()”.

That’s it in a nutshell.

You can download the code. its got a .doc extension but its really zip file. So download it and change the extension to get the code.
dataAccessBuilder

ASP.NET MVC: A utility for testing secured Actions

I have come across a common scenario while developing an ASP.NET MVC application. This being testing Actions that require the user to be authorised and / or requires permissions to execute methods  that are locked down with principal permissions.

Here as an example of a controller with an action that is firstly decorated with the “Authorize” attribute (ASP.NET MVC filter) that requires the user to be in a specified role.

[Authorize(Roles="Client Administrators")]
public ViewResult Edit(int clientId)
{
    return View("Edit");
}

 

While I was writing a test for an Action that needed the user to be Authorized . I   created implementations of the IIdentity and IPrincipal interfaces that I could use to satisfy this requirement. Although this worked, it was not reusable. When you set principle, you should apply it to the current AppDomain instead of the current thread as the every thread created in your AppDomain will have the principal set automatically. Once you have set the principle you cannot apply my than once as it will throw an exception. It is also a problem is you try to reset the principal to null.

To add to matters, is was not long before I needed to satisfy principal permissions. My Principal and Identity implementations needed to be more flexible.

So the answer was to create a utility that firstly set the AppDomain to use my principal implementation and allow each and every test to arrange the state of the principal. For each and every test  I also want to write the minimum amount of code by only writing one line of code.  This line of code would be amongst NBehave and RhinoMocks code that have their own fluent interfaces so I want my line of code to fit in with the fluent style. Below are three ways I want to my utility.

//1
TheCurrentUser.Instance.IsAuthenticated().And.IsInAllRoles();
 
//2
TheCurrentUser.Instance.IsAuthenticated()
    .And.IsInThisRole("System admins")
    .And.IsInThisRole("developers")
    .And.IsInThisRole("power users");
 
//3
TheCurrentUser.Instance.IsNotAuthenticated();

 

So I started to create this utility by placing its into its own assembly. The root object is the “TheCurrentUser” object. Its the only public class in the assembly and is used as  a singleton. It creates and hosts three objects references and sets the IPrincipal implementation to the current AppDomain.

using System;
using System.Security.Principal;
 
namespace RussellEast.Principal.Utility
{
    public class TheCurrentUser
    {
        static readonly TheCurrentUser instance = new TheCurrentUser();
 
        private IPrincipal principal;
        private IAuthenticationOptions options;
        private ISecurityContext context;
 
        private TheCurrentUser()
        {
            BuildObjectGraph();
            SetAppDomainPrincipal();
        }
 
        static TheCurrentUser() { }
 
        public static IAuthenticationOptions Instance
        {
            get { return instance.Options; }
        }
 
        public IAuthenticationOptions Options
        {
            get { return options; }
        }
 
        private void BuildObjectGraph()
        {
            context = new SecurityContext();
            principal = new FakePrincipal(context);
 
            options = AuthenticationOptions.Create(context);
        }
 
        private void SetAppDomainPrincipal()
        {
            AppDomain.CurrentDomain.SetThreadPrincipal(principal);
        }
    }
}

 

The fluent interface uses a context object (that holds the state as its passed around) that is injected into  various objects that are explained below. The context object implements the following interface.

using System.Collections.Generic;
 
namespace RussellEast.Principal.Utility
{
    internal interface ISecurityContext
    {
        bool IsAuthenticated { get; set; }
        bool IsInAllRoles { get; set; }
        List<string> Roles { get; set; }
        void Reset();
    }
}

 

This is the concrete implementation of the ISecurityContext interface.

using System.Collections.Generic;
 
namespace RussellEast.Principal.Utility
{
    class SecurityContext : ISecurityContext
    {
        public bool IsAuthenticated { get; set; }
        public bool IsInAllRoles { get; set; }
        public List<string> Roles { get; set; }
 
        public void Reset()
        {
            IsAuthenticated = false;
            IsInAllRoles = false;
 
            if (Roles != null)
            {
                Roles.Clear();
            }
        }
    }
}

 

Back to the “TheCurrentUser” object, the instance property returns an object that implements the following interface below.

(Although this object is a singleton, the pattern would be to return the singular  instance of the singleton, i have not done this as the singleton does nothing but host objects and be the root object for the fluent interface.)

namespace RussellEast.Principal.Utility
{
    public interface IAuthenticationOptions
    {
        IAuthorisationRouter IsAuthenticated();
        void IsNotAuthenticated();
    }
}

 

My concrete of the above  interface is as follows:

namespace RussellEast.Principal.Utility
{
    class AuthenticationOptions : IAuthenticationOptions
    {
        private readonly IAuthorisationRouter router;
        private readonly ISecurityContext context;
        private AuthenticationOptions(ISecurityContext context, IAuthorisationRouter router)
        {
            this.context = context;
            this.router = router;
        }
 
        public IAuthorisationRouter IsAuthenticated()
        {
            ChangeSecurityState(true);
 
            return router;
        }
 
        public void IsNotAuthenticated()
        {
            ChangeSecurityState(false);
        }
 
        private void ChangeSecurityState(bool isAuthenticated)
        {
            context.Reset();
 
            context.IsAuthenticated = isAuthenticated;
        }
 
        public static IAuthenticationOptions Create(ISecurityContext context)
        {
            var roleAuthorisation = new RoleAuthorisation(context);
            var router = new AuthorisationRouter(roleAuthorisation);
 
            return new AuthenticationOptions(context, router);
        }
    }
}

 

As you can see from the code, the AuthenticationOptions class is passed an instance of the security context and an instance of the IAuthorisationRouter.

The responsibility of this class is to reset the context and set a new authentication value. This class also contains a “Factory Method” that is used to create an instance of this object.

The “IsAuthenticated” method returns the next link in the method chain being the “IAuthorisationRouter”.

namespace RussellEast.Principal.Utility
{
    public interface IAuthorisationRouter
    {
        IRoleAuthorisation And { get; }
    }
}

 

The “IAuthorisationRouter” purpose in life is to provide a linkage in the method chain. Here is the concrete implementation.

namespace RussellEast.Principal.Utility
{
    class AuthorisationRouter : IAuthorisationRouter
    {
        private IRoleAuthorisationController roleAuthorisation;
 
        public AuthorisationRouter(IRoleAuthorisationController roleAuthorisation)
        {
            this.roleAuthorisation = roleAuthorisation;
            this.roleAuthorisation.Router = this;
        }
 
        public IRoleAuthorisation And
        {
            get { return roleAuthorisation; }
        }
    }
}

 

I am using constructor injection as much as possible. It was not so clear cut with this object as the AuthorisationRouter exposes an instance of “RoleAuthorisation” which implies that it has knowledge of it. The “RoleAuthorisation” exposes an instance of the AuthorisationRouter. So both need to know about each other.  I am using interfaces to define the overall fluent interface so I want to keep it clean from any implementation that is needed to wire references to together. So the solution is to create another interface that is only used by a specific consumer  (Interface Segregation Principal). Because I need two instances of different objects that need to know about each other, I have to construct one object first that then inject that into the other object when its be instantiated. Then I use a setter (setter injection) to provide the reference of the second object back to the first object.

namespace RussellEast.Principal.Utility
{
    internal interface IRoleAuthorisationController :
        IRoleAuthorisation, ISettableRouter
    {
    }
}

 

Here is the “ISettableRouter” interface:

namespace RussellEast.Principal.Utility
{
    internal interface ISettableRouter
    {
        IAuthorisationRouter Router { set; }
    }
}

 

Here is the “IRoleAuthorisation” interface.

namespace RussellEast.Principal.Utility
{
    public interface IRoleAuthorisation
    {
        void IsInAllRoles();
        IAuthorisationRouter IsInThisRole(string role);
    }
}

 

I have a concrete class “RoleAuthorisation” that implements the “IRoleAuthorisationController” interface. Its responsibility is to manage the list of roles.

using System.Collections.Generic;
 
namespace RussellEast.Principal.Utility
{
    class RoleAuthorisation : IRoleAuthorisationController
    {
        private IAuthorisationRouter router;
        private readonly ISecurityContext context;
 
        public RoleAuthorisation(ISecurityContext context)
        {
            this.context = context;
        }
 
        public IAuthorisationRouter Router
        {
            set { router = value;  }
        }
 
        public void IsInAllRoles()
        {
            context.IsInAllRoles = true;
        }
 
        public IAuthorisationRouter IsInThisRole(string role)
        {
            if (!string.IsNullOrEmpty(role))
            {
                if (context.Roles == null)
                {
                    context.Roles = new List<string>();
                }
 
                if (!context.Roles.Contains(role))
                {
                    context.Roles.Add(role);
                }
            }
 
            return router;
        }
    }
}

 

That’s all the interfaces and classes needed to build the fluent interface. The last objects needed is the Principal and Identity objects, which reads its values from the context.

using System.Security.Principal;
 
namespace RussellEast.Principal.Utility
{
    class FakePrincipal : GenericPrincipal
    {
        private readonly ISecurityContext context;
 
        public FakePrincipal(ISecurityContext context) : base(new FakeIdentity(context), null)
        {
            this.context = context;
        }
 
        public override bool IsInRole(string role)
        {
            if (context.IsAuthenticated)
            {
                return context.IsInAllRoles ? true : context.Roles.Contains(role);
            }
 
            return false;
        }
 
        class FakeIdentity : GenericIdentity
        {
            private readonly ISecurityContext context;
 
            public FakeIdentity(ISecurityContext context) : base("Fake user")
            {
                this.context = context;
            }
 
            public override bool IsAuthenticated
            {
                get { return context.IsAuthenticated; }
            }
         }
    }
}

 

Although a lot of code is written for the fluent interface which took two hours to build from scratch, I have a very flexible utility that I know I am going to use a lot and not just with ASP.NET MVC. The only refactoring that I want to perform is to change the name of some of the interfaces as I feel that they could be better described. To finish this post, here is an example using this utility in a unit test.

 

 
        [Specification]
        public void Should_be_able_to_edit_a_client()
        {
            ViewResult result = null;
 
            story.WithScenario("editing a client")
                .Given("an instance of the controller", () => controller.ShouldNotBeNull())
                .And("the current user belongs to the 'client administrators' role", () =>
                {
                    TheCurrentUser.Instance.IsAuthenticated()
                        .And.IsInThisRole("Client Administrators");
 
                    //NOTE: these two lines are not needed, just  validating the utility.
                    Thread.CurrentPrincipal.Identity.IsAuthenticated.ShouldBeTrue();
                    Thread.CurrentPrincipal.IsInRole("Client Administrators").ShouldBeTrue();
                })
                .When("the Edit action is invoked", () =>
                {
                    result = controller.Edit(1) as ViewResult;
                })
                .Then("verify that the user is directed to the right view", () =>
                {
                    result.AssertViewRendered().ForView("Edit");
                });
 
        }

 

For a better understanding of the unit test above, please read this post

Creating Fluent finders and repositories part 1

Introduction

This is the first post of this series about implementing fluent finders and repositories, I am going to expand my current repository and finder implementation which is explained here. I recommend that you read this post (precursor) as this series continues on from this post and the code examples.

The objectives for this series are:

  • Create a fluent interface on the finders
    • Chain the find methods so that you can find on more than one method (method chaining).
    • Create an interface for sorting.
    • Create an interface for paginating the results.
  • Allow a service request (coarse grain) to be mapped to a specific fluent-interface call.
    • Based on information provided to a service as a request object, determine the right strategy for satisfying the request.
    • Execute the relevant strategy to perform the relevant queries
    • Return the query results to service method that was called.
    • The service method will return results as a response object.
  • Drive out these behaviours using TDD/BDD.

The outcome of this work will allow you write something like:

repository.find.ByThis(somevalue).AndFind.ByThat(someOtherValue).SortBy(aField, InAscendingOrder).Paginate.WithPageSize(10).ShowPage(1);

Before I start, one of the main benefits of a fluent interface is that you create an API that guides and limits the decisions that can be expressed in a logical order. So the interface needs to limit the options as the expression flows, which ultimately means you need to plan out the branching and the interfaces for each branch and decisions to ensure that public interface is meaningful to its context.

Table of Contents

Precursor

Part 1  (this post)

  • Refactoring the existing interfaces to provide interface segregation.
  • The Query Command
  • Method Routing
  • Method Chaining

Refactoring

Following on from the precursor, I need to stop my “IApplicationUserFinder” from implementing the “IEntityFinder” interface. The reason for this is the the  “IEntityFinder” interface exposes a property called DataSource. The published Fluent interface will want to expose the Find methods but not the DataSource property. So a bit of interface segregation is needed here to expose the right interface to the relevant consumer. While doing this refactoring, I decided that the name of the “IEntityFinder” is not right so I have renamed it to “IQueryableDataStore”. Although I have changed these interfaces around my concrete class  ApplicationUserFinder still need to implement both. So I have created yet another interface called “IQueryableApplicationUserFinder” which implements the “IQueryableDataStore” and “IApplicationUserFinder” interfaces. Now the ApplicationUserFinder class just implements IQueryableApplicationUserFinder. If I have scrambled your brain up, hopefully the code snipets below will make things clear.

    public interface IQueryableDataStore where Entity : EntityBase // was IEntityFinder
    {
        IQueryable DataSource { get; set; }
    }
...
    public interface IQueryableApplicationUserFinder :
        IApplicationUserFinder,
        IQueryableDataStore
    {
    }
...
 public class ApplicationUserFinder : IQueryableApplicationUserFinder
...

Now, how is this used. The ApplicationUserFinder is injected into the ApplicationUserRepository and then exposed via a getter (all by interfaces).  With the “IQueryableApplicationUserFinder” now in play, here is the revised code snippet for the repository (remember to change your IoC container to accommodate these changes).

    public class ApplicationUserRepository : EntityRepository,
        IApplicationUserRepository
    {
        private readonly IQueryableApplicationUserFinder finder;

        public ApplicationUserRepository(IPersistanceRepository repository,
            IQueryableApplicationUserFinder finder) : base(repository)
        {
            this.finder = finder;

            this.finder.DataSource = Query();
        }

        public IApplicationUserFinder Find
        {
            get { return finder; }
        }
    }

At this point, all my unit tests pass and application runs the same as it did before this refactoring.

The Query Command

Regardless of the expression that you can write using the fluent-interface, it needs  an end at some point. The Query Command objects is responsible for executing the query and return the result. I am using “Linq for objects” to write my queries and passing an IQueryable around under the covers, the execution of the queries is deferred until a method is called on it like “ToList()”. Calling the “ToList()” method will execute the underlying query.  I have  created a command object (based on the command pattern) to expose an “Execute” method that is going to return an IEnumerable<Entity>. The reason for returning “IEnumerable<Entity>” is that you have a vast about of extension methods that you use to execute the query. For example “ToList()” and “FirstOrDefault”. We can create the Query Command now and integrate it into the fluent-interface later with out much effort.

    public interface IQueryCommand where Entity : EntityBase
    {
        IEnumerable Execute();
    }

    public class QueryCommand : IQueryCommand
    {
        private readonly IQueryableDataStore queryableDataStore;

        public QueryCommand(IQueryableDataStore queryableDataStore)
        {
            this.queryableDataStore = queryableDataStore;
        }

        public IEnumerable Execute()
        {
            return queryableDataStore.DataSource.AsEnumerable();
        }
    }

So how can the fluent-interface get to this endpoint? Answer: we need an object to return it, so we can call it. I have defined this as “MethodRouter”.

Method Router

The method router exposes the actions that could be performed after a find method is called. As this is based on my previous post Implementing the Repository and Finder Pattern, I am going to change the original unit tests to drive out the method router. Here is the original specification for the “ApplicationUserFinder” class.

    [TestFixture]
    public class When_executing_queries_against_application_users
    {
        private ApplicationUserFinder finder; // subject under test

        [SetUp]
        public void Setup()
        {
            finder = new ApplicationUserFinder();

            finder.DataSource = GetStubbedCollection();
        }

        [Test]
        public void Should_return_a_user_by_login_name_when_supplied_a_known_login_name()
        {
            ApplicationUser result = finder.ByLoginName("Test.User3");

            Assert.That(result.LastName, Is.EqualTo("User3"));
        }

        [Test]
        public void Should_return_a_user_by_token()
        {
            ApplicationUser result = finder.ByToken(Guid.Empty);

            Assert.That(result.LastName, Is.EqualTo("User2"));
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void Should_fail_if_supplied_null_login_name()
        {
            IQueryable users = GetStubbedCollection();

            ApplicationUser result = finder.ByLoginName(null);
        }

        private IQueryable GetStubbedCollection()
        {
            List users = new List
            {
                new ApplicationUser { FirstName = "Test", LastName = "User1", LoginName="Test.User1", Token = Guid.NewGuid() },
                new ApplicationUser { FirstName = "Test", LastName = "User2", LoginName="Test.User2", Token = Guid.Empty},
                new ApplicationUser { FirstName = "Test", LastName = "User3", LoginName="Test.User3", Token = Guid.NewGuid()},
                new ApplicationUser { FirstName = "Test", LastName = "User4", LoginName="Test.User4", Token = Guid.NewGuid()},
                new ApplicationUser { FirstName = "Test", LastName = "User5", LoginName="Test.User5", Token = Guid.NewGuid()}
            };

            return users.AsQueryable();
        }
    }

As you can see from the above tests, each find method returns the result as a single domain entity. I now want to return an interface of the Method Router instead. The Method Router at point will expose the QueryCommand so that I still execute the queries and keep the code in a “close to working” state at all times.

To start with, I defined the MethodRouter interface “IApplicationUserFinderActions”

    public interface IApplicationUserFinderRouter
    {
        IQueryCommand Output { get; }
    }

Now, I need to change the return types in the IApplicationUserFinder to now return the IApplicationUserFinderRouter instead.

    public interface IApplicationUserFinder
    {
        IApplicationUserFinderRouter ByLoginName(string loginName);
        IApplicationUserFinderRouter ByToken(Guid token);
    }

At this point, things a little broken, so I need to change the concrete ApplicationUserFinder class to implement the changes made to the interface. To do this the concrete finder will need to know about the Method Router class. The method Router’s responsibility is to act as a hub to link object instances together. With this in mind, the MethodRouter class will need to know about the finder and the QueryCommand class. Still being mindful of the fluent interface and members it exposes, I need to ensure that the QueryCommand knows about the IQuerable instance held in the finder without coupling the objects together. To achieve this, I going to use the same technique I used in the Refactoring effort being the i return different interfaces to different parties. I have created another interface “IFindableApplicationUserFinderRouter” that implements IApplicationUserFinderRouter with an additional member.

Here is the new interface

    public interface IFindableApplicationUserFinderRouter
        : IApplicationUserFinderRouter
    {
        IQueryableApplicationUserFinder Finder { get; set; }
    }

Here is the concrete class ApplicationUserFinderRouter at this point.

    public class ApplicationUserFinderRouter : IFindableApplicationUserFinderRouter
    {
        private IQueryCommand queryCommand;

        public IQueryableApplicationUserFinder Finder { get; set;}

        public IQueryCommand Output
        {
            get
            {
                if (queryCommand == null)
                {
                    queryCommand = new QueryCommand(Finder);
                }

                return queryCommand;
            }
        }
    }

Here is the changed ApplicationUserFinder

    public class ApplicationUserFinder : IQueryableApplicationUserFinder
    {
        private readonly IFindableApplicationUserFinderRouter router;
        private IQueryable users;

	
        public ApplicationUserFinder(IFindableApplicationUserFinderRouter router)
        {
            this.router = router;
            this.actions.Finder = this;
        }
	

        public IQueryable DataSource
        {
            get { return users; }
            set { users = value; }
        }

        public IApplicationUserFinderRouter ByLoginName(string loginName)
        {
            if (string.IsNullOrEmpty(loginName))
            {
                throw new ArgumentNullException("loginName");
            }

	    
            users.Where(u => u.LoginName == loginName).FirstOrDefault();

            return router;
        }

        public IApplicationUserFinderRouter ByToken(Guid token)
        {
            users.Where(u => u.Token == token).FirstOrDefault();

		
            return router;
        }
    }

Here is a snippet of how one of the unit tests is looking.

	[SetUp]
        public void Setup()
        {
            router = MockRepository.GenerateStub();

            finder = new ApplicationUserFinder(router);

            finder.DataSource = GetStubbedCollection();
        }

        [Test]
        public void Should_return_a_user_by_login_name_when_supplied_a_known_login_name()
        {
            ApplicationUser result = finder.ByLoginName("Test.User3").Output.Execute().FirstOrDefault();

            Assert.That(result.LastName, Is.EqualTo("User3"));
        }

At this stage is hard to see the advantage of this apart from separating out code. The next step is to allow the find methods to be chained together (method chaining).

Method Chaining

The IApplicationUserFinderRouter interface is going to allow the finder to be returned from a property. This is pretty simple stuff. Below is the interface with the new property and the concrete class implementing this addition member.

    public interface IApplicationUserFinderRouter
    {
        IQueryCommand Output { get; }
        IApplicationUserFinder AndFind { get; }
    }

    public class ApplicationUserFinderRouter : IFindableApplicationUserFinderRouter
    {
        private IQueryCommand queryCommand;

        public IQueryableApplicationUserFinder Finder { get; set;}

        public IQueryCommand Output
        {
            get
            {
                if (queryCommand == null)
                {
                    queryCommand = new QueryCommand(Finder);
                }

                return queryCommand;
            }
        }
	
        public IApplicationUserFinder AndFind
        {
            get { return Finder; }
        }
    }

This now allows the find methods to be chained so you can write the following code

        [Test]
        public void Should_return_a_user_when_finding_by_Login_name_and_token()
        {
            ApplicationUser result = repository
                .Find.ByToken(Guid.Empty)
                .AndFind.ByLoginName("Test.User2")
                .Output.Execute().FirstOrDefault();

            Assert.That(result.LastName, Is.EqualTo("User2"));
        }

That concludes this post, the next part of this series will cover paginating the results returned from the underlying query.