September 8, 2010

Loop through Enumerations in C#

UPDATE: As commenter Tr3v has pointed out, there's a simpler way to achieve this with Enum.GetValues which avoids the parsing. Code snippet was updated.

I recently found out it's pretty easy to iterate through enums by first getting the names of the enums and then parsing those back as enum.

Note that this Enum.GetNames method uses reflection internally to read the enum metadata in memory.

Not the biggest discovery of the year here. I'll tag it as self-archiving :)

kick it on
Shout it

July 22, 2010

Lazy Loading Ajax in ASP.NET MVC

I recently changed jobs and now work for an e-commerce company called We typically open new sales around 9am in the morning and immediately get a MASSIVE amount of traffic from that moment.

Of course the architecture behind our ASP.NET MVC frontend is made to handle that and we manage to keep a pretty good response time using a mix of caching techniques, content delivery networks and clever programming.

I was tasked with implementing a new "users who bought this also bought..." kind of feature you may see on most e-commerce sites. The processing time and data to load on the page are not negligible and that feature being displayed at the very bottom of the page, we might end up using a lot of additional resources for nothing if the user does not scroll down.

It was decided that we would display these frequently combined items only if the area where it's supposed to load comes into the user's viewport - that is if it's displayed on the user's screen whether he scrolled down or his screen is big enough to handle the whole page. Amazon uses the technique on its homepage (scroll down to the bottom).

I found a pretty neat jQuery plugin to handle just that, it can be found at:

The frequently-ordered block has a display:none property. While remaining invisible it can be attached to an event called 'inview' that will be triggered only once on the page (hence the ".one").

The next step is standard MVC Ajax. The loadFrequentlyOrderedProducts function calls the Controller Action and returns the data from the partial:

The Action would be fairly straightforward:

That's an interesting technique for high traffic sites often dealing with a trade-off between high availability and rich dynamic features.

March 3, 2010

ASP.NET MVC : Injecting & Mocking an IRepository

If you are already familiar with ASP.NET MVC, you have probably seen the repository pattern in a few examples (such as NerdDinner), maybe you even use it in your own app.

One of the most frequent way to hot-plug a Repository class into a controller is to use the Strategy Pattern. But while an application evolves, you might want to centrally manage your wiring within a provider, that's what Dependency Injectors are for.
However lots of Dependency Injectors - or IoC containers at large - such as Unity or Castle Windsor contain a plethora of features and often rely heavily on XML configuration, making them overkill for smaller projects.
Ninject makes it relatively effortless to set up a DI. It just reached version 2.0.

In this post we will see how to:
  • Quickly inject a Repository in a controller with Ninject
  • Mock the IRepository interface in your tests with the Ninject.Moq plugin

Get the bits

Here's where to get these dependencies:
Ninject2 (with Ninject.Web.Mvc)
Ninject.Moq plugin (download and build)

Creating a Simple Repository

Let's start a quick MVC app with a Repository.
The Winter Olympics provide us with a simple Model composed of the following types:

Our Repository class looks like this:

Of course the first thing we'll do is to extract an IRepository interface from this class. We can at this point create a few Action Methods in an AthletesController to send some data to the view.

Injecting an IRepository into a Custom Controller

We'll now create a custom Controller by extending the MVC Controller class. Our extended type will contain our injected IRepository and all our controllers will inherit from it. Notice the [Inject] attribute:

We only need two things to set up Ninject and bind the Repository implementation as an IRepository in our controller instance:

-First, a Ninject Module class where the binding occurs:

-Second, we need to change our Global.asax so our MvcApplication inherits from NinjectHttpApplication instead. That's also where the override CreateKernel() references our binding module. Finally, we'll move the Application_Start content under the OnApplicationStarted override and call RegisterAllControllersIn() with the current assembly as parameter.

Ninject is now set up. At any time during development you can switch your IRepository implementation by changing the bindings of the NinjectModule.

Mocking an IRepository with Ninject

Because our Repository implementation uses some sort of database, we don't want our Unit Tests to depend on it. It is generally recommended to test persistence layers in separate integration tests.

For our Unit Tests, we set up a fake IRepository implementation with Moq.
The Ninject.Moq plugin integrates our mock in our controller by using a MockingKernel (as opposed to the StandardKernel previously seen in our Global.asax).

Let's create a test context in which we set up the mocked injection.
Notice how the kernel injects a mock in the controller and how we're then able to retrieve the mock to set it up.

[Thanks to Miguel Madero for helping me figure out this last part]

Our test class inherits from this context and our test methods mimic the behavior of the application, goal achieved.

[Requires Visual Studio 2010 RC / ASP.NET MVC2 RC2]

Wrapping Up

In this post we saw how to inject our Repository implementation as an IRepository member of the controller.

Finally we switched our implementation for a mocked Repository in our tests.

We clearly saw a case for injection as our application is now loosely coupled and our MVC is testable. We could switch from a database to an XML file as persistence layer without affecting the client or the tests.

kick it on
Shout it

February 18, 2010

Random News, Links & Thoughts

C# creator Anders Hejlsberg's 1984 laptop on which he developed TurboPascal has been sold on eBay for a final auction price of $2,025. That makes 1 dollar per octet of memory to a Haiti relief fund.

Because my current job involves constant travel I have to work with a laptop. For you all laptop workers out there I highly recommend you to get a laptop stand and a keyboard (additional screen should be mandatory also). My back problems magically ceased since I got them. For the keyboard I chose an IBM-like sturdy and clickety Cherry keyboard.

While going in a crowded elevator, have you ever thought it's a Stack Collection (LIFO)?

Speaking of Stack Overflow, did you know StackOverflow jobs section ask companies to fill in the Joel Test on software? I think it's clever.

Apparently NoSQL is all the rage these days but I don't get it YET. There's a podcast on Herding Code that confused me even more (good debate though).

There's a missing command in Visual Studio: Collapse All Projects and Folders in Solution Explorer. Thank god someone made a macro for that.

UPDATE: The Power Commands for Visual Studio already did that from the context menu.