Don’t force your data-persistence solution to fit every needs

The N+1 is evil. I want referential integrity. I want…

“Hold it right there Mr!” A document-oriented Db (DOD) is not an RDBMS! If you are having an N+1 scenario or feeling a pain with references, you should probably first have a look at your model and your chosen data-persistence solution (DPS). Is it perhaps so that you shouldn’t be using a DOD for the scenario you are having issues with?

The DPS are designed for specific use-cases and it’s likely so, that if you find your self in a somewhat complex domain; you should have more than one DPS, instead of forcing one to fit in every context.

Vendors can bring all kinds of help to the table, generating proxies around your POCOs and let the DPS: track changes, manage references and automatically pull stuff in from the DPS into cache; All kinds of magical stuff could be done by the DPS. But is this really the way to go for a DOD?

If you are experiencing e.g an N+1 scenario as a result of you iterating over a bunch of documents referencing other documents. Could it perhaps be so that you should instead have designed a specific document containing all data for that particular view? Sure, that would mean you would take parts of documents and duplicate the storage of it, but you will get a view representing a certain context. This would benefit read scenarios whilst you will get harder to administer the write scenarios, and if that gets a pain (a real pain), you should start thinking of using another DPS that fits your needs for that use-case.

Just some rambling, nothing scientific. Agree or don’t agree.

//Daniel

IoC with SisoDb in ASP.Net MVC

I just put together a short screencast (about 4min) showing you have to configure SisoDb with an IoC-container in ASP.Net MVC using “One session per HttpRequest”. For this demo I will use Ninject.

The screencast is hosted in the SisoDb channel at Vimeo.

Updated: Mike Paterson has a GitHub repository with code for the episode, found here: https://github.com/devlife/Sandbox/tree/master/SisoDb

Summarized

After having installed the “Ninject.MVC3 NuGet package”, I added a NinjectModule named “DbConfig” under a new folder/namespace “IoCConfig”.

public class DbConfig : NinjectModule
{
    public override void Load()
    {
        var db = "CoreConcepts".CreateSql2012Db();
        Kernel.Bind<ISisoDatabase>()
            .ToMethod(ctx => db)
            .InSingletonScope();

        db.CreateIfNotExists();

        Kernel.Bind<ISession>()
            .ToMethod(ctx => db.BeginSession())
            .InRequestScope();
    }
}

After that we just need to ensure the module is loaded by Ninject in the bootstraper, which is installed by the Ninject.MVC3 NuGet, under “App_Start”. The only change that is needed is adding one row to the “CreateKernel” member, so that it look like this:

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
    kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

    //ADD THIS TO LOAD OUR MODULE(s)
    kernel.Load(typeof(MvcApplication).Assembly);

    RegisterServices(kernel);
    return kernel;
}

We are now all set and can take a dependency on “ISession” in our controllers. Either in the constructor or by resolving it using a static class/method/service locator concept against the Ninject IoC-container. Since my sample uses Db-access in each action, I used constructor injection.

public class CustomerController : Controller
{
    private readonly ISession _dbSession;

    public CustomerController(ISession dbSession)
    {
        _dbSession = dbSession;
    }

    //...
}

That’s it.

//Daniel

Realtime web application using CQRS and websockets

I’ve started to put together a sample application having an architecture looking like this:

There’s an ASP.Net MVC application that only serves GET requests. Each rendered view then communicates to a web socket server using web sockets. The client issues commands and listens/reacts to business events triggered by the domain executed at the application server. The commands reaches the application server using a service bus (MassTransit). The events generated by the aggregate roots in the domain are alos put on the bus and thereby will be delivered back to the web socket server which notifies the correct sender. All events are stored in an event store. The events are also denormalized to customer read models (using SisoDb), which could be seen as a data model that is designed to target a specific scenario, with e.g precalculated aggregated values etc. The read models are written to one data base which then is replicated to one serving reads in the web application and one serving reads in the web socket server.

I’ll keep writing about this and when time comes, it will be open sourced at GitHub.

//Daniel

Ensure.That – a simple guard clause project

Yes I know there’s a bunch of these projects out there already and that there’s built in support for using code-contracts in .Net, but even so we found a need for a custom API, hence Ensure.That was created. Also, I think Microsoft’s Code-contracts fails on the part of having to install an add-on to VS2010 to actually put the Code-contract requirements to use. Until it’s a first class citizen of VS, it’s not useful in my eyes. Enough about that.

Why

Easy, to provide a clean API for validating arguments and a solution that throws natural argument exceptions with informative exception messages.

NuGet

It’s distributed using NuGet. You could consume it as a normal lib or as a source distribution. The later gives you the possibility of incorporating it into any existing “common core lib” that you already use for these kind of utils.

Some code

The API is continuously evolving and it hasn’t reached v1.0 yet, hence there might be braking changes, but that’s not very likely. There will probably only be new stuff added.

Without parametername

Will throw ArgumentNullException or ArgumentException without ParameterName.

public void MyMethod(string myString, int myInt, Guid myGuid)
{
    Ensure.That(myString).IsNotNullOrEmpty();
    Ensure.That(myInt).IsInRange(10, 20);
    Ensure.That(myGuid).IsNotEmpty();
}

Using Lambdas

Note, that since the value also is extracted via the Lambda there’s a compile of it, hence the other overloads or more performant.

public void MyMethod(string myString, int myInt, Guid myGuid)
{
    Ensure.That(() => myString).IsNotNullOrEmpty();
    Ensure.That(() => myInt).IsInRange(10, 20);
    Ensure.That(() => myGuid).IsNotEmpty();
}

Providing parameter name explicitly

Will work as the first example with the difference of including the parameter name in the exception’s _ParameterName _property.

public void MyMethod(string myString, int myInt, Guid myGuid)
{
    Ensure.That(myString, "myString").IsNotNullOrEmpty();
    Ensure.That(myInt, "myInt").IsInRange(10, 20);
    Ensure.That(myGuid, "myGuid").IsNotEmpty();
}

More information and sourcecode is available on the GitHub site.

//Daniel

I like to dance

A couple of years ago me and my wife took dance lessons. I thought it was very challenging since I had no idea of how to get my body to move like the instructor showed us, in pace with the music and at the same time leading my partner and protecting her on the dance floor from getting hit by other dancers. After weeks and months of practice I managed to master dance after dance and it just got more and more of a joy. Why? Simple! I had learned to master the steps. Learned how to feel the music. Learned how to plan and create a choreography that was suitable for me and my partner – for our team.

As a software developer I have made many mistakes. I have been in scenarios where I have been to junior for the responsibility given to me. I have produced bugs and misinterpreted specifications. I have produces architectural solutions that didn’t make the cut. For every failure though, I have gone home, sat my self down, trying to evaluate and come up with other ideas. Studying other developers work to see alternative solutions. Everything for evolving my skills. And that’s a good start but still, no matter how smart solutions you produce, they mean nothing if the team isn’t on the same track. It doesn’t matter if you understand how every part works together. What matter is that everyone in the team feels comfortable with the solution and feel that they can be productive. It should also be easy to introduce new members in the team. That’s something I think is foreseen. To much focus is put on creating “hyped solutions” using the latest frameworks and “buzziest” patterns without looking at the maturity of the team. Without thinking about the developers that will administer the software when all consultants and/or initial staffing has left.

Balance. Yes, I know it’s a vague word, but you must try to balance the complexity of the solution seen to the team. That’s one of the most important thing I have learnt and used. Listen, back down and adapt and you will conquer. I know it’s tempting to be “cool”, but sometimes a step in another direction might be better. Keep this in mind and remember to be open minded.

//Daniel

C#, Clean up your Linq-queries and lambda expressions for Non Linq to objects

This is an update to my post “C#, Clean up your Linq-queries and lambda expressions”, where I got a comment that it will not work other than against Linq to objects. That is somewhat true. It will work but the query will fetch all posts from the database and then apply the where clause to objects in memory which should trigger a sign DANGER!. In my case I only needed in memory but I thought, why not provide an example….

This example will be targetting Entity framework Code first, CTP 5.

The test

[Test]
public void AgainstEfCodeFirstCtp5()
{
    using (var dbContext = new StorageContext())
    {
        DbDatabase.SetInitializer(new DropCreateDatabaseAlways<StorageContext>());

        foreach (var customer in _customers)
            dbContext.Customers.Add(customer);

        dbContext.SaveChanges();
    }

    using (var dbContext = new StorageContext())
    {
        //Will not call the database
        var bonusCustomers = dbContext.Customers.Where(new IsBonusCustomer());

        //Will invoke call to database
        CollectionAssert.AreEqual(_expectedBonusCustomers.Select(c => c.Id), bonusCustomers.Select(c => c.Id));
    }
}

The sql-query will not be executed against the database until I access the deferred executable collection “bonusCustomers”. The query will look like this (interceptet with the Sql Profiler).

SELECT 
[Extent1].[Id] AS [Id]
FROM [dbo].[Customers] AS [Extent1]
WHERE
(
	(0 = [Extent1].[NumOfYearsAsMember])
	AND
	([Extent1].[CashSpent] >= 3000)
)
OR
(
	([Extent1].[NumOfYearsAsMember] > 0)
	AND 
	(
		([Extent1].[CashSpent] / [Extent1].[NumOfYearsAsMember]) >= 5000
	)
)

It matches our rule of the c-sharp code, but the generated Sql will of course brake, since it will give a divide by zero for the customers with less than one year of membership, but that is not the point of this blog post.

The changes from the last blog post

Instead of letting the implicit operator return a Func<T> it now returns Expression<Func<T>>. To let the Evaluate member work I also compiled the lambda to a Func.

public class ExpressionRule2<T>
    : IRule<T> where T : class
{
    public Expression<Func<T, bool>> Expression { get; private set; }

    public Func<T, bool> Compiled { get; private set; }

    public ExpressionRule2(Expression<Func<T, bool>> expression)
    {
        Expression = expression;
        Compiled = expression.Compile();
    }

    public static implicit operator Expression<Func<T, bool>>(ExpressionRule2<T> item)
    {
        return item.Expression;
    }

    public bool Evaluate(T item)
    {
        return Compiled(item);
    }
}

Yes, I know, not the best naming with ExpressionRule2 but it’s a quick hack to get the blog post compatible with non linq to object sources. There’s actually nothing more to it. Of course I have put up a custom DbContext for Entity framework Code-first CTP 5, as well as added an Id to the customer.

public class StorageContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }

        public StorageContext()
            : base(@"data source=.;initial catalog=NiceLambdas;integrated security=SSPI;")
        {
        }
    }
public class Customer
{
    public int Id { get; set; }

    public int NumOfYearsAsMember { get; set; }
    public int CashSpent { get; set; }
}

Why this solution at all?

What this gives me:

  • A name to my rule.
  • I can have interfaces represent it and have a factory or IoC returning variations of the rule.
  • I can isolate it for testing.

Happy coding!

//Daniel

C#, Clean up your Linq-queries and lambda expressions

Part 2How to get it to work against non Linq to object sources

Last week something caught my eyes. How scattered business logic can become if you let your binary expressions be used “here and there” when matching entities against certain rules. Logic for a single entity, e.g Customer can be used all over your codebase. This article will show you a way to get around this and to get a central repository of rules/predicates that can be applied to entities and makes your daily unit test writing easier. I will use simple operator overloading for accomplishing this.

The example code can be downloaded here.

I have put together a testfixture with test going from ugly code to “more” beautiful code. The example is fictive and therefore not the best example for what I’m showing. The problem below might be best solved with simple code as Customer.IsBonusCustomer() which then contains the logic for determening this. But I want to show you a way to handle this if you instead want the logic outside the customer and don’t want the lambdas/linq queries scattered all over your codebase.

In the code I have made use of Func but you can of course use Expression<Func> if you need to parse the expression tree.

The problem

Identify customers that are considered to be bonus customers.

Rules:

  • A customer that has been member shorter than one year and has spent 3000 or more in our store.
  • A customer that has been member for one year or more and where money spent divided by the years is equal to or greater than 5000.

The solution

Lets start with the entity example which of course intentionally have been made simple.

public class Customer
{
    public int NumOfYearsAsMember { get; set; }
    public int CashSpent { get; set; }
}

The ugly ways

First, lets be clear: “No I don’t mean the Linq or Lambda syntax in it self when I say ugly”. I mean ugly as you get “small” (in best case) pieces of logic lying around in your queries.

[Test]
public void TheUglyWayUsingLinq()
{
    var bonusCustomers = 
        from c in _customers
        where
        (c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000) ||
        (c.NumOfYearsAsMember > 0 && (c.CashSpent / c.NumOfYearsAsMember) >= 5000)
        select c;

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}
[Test]
public void TheUglyWayUsingLambdas()
{
    var bonusCustomers = _customers.Where(c =>
        (c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000) ||
        (c.NumOfYearsAsMember > 0 && (c.CashSpent / c.NumOfYearsAsMember) >= 5000));

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}

Both of these examples are rather simple (seen to what you meet in different enterprise applications) but yet rather hard to read. Well of course not if you concentrate on just the algorithm but as a whole it is. First lets make it somewhat nicer. Lets extract the selectors so that we get a name in the Linq and Lambda expressions.

[Test]
public void SomewhatNicerUsingLinq()
{
    Func<Customer, bool> isFirstYearBonusCustomer = c => 
        c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000;

    Func<Customer, bool> isAfterFirstYearBonusCustomer = c => 
        c.NumOfYearsAsMember > 0 && ((c.CashSpent / c.NumOfYearsAsMember) >= 5000);

    var bonusCustomers = from c in _customers
                            where isFirstYearBonusCustomer(c) ||
                            isAfterFirstYearBonusCustomer(c)
                            select c;

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}
[Test]
public void SomewhatNicerUsingLambdas()
{
    Func<Customer, bool> isFirstYearBonusCustomer = c =>
        c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000;

    Func<Customer, bool> isAfterFirstYearBonusCustomer = c =>
        c.NumOfYearsAsMember > 0 && ((c.CashSpent / c.NumOfYearsAsMember) >= 5000);

    var bonusCustomers = _customers.Where(c =>
        isFirstYearBonusCustomer(c) ||
        isAfterFirstYearBonusCustomer(c));

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}

Slightly better and if we put the selectors in a class they can be reused.

The more beautiful way

Now lets write a test in a way I would like to read it.

[Test]
public void MaybeMoreBeautifulUsingRules()
{
    var bonusCustomers = _customers.Where(new IsBonusCustomer());

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}

How can I accomplish this?

Well it’s easy. Create a class that implements a implicit operator overloading for Func which then allows you to pass instances of this class into the IEnumerable.Where function.

public class ExpressionRule<T> 
    : IRule<T> where T : class
{
    public Func<T, bool> Expression { get; private set; }

    public ExpressionRule(Func<T, bool> expression)
    {
        Expression = expression;
    }

    public static implicit operator Func<T, bool>(ExpressionRule<T> item)
    {
        return item.Expression;
    }

    public bool Evaluate(T item)
    {
        return Expression(item);
    }
}

The next step is to create one representing the rule at hand IsBonusCustomer.

public class IsBonusCustomer 
    : ExpressionRule<Customer>, IIsBonusCustomer
{
    public IsBonusCustomer()
        : base(c =>
                (c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000) ||
                (c.NumOfYearsAsMember > 0 && (c.CashSpent / c.NumOfYearsAsMember) >= 5000))
    {
    }
}

Again, if you need to parse the expression tree the ExpressionRule class would look something like this.

public class ExpressionRule<T>
    : IRule<T> where T : class
{
    public Func<T, bool> Expression { get; private set; }

    public ExpressionRule(Expression<Func<T, bool>> expression)
    {
        //Do something with the lambda
        //...
        //...
        Expression = expression.Compile();
    }

    public static implicit operator Func<T, bool>(ExpressionRule<T> item)
    {
        return item.Expression;
    }

    public bool Evaluate(T item)
    {
        return Expression(item);
    }
}

Easier to test

By having the solution above you open up your code to be easy to test. Lets say we have a PriceLocator that uses this rule to determine the price for a customer. We want to test the discount algorithm and be sure that the rule for determining if a customer is a bonus customer, always evaluates to true.

public class PriceCalculator
{
    public IIsBonusCustomer IsBonusCustomer;

    public PriceCalculator()
    {
        IsBonusCustomer = new IsBonusCustomer();
    }

    public decimal Calculate(decimal basePrice, Customer customer)
    {
        return IsBonusCustomer.Evaluate(customer)
                    ? basePrice * 0.8M : basePrice;
    }
}

Now I can put up a fake and inject it to the price locator, so that the code under test becomes isolated.

[Test]
public void CanBeEasilyBeFaked()
{
    var alwaysBonusCustomerRuleFake = new Mock<IIsBonusCustomer>();
    alwaysBonusCustomerRuleFake.Setup(f => f.Evaluate(It.IsAny<Customer>())).Returns(true);

    var priceCalculator = new PriceCalculator { IsBonusCustomer = alwaysBonusCustomerRuleFake.Object };
    var priceWithDiscount = priceCalculator.Calculate(100, new Customer());

    Assert.AreEqual(80, priceWithDiscount);
}

I can now of course also test the IsBonusCustomer rule.

[Test]
public void CanBeTestedInIsolation()
{
    var firstYearBonusCustomer = new Customer { CashSpent = 3000, NumOfYearsAsMember = 0 };

    var rule = new IsBonusCustomer();

    ExpressionAssert.EvalAsTrue(rule, firstYearBonusCustomer);
}

That’s it. Again the examples above might be overkill since you could have placed methods directly on the Customer, but….

Why this solution at all?

What this gives me:

  • A name to my rule.
  • I can have interfaces represent it and have a factory or IoC returning variations of the rule.
  • I can isolate it for testing.

//Daniel

C# and abusive dynamic APIs

I read a blogpost last night about dynamic code and how it could be used to handle arguments passed in to a method, and it got me thinking. I exchanged a couple of tweets with about this and I really didn’t get any wiser, hence I guess I have to go and try out some Ruby, but thats another day.

The thing I don’t get is how someone, in a public API designed for use by others, generally can think dynamic args or a collection of args can be received by a method which in turn just selects X of the passed in args without even bother looking at the rest of them? How are the consumer supposed to know what to name the keys/members to get their elements processed? If a method takes a collection of arguments, I as a consumer, kind of expect all the elements to be visited. I don’t wan’t to crank up Reflector and look at the source to see what I should name the keys and members to get them processed.

Lets start with an over exaggerated example using say a generic Dictionary.

public class AddressParser
{
    public string BuildAddress1(Dictionary<string, string> args)
    {
        return string.Format("Street: {0}\r\nZip:{1} City: {2}\r\nCountry: {3}.",
            args["Street"], args["Zip"], args["City"], args["Country"]);
    }

    public string BuildAddress2(dynamic args)
    {
        return string.Format("Street: {0}\r\nZip:{1} City: {2}\r\nCountry: {3}.",
            args.Street, args.ZipCode, args.City, args.Country);
    }
}

So, how would you as a consumer know that the args being processed are:”Street, ZipCode, City and Country”. Should you test all of the common names of address attributes? “StreetName, StreetNumber, Zip, Area….”

I asked:

And how would I now as a consumer that every element has been visited?

Because you’re an awesome tester and you don’t rely on your API method signatures to tell you what to do.

So pull up your sleeves and put on that monkey suite. It’s time to do some exploratory API programming.

To be fair, the dynamic example has one huge advantage. If I miss to pass something to the Dictionary method I get a not so informative KeyNotFoundException. If I instead use the dynamic example I get a more detailed exception:

'f__AnonymousType0' does not contain a definition for 'Country'

Ok, of course you could be a good citizen and document your method but we all know where that ends up.

I don’t know about you, but in this scenario, I don’t want to be forced to be a Curious George programmer.

//Daniel

Let business scenarios be reflected in your code

I’m working with a project where I use something I call “scenarios”. The idea is that each scenario in the businessmodel is represented by three classes.

Command – Contains the inputdata needed to perform the Scenario. Is optional since the operation might not need any input parameters.

Scenario – Validates and Executes the Command and is where the logic is kept. It is not ment to cross boundraries. It also provides an eventmodel, publishing events for Validated, Executed etc.

Result – Contains the command (input data), any exception and violations generated by the Validation- or Execution step in the scenario, as well as scenariospecific outputdata.

The reason for why I wan’t this is that I want each scenario easily detected in my coding-model. I want to be able to quickly look in the solutionexplorer in the Scenarios namespace, and directly see what the system targets in the domain. By looking at the Command- and the Result-classes I can also see what the scenario accomplishes. By isolating each scenario-flow-logic to one single class, I hopefully achieve a more cohesive and readable class.

An example

The example is not drawn from the business model since it’s about signing in to the system, hence it’s sort of an indirect business scenario, since you can’t run the “Place order scenario” if you’r not an authorized user.

The shown example is about logging in to the system and is using OpenId in an Asp.Net Mvc 2 application. This concludes two steps. First a request has to be initiated to an OpenId-provider. Second, we need to handle the callback request from the provider, hence the enum LogOnSteps. (I guess it would have been more clear to put these in two different scenarios.)

[Serializable]
public enum LogOnSteps
{
    Initiate,
    Finalize
}

The Command contains properties that are required for Step 1 as well as a flag indicating where we are in the process so that the validation and execution in the scenario-class nows what to do.

[Serializable]
public class LogOnCommand
{
    public LogOnSteps Step { get; set; }

    public string OpenId { get; set; }

    public string ReturnToUrl { get; set; }

    public LogOnCommand(LogOnSteps step)
    {
        Step = step;
    }
}

The implemented scenario extends a baseclass so that boilerplate code for catching exceptions etc. is kept away. The scenario is defined in an interface and is accessed via an IoC-container.

public class LogOnScenario : Scenario<LogOnCommand, LogOnResult>, ILogOnScenario
{
    public IOpenIdAuthenticationService AuthenticationService { protected get; set; }

    public IMembershipService MembershipService { protected get; set; }

    public LogOnScenario(
        IOpenIdAuthenticationService authenticationService,
        IMembershipService membershipService)
    {
        AuthenticationService = authenticationService;
        MembershipService = membershipService;
    }

    protected override IViolations OnValidate(LogOnCommand command)
    {
        var violations = new Violations();

        if (command.Step == LogOnSteps.Initiate)
        {
            violations.AddIf(command.OpenId.IsNullOrEmpty(), new Violation(
                ResourceStrings.LogOnCommand_OpenId_IsRequired, CommandName, "OpenId"));
            
            violations.AddIf(command.ReturnToUrl.IsNullOrEmpty(), new Violation(
                ResourceStrings.LogOnCommand_ReturnToUrl_IsRequired, CommandName, "ReturnToUrl"));
        }

        return violations;
    }

    protected override LogOnResult OnExecute(LogOnCommand command)
    {
        return command.Step == LogOnSteps.Initiate
            ? HandleInitiateStep(command)
            : HandleFinalizeStep(command);
    }

    private LogOnResult HandleInitiateStep(LogOnCommand command)
    {
        var logOnResult = new LogOnResult
        {
            Command = command,
            MvcActionResult = AuthenticationService
                                .InitiateMvcAuthentication(command.OpenId, command.ReturnToUrl)
        };

        return logOnResult;
    }

    private LogOnResult HandleFinalizeStep(LogOnCommand command)
    {
        var logOnResult = new LogOnResult { Command = command };
        var openIdAuthentication = AuthenticationService.AuthenticateRequest();

        if (openIdAuthentication.Violations.IsNotEmpty)
        {
            logOnResult.Violations.Add(openIdAuthentication.Violations);

            return logOnResult;
        }

        var mapper = IoCContainer.Instance.GetInstance<IObjectMapper>();
        var identity = mapper.Map<OpenIdAuthentication, Identity>(openIdAuthentication);
            
        logOnResult.UserSession = new UserSession(identity);
        logOnResult.Member = MembershipService.GetByOpenId(identity.OpenId);

        return logOnResult;
    }
}

Since we want every scenario to return any caught exception and violations, we have a base-class that the ScenarioResults can extend, which contains members for this.

[Serializable]
public class LogOnResult : ScenarioResult
{
    public LogOnCommand Command { get; set; }

    public ActionResult MvcActionResult { get; set; }

    public IUserSession UserSession { get; set; }

    public Member Member { get; set; }
}

Now if we take a look at some consumer code, I think it gets a bit easier to understand, and the application controller only handles logic for controlling which view and viewdata should be presented.

Step 1 – Initiate the scenario

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(LogOnViewModel viewModel)
{
    if (!ModelState.IsValid)
        return View(viewModel);

    var returnToUrl = Url.AbsoluteUrlFromAction("AuthenticateOpenIdRequest");
    var command = new LogOnCommand(LogOnSteps.Initiate)
                      {
                          OpenId = viewModel.OpenId, 
                          ReturnToUrl = returnToUrl
                      };

    var scenario = IoCContainer.Instance.GetInstance<ILogOnScenario>();
    var scenarioResult = scenario.Execute(command);

    if (!scenarioResult.Succeeded)
    {
        this.HandleScenarioResult(scenarioResult);
        return View(viewModel);
    }

    return scenarioResult.MvcActionResult;
}

Step 2 – Finalize the scenario

public ActionResult Authenticate()
{
    WebUserSession.SetGuest();

    var viewModel = new LogOnViewModel(OpenIdProviders);
    var command = new LogOnCommand(LogOnSteps.Finalize);
    var scenario = IoCContainer.Instance.GetInstance<ILogOnScenario>();

    var scenarioResult = scenario.Execute(command);
    if (!scenarioResult.Succeeded)
    {
        this.HandleScenarioResult(scenarioResult);

        return View("LogOn", viewModel);
    }

    if (scenarioResult.Member == null)
        return View("SetupNewMembership");

    if (!scenarioResult.Member.IsActivated)
        return View("ConfirmMembership");

    WebUserSession.Set(scenarioResult.UserSession);

    if (WebUserSession.Current.IsAuthenticated)
        return Redirect("~/");

    return View("LogOn", viewModel);
}

That’s it.

//Daniel

Use extension methods to let your enums hold the logic.

I often stumble upon code checking values on enumerations to determine the state of some object or rule. At best, this code is extracted and put in a helper or utils class of some sort. Don’t! Use extension methods instead. It let’s you provide a name for the condition (rule) that you are checking, and it put’s it together with the enumeration.

Example
Lets say I have an enumeration with storage providers. Each provider might be able to store data virtually, hence I need the possibility of determining if it’s capable of this.

[Serializable]
public enum StorageProviders
{
    LuceneIo = 0,
    LuceneVirtual = 1
}

public static class StorageProvidersExtensions
{
    public static bool IsVirtual(this StorageProviders provider)
    {
        return provider == StorageProviders.LuceneVirtual;
    }
}

I can now act on the enumeration value it self.

...connectionInfo.ProviderType.IsVirtual()...

//Daniel