Convert non-generic type to generic type in c#

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

Just today when mussing with List controls and their SelectedItems property came to a point where I needed to convert their SelectedItems property to a generic list (because god knows why it is non-generic).

I needed this because I wanted to query over the selected items and LINQ doesn’t work with non-generic lists so…

Turns out the solution is quite simple:

IEnumerable<string> genericizedItems = itemsListBox.SelectedItems.OfType<string>();

Works like a charm, hope this helps!

Cheers!


Filed under: .NET, C#
Written on: 12 Jun 2008 · No Comments »

Actively enforcing the aggregate root boundaries by setting the child entities constructor as Internal

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5 out of 5)
Loading ... Loading ...

Some more Aggregate Root thinking…

If a child entity in an Aggregate Root should not be accessible outside the boundaries of a Root, why should you be able to instantiate it?

If I mark their constructor with internal, it should be only instantiated from a Root (root should know how to instantiate it), this would also allow us to play with them only within the Model project, but others should get it via Root (like Services, Client applications and others).

Example…

public class Car : EntityBase<int>, IAggregateRoot
{
    public Car()
    {}

    public Wheel RightWheel
    {
        get
        {
            return new Wheel(”Right”);
        }
    }
}

and Wheel (child entity):

public class Wheel : EntityBase<int>
{
    private string _wheelType;

    internal Wheel(string wheelType)
    {
        _wheelType = wheelType;
    }
}

Again… my insecurities and concerns come from previous reasons as with the previous post:

Pros:

  • Explicitness
  • Active enforcing of rules

Cons:

  • Cluttering the design
  • Running with scissors… we like running with scissors, although we probably won’t fall on them

What do you think?

I am having double thoughts.


Filed under: Akua.Framework, C#, DDD
Written on: 19 May 2008 · No Comments »

Actively enforcing Aggregate Roots 1…1 relation to Repositories

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 3 out of 5)
Loading ... Loading ...

I am toying with an idea.

One of the pillars of DDD is the pattern of Aggregate Roots and their boundaries. Also the fact that our Repositories should only work against Aggregate Roots and not Entities themselves.

As I like explicitly to enforce my rules I am toying with an idea of a marker interface IAggregateRoot which would not contain ANY elements, just exist.

What I could do then is put a Generics constraint on my Repository like:

IRepository<EntityT, IdentifierT> where EntityT : EntityBase<IdentifierT>, IAggregateRoot

Then all my entities which are Aggregate Roots should be *marked* as one:

Category : Entity<int>, IAggregateRoot

Now… I both like and dislike this, I can’t put my mind what is better yet :(

Pros:

  • Allows us to actively enforce DDD rules and make the users of this framework think about what their roots are and not generalize everything
  • Nice explicitness of knowing exactly which entity is a Root and which is not
  • In any future gives me a leverage to find out if an Entity is a Root or not if for any reason I need to get this info

Cons:

  • Design noise, in it’s sense it doesn’t bring anything concrete to the table, forcing my users to do this one extra step (mark an Entity) and also clutter the design doesn’t sound too thrilling
  • What would be a default setup for an entity? Probably that it is an Aggregate root (think code generating your initial model from database or any other resource). Doesn’t this then go against it? Everything is a Root. Also knowing the users, the simplest thing will be to mark them all with IAggregateRoot
    Uhhh… Tough descision.

What do you think?


Filed under: Akua.Framework, C#, DDD
Written on: 19 May 2008 · No Comments »

Linq Expressions for creating objects

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

As you might know I am building my own Repositories for NHibernate as a part of my upcoming “glue” framework.

A part of that implementation are various transformers and default transformation strategies for things like tuple to object transformations (dto) and data reader to object transformations (dto)… the first is used when using projections, the later when calling stored procedures.

I’ve choosen to do this via Linq Expression Trees because I’ve been frankly scared to use the plain DynamicMethod till now, and as Expression trees do generate them in the background it seemed like a great way to do runtime code generation.

Probably in the future I will write some more detailed posts on the implementation itself and more on the reasons, but for starters here are a few links which will help to you give an insight into the power and how LINQ can be used waaaay beyond querying:

http://rogeralsing.com/2008/02/28/linq-expressions-creating-objects/
http://blogs.msdn.com/meek/archive/2008/04/25/using-linq-expressions-to-generate-dynamic-methods.aspx
http://blogs.msdn.com/meek/archive/2008/05/13/using-linq-expressions-to-generate-dynamic-methods-ii.aspx

Enjoy!


Filed under: .NET, Akua.Framework, C#
Written on: 17 May 2008 · No Comments »

Testing methods which do yield return (deferred execution problem)

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4.5 out of 5)
Loading ... Loading ...

Had a funny problem today. I’ve written a spec (tests) for a code that should have iterated over a collection of items and with some conditions do a yield return for each of them.

In it’s form, its a very simple piece of code, but somehow I could not for the light of me get the spec (test) to pass. It always seemed that the code didn’t even execute… I kept thinking to myself, WTF? This code is simple, and it does what it needs to!? Why doesn’t it pass? (as you can imagine I got a bit frustrated).

Then I remembered one *small* bit… yield return coupled with IEnumerable provides the deferred execution for my code, so this example:

image

When called like this in my spec (test):

image 

Actually does nothing at all, so my specs would fail… it was really frustrating.

What can be done?

Actually, three things:

image

So:

s1) We are enumerating like we are expected to. This will execute the functionality

s2) We are manually assembling the enumerator and asking him to call our functionality

s3) We are feeding the deferred execution functionality to a new List which internally then executes it


I personally prefer and use option 3 now.

Hope this helps someone, it sure would me if I’ve remembered it out earlier.

Cheers!


Filed under: .NET, Best practices, C#
Written on: 14 May 2008 · No Comments »

Prefer Early exit strategies over nested if’s and conditionals

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

So, quite a simple rule… someone likes it, someone doesn’t.

I’ve seen over and over these kinds of examples:

image

This is probably to simple of an example, but should prove a point.

To some extended, this code (because it’s stupid and simple) could be converted to:

image

But what I would advise you is that instead you fail early with the logic instead of branching and complicating the code like above (keep in mind once more that that above is too simple of an example)

How would you fail early in this case?

 image


What do you think? How do you do it?

Cheers!


Filed under: .NET, Best practices, C#
Written on: 14 May 2008 · No Comments »

Partitioning NHibernate IRepository to achieve better SRP level (hopefully!)

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

As you might know for some time now I’ve been working on my own NHibernate implementation. Largely it is influenced by Ayende’s great Rhino.Commons for NHibernate, but what I like to think is that it took a little bit different direction, and that the details of implementation are what it makes really different (not better or worse… just different).

With this in mind I am working on my own IRepository implementation and have found that it actually has at least 3 reponsibilities it must fullfill:

  1. It must be able to Save/Update/Delete/Query Entities
  2. It must be able to Query for DTO’s (via projections)
  3. It must be able to call Stored procedures

Now, with Ayende’s REALLY great implementation all this is a part of the main IRepository interface, what I’ve decided is that in my implementation they will be split:

  • IEntityRepository
  • IStoredProcedureRepository
  • IProjectionRepository

This allows me to split the responsibilities more accurately over them. Some of the differences:

  • IEntityRepository<EntityT> is full featured - it can both query and save/update/delete mapped entities
  • IStoredProcedureRepository contains only methods to call stored procedures
  • IProjectionRepository also only contains querying possibilities, it can query very similary to Entity repository, difference being that here you define the projections as well and thus tranform the result to a DTO or something else. Also, instead of defining the resulting type on the repository level (IRepository<T>), here you define it on a query level (.Find<T>….)

What do you think of a such idea?

I have to mention that the first two repositories are already made (Entity and Stored procedure), and are fully tested (spec’d out).

Ill describe how the current ones look in a series of upcoming posts, but they do contain some neat things.

Cheers!


Filed under: Akua.Framework, BDD, C#, NHibernate
Written on: 21 Apr 2008 · No Comments »

Context driven Fluent interfaces via Chameleon pattern

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Before anyone flames me with bad comments, let me do a little disclaimer:

  • I am not a pattern authority; there is a big chance that this already exists under a different pattern. If so, please let me know and I will start using the original name instead of mine.
  • I am calling it by name so that in future I can easily refer to the beast by name and not be ambiguous about it.

So… let the interface extravaganza begin…

So you want to make a Fluent interface in c#, right? You want your interface to bend and shape itself depending on the how it’s used, right?

A little example; I was lately building my own Repository implementation for NHibernate and for the Find part, I want to build it as a fluent interface instead of having a parameter explosion smell.

I want to be able to do something like:

Repository.Find(when.Customer.Name == “Vladan”)
              .Order(on.Customer.Id)
              .StartFrom(10)
              .LimitTo(20)
              .All();

Let’s dissect requirements for each of the methods (this is only a subset of requirements I’ve put in front of myself when defining this interface)

- Find should be able to chain to Order, StartFrom and All
- Order should be able to chain StartFrom and All
- StartFrom should be able to chain only LimitTo
- LimitTo should be able to chain Order and All

Besides the specified allowed chain, the methods should not allow calls to other methods in the chain (e.g. “StartFrom” should not be allowed to call “All” directly, or “Order” should not be able to chain “LimitTo” directly) – or in other words, our method calls should be presented to us depending on the context of their usage, ok?

How do we implement this? Well, let’s start by defining for each method call above an interface:

public interface IFindQuery
{
}
public interface IFind
{
}
public interface IOrder
{
}
public interface IStartFrom
{
}
public interface ILimitTo
{
}

Now let’s chain them together depending on the allowed chaining requirements:

public interface IFindQuery
{
    IFind Find(…);
}
public interface IFind
{
    IOrder Order(…);
    IStartFrom StartFrom(…);
    List<OfResult> All();
}
public interface IOrder
{
    IStartFrom StartFrom(…);
    List<OfResult> All();
}
public interface IStartFrom
{
    ILimitTo LimitTo(…);
}
public interface ILimitTo
{
    List<OfResult> All();
}

Still with me?

Now, can you see that we’ve defined the context of chaining these methods? By being explicit about it, we were able to limit the context only to those operations we want to allow in a given moment.

How do we implement this?

Well the great thing is that now I can implement the complete Find part of my repository as a single object that implements all these interfaces and acts as a Chameleon – or better said, that changes its (inter)face depending on the situation.

Let’s try it:

public class FindQueryImpl : IFindQuery,
                                       IFind,
                                       IOrder,
                                       IStartFrom,
                                       ILimitTo
{
    public IFind Find(…)
    {
        …do something with it…
        return this;
    }
    IOrder Order(…);
    {
        …do something with it…
        return this;
    }
    IStartFrom StartFrom(…);
    {
        …do something with it…
        return this;
    }
    ILimitTo LimitTo(…);
    {
        …do something with it…
        return this;
    }
    List<OfResult> All()
    {
        …do something with it…
        return some_result;
    }
}

As you can see, by always returning a self reference, only under a different (inter)face we become context driven with a really simple object graph to support it.

And that ladies and gents… makes our chameleon. One object which shows it’s (inter)face based on context.

One thing to note though… this object would probably in very complex scenarios become too big and complex to maintain, so in those cases you should probably try to take it to the next level by partiotioning the chameleon to several smaller ones.

What do you think?


Filed under: C#, Patterns
Written on: 04 Apr 2008 · No Comments »

NAnt + VS2008 csproj annoying thing

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Ok, so you have an automated script for building your system… yes?

You decide to plug in in another your c# projects created by Visual Studio 2008 and run them via msbuild task and then it brakes… MSBuild tells you that it can’t find c# targets.

You go to your project file and see that it actually uses now a new property for setting up the tools path which obviously NAnt (or the community contrib task MSBuild) cannot resolve:

<Import Project=”$(MSBuildToolsPath)\Microsoft.CSharp.targets” />

The fix is actually quite easy, but still it annoyes me :)

Change the above to the old version:

<Import Project=”$(MSBuildBinPath)\Microsoft.CSharp.targets” />

And it works like a charm! only it annoyes me :)

Hope this helps someone!

Cheers!


Filed under: C#, VS2008
Written on: 20 Jan 2008 · No Comments »

Naming in my BDD-style Specification base class

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

One thing I really like in my BDD specification base class (found here) is how I’ve renamed the Rhino Mocks - Record - Playback model to be more expressive.

However, there is one part I am really not happy with… the naming of the Playback using statement.

Currently I’ve put it of as “What_SUT_Should_Result_To” but that doesn’t really express what the code does inside… my suspicions were confirmed this morning also by JP who mentioned that it looks good, but that he is not in love with that method name.

So, what could I call it to make it express intent better? Here are some examples:

- How_SUT_should_be_used
- When_SUT_is_used
- When_SUT_functionality_is_used
- When_SUT_is_used_like
- When_SUT_functionality_is_used_like
- When_SUT_is_called
- When_SUT_functionality_is_called

The sound of “When_SUT_functionality_is_used_like” sounds good in combination of the previous using statement:

using (How_SUT_should_Behave) {
           …
}

using (When_SUT_functionality_is_used_like) {
            …
}

What do you think? Do you have any ideas?

Cheers!


Filed under: BDD, C#
Written on: 16 Jan 2008 · No Comments »

BDD and ASP.NET MVC… a match made in heaven

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

Whilst preparing for my user group session on MVC I’ve upgraded my BDD base class (actually subclassed it) with specifics related to specifying the behavior of MVC routes and controllers.

I’ve made for starters 2 new classes:

public class MvcMockedHttpContext
{
    private readonly MockRepository _mocks;
    private IHttpContext _context;          

    public MvcMockedHttpContext(MockRepository mocks)
    {
        _mocks = mocks;
    }          

    private void _CreateMocked()
    {
        _context = _mocks.DynamicMock<IHttpContext>();          

        SetupResult.For(_context.Request)
		.Return(_mocks.DynamicMock<IHttpRequest>());
        SetupResult.For(_context.Response)
		.Return(_mocks.DynamicMock<IHttpResponse>());
        SetupResult.For(_context.Session)
		.Return(_mocks.DynamicMock<IHttpSessionState>());
        SetupResult.For(_context.Server)
		.Return(_mocks.DynamicMock<IHttpServerUtility>());          

        _mocks.Replay(_context);
    }          

    public IHttpContext ReturnMocked
    {
        get
        {
            if (_context == null) _CreateMocked();          

            return _context;
        }
    }
    public MvcMockedHttpContext FakeoutUrlRequest(string url)
    {
        if (_context == null) _CreateMocked();          

        SetupResult.For(_context.Request.AppRelativeCurrentExecutionFilePath)
                        .Return(url);
        SetupResult.For(_context.Request.PathInfo)
                        .Return(string.Empty);          

        return this;
    }
    public MvcMockedHttpContext FakeoutApplicationPath(string path)
    {
        if (_context == null) _CreateMocked();          

        SetupResult.For(_context.Request.ApplicationPath).Return(path);          

        return this;
    }          

}

Which I use to mock out the HttpRequest quickly and it serves me as a small mock out DSL for often used tasks with mocking the HttpRequest

Second part is the upgraded specification class:

public class MvcContextSpecification : ContextSpecification
{
    public MvcMockedHttpContext HttpContext
        {
            get
            {
                MvcMockedHttpContext context = new MvcMockedHttpContext(Mocks);
                return context;
            }
        }          

    public TController
                  CreateTestableControllerOf<TController>
                                                (string routeDataController,
                                                 string routeDataAction,
                                                 params object[]
                                                        paramsForControllerConstructor)
        where TController : Controller
    {
        TController controller =
                            CreateMockOf<TController>(paramsForControllerConstructor);          

        RouteData routeData = new RouteData();
        routeData.Values.Add(“Controller”, routeDataController);
        routeData.Values.Add(“Action”, routeDataAction);          

        IHttpContext context = HttpContext
                                    .FakeoutApplicationPath(“/”)
                                    .ReturnMocked;          

        controller.ControllerContext
                     = new ControllerContext(context, routeData, controller);          

        return controller;
    }          

    public bool HasActionActionAttribute<TController>
                                       (Expression<Action<TController>> action)
    {
        StringBuilder sb = new StringBuilder();
        MethodCallExpression call = action.Body as MethodCallExpression;
        if (call == null)
            throw new InvalidOperationException(“Expression must be a method call”);
        if (call.Object != action.Parameters[0])
            throw new InvalidOperationException(“Method call must target lambda argument”);          

        Attribute attribute
                       = Attribute.GetCustomAttribute(call.Method,
                                                      typeof(ControllerActionAttribute));          

        return (attribute != null);
    }
}

These 2 classes are my base for BDD with MVC (although admittedly this is for the combination of TDD and BDD, because although I am mostly testing the behavior at some parts I am testing the configuration as well)

Now comes the sweet part… how does this look implemented?

Let me show you an example of specifying the routes:

[Specification]
public void And_the_Selected_route_data_should_resolve_default
                                   _route_when_default_url_is_received()
{
    using (How_SUT_should_Behave)
    {
        _httpContext = HttpContext
                            .FakeoutUrlRequest(“~/default.aspx”)
                            .ReturnMocked;
    }          

    using (What_SUT_should_Result_to)
    {
        RouteData routeData = _routes.GetRouteData(_httpContext);          

        Assert.IsNotNull(routeData);
        Assert.AreEqual(“home”, routeData.Values["controller"]);
        Assert.AreEqual(“index”, routeData.Values["action"]);
    }
}

Sweet, isn’t it? Let me show the controllers:

[Context]
public class When_OrdersController_List_action_is_called
                                         : MvcContextSpecification
{
    [Specification]
    public void Then_List_view_should_be_displayed_and_OrdersService
                                                 _should_get_the_data_for_view()
    {
        IOrdersService mockedOrdersService = CreateMockOf<IOrdersService>();          

        OrdersController controller
                  = CreateTestableControllerOf<OrdersController>(“orders”,
                                                                 “list”,
                                                                 mockedOrdersService);          

        IList<Order> dummyOrders = _GetDummyOrders();          

        using (How_SUT_should_Behave)
        {
            Expect.Call(mockedOrdersService.ListAll()).Return(dummyOrders);          

            controller.RenderView(“List”, dummyOrders);
        }          

        using (What_SUT_should_Result_to)
        {
            controller.List();
        }
    }          

    [Specification]
    public void And_List_action_should_have_an_action_attribute()
    {
        Assert.IsTrue(HasActionActionAttribute<OrdersController>(x => x.List()));
    }          

    private List<Order> _GetDummyOrders()
        {
            return new List<Order>{
                            new Order(),
                            new Order(),
                            new Order()
                        };
        }
}

I’ve mentioned this to Joe Ocampo… I am struggling with myself to try to write the vanilla unit tests now for my session so that the attendees can more easily grasp the concepts in testing the MVC controllers and routes, and I must admit that… I DON’T WANT TOOO!!! I like my specifications, they feel so “right”.

What do you think? As with the previous BDD article… I would love your comments is this any good or bad?

Cheers!


Filed under: ASP.NET MVC, BDD, C#
Written on: 13 Jan 2008 · No Comments »

My variation of the BDD style specification base class

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

So lately I’ve been playing with BDD at home trying to *grok* the idea completely… as many people have said it in the past, one just needs to look pasted the *test* naming and understand your not doing BDD by naming your tests in natural sentence way… that’s just the tip of an iceberg.

However, to fully grasp the concept (I am still not 100% sure I have, but I am somewhere around hitting the target) one thing you definitely need is to bring the expressiveness in your tests (there I go again… Specifications) a few notches up to see the bigger picture.

So what I’ve done is… I took JP’s spec base class:

http://www.jpboodhoo.com/blog/BDDSpecificationBaseClass.aspx

…gave it my own touch and out came my version which is for me personally allot more expressive in it’s intent to describe the behavior of a functionality.

One great thing is that JP implemented and I followed Rhino Mocks and AutoMockingContainer which makes testing or specifying things allot better, faster and more natural (read JP’s article to get the idea of the full power of his Spec base).

Here it is my way:

public abstract class ContextSpecification
{
    private MockRepository _mocks;
    private AutoMockingContainer _container; 

    protected MockRepository Mocks
    {
        get { return _mocks; }
    }
    protected AutoMockingContainer Container
    {
        get { return _container; }
    } 

    [SetUp]
    public void BaseSetup()
    {
        _mocks = new MockRepository();
        _container = new AutoMockingContainer(_mocks);
        _container.Initialize(); 

        Before_Each_Specification();
    }
    [TearDown]
    public void TearDown()
    {
        After_Each_Specification();
    } 

    protected virtual void Before_Each_Specification()
    {
    }
    protected virtual void After_Each_Specification()
    {
    } 

    protected IDisposable How_SUT_should_Behave
    {
        get { return Mocks.Record(); }
    }
    protected IDisposable What_SUT_should_Result_to
    {
        get { return Mocks.Playback(); }
    }
    protected void Verify_Behavior_of(object mock)
    {
        _mocks.Verify(mock);
    }
    protected void Verify_Behavior_of_All_Objects()
    {
        _mocks.VerifyAll();
    }
    protected void Replay_Specified_Behavior_of(object specifiedObject)
    {
        Mocks.Replay(specifiedObject);
    }
    protected void Replay_Specified_Behavior_of_All_Objects()
    {
            Mocks.ReplayAll();
    } 

    protected T Mock<T>() where T : class
    {
        return _container.Get<T>();
    }
    protected T Create<T>()
    {
        return _container.Create<T>();
    } 

    protected void ProvideAnImplementationOf<Interface, Implementation>()
    {
        _container.AddComponent(typeof(Implementation).FullName,
                                        typeof(Interface),
                                        typeof(Implementation));
    }
    protected void ProvideAnImplementationOf<Interface>(object instance)
    {
        _container.Kernel.AddComponentInstance(instance.GetType().FullName,
                                            typeof(Interface), instance);
    } 

    protected IEnumerable<T> CreateEnumerableMockOf<T>()
    {
        return CreateMockOf<IEnumerable<T>>();
    }
    protected Interface CreateMockOf<Interface>(params object[] paramsForConstructor)
    {
        return Mocks.DynamicMock<Interface>(paramsForConstructor);
    }
    protected Interface CreateStrictMockOf<Interface>(params object[] paramsForConstructor)
    {
        return Mocks.CreateMock<Interface>(paramsForConstructor);
    }
    protected Interface CreatePartialOf<Interface>(params object[] paramsForConstructor)
                            where Interface : class
    {
        return _mocks.PartialMock<Interface>(paramsForConstructor);
    }
    protected Interface CreateStubOf<Interface>(params object[] paramsForConstructor)
    {
        return _mocks.Stub<Interface>(paramsForConstructor);
    } 

}

And how do I use it, well it’s quite simple. Here is an example of the *loong* way-round specifying the behavior of an ASP.NET MVC route.

First my Specification template imports these:

using Context = MbUnit.Framework.TestFixtureAttribute;
using Specification = MbUnit.Framework.TestAttribute;

Then I use them like this:

[Context]
public class When_RouteContainer_is_configured : ContextSpecification
{
    private RouteCollection _routes;
    private IHttpContext _httpContext; 

    protected override void Before_Each_Specification()
    {
        _routes = new RouteCollection();
        RouteContainer.Initialize(_routes);
    } 

    [Specification]
    public void Then_RoutesCollection_should_be_initialized()
    {
        Assert.IsNotNull(_routes);
    } 

    [Specification]
    public void And_RoutesCollection_should_contain_2_routes()
    {
        Assert.AreEqual(_routes.Count, 2);
    } 

    [Specification]
    public void And_the_Route_data_should_resolve_default_route_when_default_url_is_received()
    {
        using (How_SUT_should_Behave)
        {
            _httpContext = CreateMockOf<IHttpContext>(); 

            IHttpRequest request = CreateMockOf<IHttpRequest>();
            SetupResult.For(_httpContext.Request).Return(request); 

            Replay_Specified_Behavior_of(_httpContext); 

            SetupResult.For(_httpContext.Request.AppRelativeCurrentExecutionFilePath)
                            .Return(“~/default.aspx”);
            SetupResult.For(_httpContext.Request.PathInfo)
                            .Return(string.Empty);
        } 

        using (What_SUT_should_Result_to)
        {
            RouteData routeData = _routes.GetRouteData(_httpContext); 

            Assert.IsNotNull(routeData);
            Assert.AreEqual(“home”, routeData.Values["controller"]);
            Assert.AreEqual(“index”, routeData.Values["action"]);
        }
    }
}

Notice a few things:

  • Usage of different attribute naming to express intent
  • Usage of When…Then…And naming to express continuity
  • Expressiveness of the specification itself - notice the last one - read it from bottom up - The result of the work done with SUT, or When SUT is used in this particular way (”What_SUT_should_Result_to”) it’s behavior should be (”How_SUT_should_Behave”) …

What do you think? Comments would be appreciated.

If anyone is interested in the real code, it will be published in the near future as part of my (future) code repository.

Cheers!


Filed under: ASP.NET MVC, BDD, C#
Written on: 13 Jan 2008 · 2 Comments »

Why use IoC and Containers?

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

A question came up on the Alt.Net mailing list asking why would you use IoC and Containers.


I think Ayende summed it up real good:

“Is is a pattern that is useful when you are already doing the right things, then you begin to feel the pain of managing all the moving pieces, at which point the container comes in and manages that for you.
I’m going to have a post about it soon…”


Enough to say that I’ve felt the pain… and used the pain killer :)


It’s a great idea, and when I’ve implemented Windsor on the project I am working on currently, it has helped me a great deal.

My next step is to replace XML configuration with Ayende’s great Binsor.

 

Cheers!


Filed under: Best practices, C#
Written on: 08 Dec 2007 · No Comments »

Oh nooo… please stop… and other feelings when reading posts about PetShop code

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

It just hurts too much.

When reading about code like this, and especially code that should be an “good architectural principles” and “basic and advanced coding concepts” example it just hurts me to see what people write… believe me people… IT HURTS!

 

I cannot imagine that at any point in time (one common argument is that this is an *old* code, and an outdated example) this was considered good - no matter how old the code is - bad things are bad, terrible practices are terrible. Someone should really stop and scratch their heads before calling something good.


Now, if you want to read the post that disturbed me this morning, go here:

http://ayende.com/Blog/archive/2007/11/28/Code-review-The-PetShop-Application.aspx

 

@Ayende: I feel your pain man. No one should be put to this - no one deserves it.


Ok, I need some more coffee…


Filed under: .NET, C#, General
Written on: 28 Nov 2007 · No Comments »

Replace switch statement + enum combo with a little fluent interface

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.75 out of 5)
Loading ... Loading ...

Well I would rather say, fluentish interface as it is only a tiny implementation of the idea.

As you might know I am against switch statement + enumeration combination in once code… I became grown to a habit of getting that unpleasant feeling in my stomach when I see that in code. Not that I don’t like the language constructs as such… but simply, often when they are a sign of bad programming practices which I’ve done (hopefully only in the past if I can help myself) and see other people do as well.

So, a little bit more concrete. You often write something like:

fluentconfig3

Lets say this is the standard way of doing it.

Some of the problems I have with this approach is:

  • When adding a new timeout value you are doing changes in more then one place
    (enum + dreaded switch, not to mention if you have to repeat the logic somewhere else)
  • It’s not as readable and as clean as it can be

The other way that you could do it (which I like much more then the previous one):

fluentconfig2

Now this I like :)

Hope this give you some ideas for your own code.

Cheers!


Filed under: Best practices, C#
Written on: 20 Nov 2007 · No Comments »

Being professional…

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Can you imagine being a professional and writting a stored procedure for a client like this?





The guy got fired of course, not because of this procedure… but because of his attitude which was equal to this procedure.

Aargh!


Filed under: C#
Written on: 09 Nov 2007 · No Comments »

Object disposal in c#

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 4 out of 5)
Loading ... Loading ...

A question came up on the mailing list about what is the equvivalent for object disposal to the using() statement.

Here it is, enjoy!





Filed under: C#
Written on: 07 Nov 2007 · No Comments »

A very interesting post on Visitor, Double Dispatch and Composite patterns…

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

You know that one blog post which you leave for the weekend? Maybe print it out? Re-read it several times while drinking your first morning coffee on Sunday?

This is one of those posts… I’ve printed it on Friday for the weekend, left it for my first Sunday coffee in the sun by the sea and enjoyed reading it several times over - that’s how much I’ve liked it :)


As I am kind of new to the Patterns and Principles scene (well not new actually, more seriously paying attention) I reall enjoy articles like these, especially from people like Jeremy which explain all the right details with great timing.


Go check it out:

http://codebetter.com/blogs/jeremy.miller/archive/2007/10/31/be-not-afraid-of-the-visitor-the-big-bad-composite-or-their-little-friend-double-dispatch.aspx


Hmm… maybe I can read it again tommorow morning before work (again with my first daily coffee)? :)

Enjoy!




Filed under: C#
Written on: 04 Nov 2007 · No Comments »

With respect to “Imports alias” post by Mark Smith - C# using alias

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

As mention in the post title… Mark wrote a post on how to alias the Imports with VB.NET (here: http://weblogs.asp.net/marksmith/archive/2007/10/11/imports-alias.aspx), well how would you do it in C#?




Hope this helps someone :)

Do you know any obscure bits like these?



Cheers!


Filed under: C#
Written on: 11 Oct 2007 · No Comments »

Scott Guthrie to announce ASP.NET MVC at ALT.NET!

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Finally!

Too bad I am not there… personally I would rather be there then on TechEd.

Ok.. back to the subject… Earlier this year on the MVP summit in Seattle Scott Guthrie announced that they might (finallly :)) build a real MVC framework.

Well… seems they were woring hard on it and now finally Scott is ready to go public with some of the concepts as Jeffrey mentiones here:

http://codebetter.com/blogs/jeffrey.palermo/archive/2007/10/05/altnetconf-scott-guthrie-announces-asp-net-mvc-framework-at-alt-net-conf.aspx


By the things he is saying it will be pretty good… I just hope someone will make a video of Scott’s presentation so I can view it :(

Can’t wait for Scott to publish some more details himself!




Filed under: ASP.NET, ASP.NET MVC, C#, Interesting sites
Written on: 06 Oct 2007 · No Comments »