About this blog
November 16, 2016

I briefly had a blog hosted on Blogger from 2009 to 2010 so I thought it’d be fun to import these posts from my C# days and use a markdown based site generator on a github page. Jekyll’s default design and structure didn’t feel right somehow and I opted instead for middleman which is also made in Ruby.

7 years have passed and my job has kept changing in the meantime - from C# to nodeJS and React, from IIS on premise to AWS lambdas, from bash deployment scripts to Docker. I found it pretty interesting to read my past self playing with AJAX and jQuery.

Lazy Loading Ajax in ASP.NET MVC
July 22, 2010

I recently changed jobs and now work for an e-commerce company called vente-exclusive.com. 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: http://remysharp.com/2009/01/26/element-in-view-event-plugin

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”).

$(document).ready(function () {
  $('#frequently-ordered')
  .one('inview', function (event, visible) {
      if (visible) {
          loadFrequentlyOrderedProducts(1);
      }
  });
});

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


function loadFrequentlyOrderedProducts(page) {
  $('#frequently-ordered').show();
  var url = '/Product/LoadFrequentlyOrderedProducts';

  $.get(url, { productId: 324, saleId: 234 },
    function (data) { 
      $('#frequently-ordered').html(data); 
    }
  );
};

The Action would be fairly straightforward:


public ActionResult LoadFrequentlyOrderedProducts(int? productId, int?saleId)
{
    FrequentlyOrderedProductsModel model = 
        new FrequentlyOrderedProductsModel();

    //code omitted for illustration purposes
    return PartialView("FrequentlyOrderedProducts", model);
}

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

ASP.NET MVC, Injecting & Mocking an IRepository
March 3, 2010

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:

Get the bits

Here’s where to get these dependencies:
Moq
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:

Classdiagram

Our Repository class looks like this:

public class Repository
{
    public IEnumerable<Athlete> Athletes
    {
        get
        {
            return FakeDb.Athletes;
        }
    }

    public Athlete GetAthleteByName(string name)
    {
        var ath = from a in FakeDb.Athletes
                  where a.LastName == name
                  select a;
        return ath.Single();
    }

    public IEnumerable<Athlete> GetAthletesByDiscipline(string discipline)
    {
        var ath = from a in FakeDb.Athletes
                  where a.Discipline.Name == discipline
                  select a;
        return ath;
    }

    public IEnumerable<Athlete> GetAthletesByCountry(string country)
    {
        var ath = from a in FakeDb.Athletes
                  where a.Country.Name == country
                  orderby a.Discipline.Name
                  select a;
        return ath;
    }

}


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.


public interface IRepository
{
    IEnumerable<Athlete> Athletes { get; }
    Athlete GetAthleteByName(string name);
    IEnumerable<Athlete> GetAthletesByCountry(string country);
    IEnumerable<Athlete> GetAthletesByDiscipline(string discipline);
}

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:


public class OlympicsController : Controller
{
    [Inject]
    public IRepository Repository;
}

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:



namespace WinterOlympics
{
  public class WebModule : NinjectModule
  {
      public override void Load()
      {


          //Repository injection
          Bind<iRepository>()
              .To<repository>();

      }
  }
}

-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.

namespace WinterOlympics
{

    public class MvcApplication : NinjectHttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
              "Default",
              "{controller}/{action}/{id}",
              new { controller = "Home", action = "Index", id = "" }
            );

        }

        protected override void OnApplicationStarted()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
            RegisterAllControllersIn(Assembly.GetExecutingAssembly());
        }

        protected override IKernel CreateKernel()
        {
            return new StandardKernel(new WebModule());
        }
    }
}

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.

public class AthletesControllerContext
{
    protected readonly MockingKernel kernel;
    protected readonly AthletesController controller;
    protected readonly Mock<irepository> repositoryMock;

    public AthletesControllerContext()
    {
        kernel = new MockingKernel();
        controller = new AthletesController();
        //inject a mock of IRepository in the controller 
        kernel.Inject(controller);
        repositoryMock = Mock.Get(controller.Repository);

        //setup mocks
        Athlete mockAthlete = new Athlete()
        {
            BirthDate = new DateTime(1980, 5, 26),
            Discipline = new Discipline()
            {
                Name = "curling",
                IsPlayedInTeams = true
            },
            Country = new Country() { Name = "Luxemburg" },
            FirstName = "tee",
            LastName = "bot"
        };
        repositoryMock.Setup(m => m.Athletes).Returns(new[] { mockAthlete });
        repositoryMock.Setup(m => m.GetAthletesByCountry("Luxemburg")).Returns(new[] { mockAthlete });
        repositoryMock.Setup(m => m.GetAthletesByDiscipline("curling")).Returns(new[] { mockAthlete });
        repositoryMock.Setup(m => m.GetAthleteByName("teebot")).Returns(mockAthlete);
    }
}

[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.


[TestClass]
public class AthletesControllerTest : AthletesControllerContext
{
    [TestMethod]
    public void Index_Returns_NotNull_ViewResult_With_Data()
    {
        //Act
        ViewResult res = controller.Index() as ViewResult;

        //Assert
        Assert.IsNotNull(res.ViewData);
    }

    [TestMethod]
    public void Detail_Returns_ViewResult_With_Data()
    {
        //Act
        ViewResult res = controller.Detail("teebot") as ViewResult;

        //Assert
        Assert.IsNotNull(res.ViewData);
        Assert.IsInstanceOfType(res.ViewData.Model, typeof(Athlete));
    }

    [TestMethod]
    public void Detail_Returns_NotFound_View_For_NonExisting()
    {
        //Act
        ViewResult res = controller.Detail("nonexisting") as ViewResult;

        //Assert
        Assert.AreEqual("NotFound", res.ViewName);
    }
}

Download Sample Code

[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.

TeeBots-NET-Blog-ASPNET-MVC-Mocking-the-Repository-with-NinjectMoq)
CodeProject

Setting AD Properties using the new AccountManagement API
November 16, 2009

So I’m currently programming a lightweight utility to manage LDAP objects and I came to use the new AccountManagement API introduced in .NET 3.5 because it’s way easier and more object-oriented than DirectoryServices.

This new namespace, as I see it, is just provided as a friendlier way to query an LDAP server and is actually built on top of the plain DirectoryServices bits. And it shows… For example you have to dispose all objects performing a search (FindIdentity) or as Gary Caldwell puts it:

This call has an unmanaged memory leak because the underlying implemenation uses DirectorySearcher and SearchResultsCollection but does not call dispose on the SearchResultsCollection as the document describes.

Also, because AccountManagement is not as close to the metal as DirectoryServices you can only control whatever Microsoft chose to expose in the API.

However a fantastic feature of AccountManagement is the ability to fall back on a DirectoryServices object whenever you need to because the underlying object of any Principal is exposed through GetUnderlyingObject().

DirectoryEntry entry = (DirectoryEntry)principal.GetUnderlyingObject();

With that much power in our hands we can now use this to set some properties unexposed by AccountManagement. Here’s a generic method I made to set LDAP properties on any Principal (users, groups, computers):

public void SetCustomProperty<T>(string key, string value, T principal)
 where T : Principal {
 if (principal.GetUnderlyingObjectType() == typeof(DirectoryEntry)) {
   DirectoryEntry entry = (DirectoryEntry)principal.GetUnderlyingObject();
   entry.Properties[key].Value = value;

   try
   {
      entry.CommitChanges();
   }
   catch (Exception e)
   {

      string message = 
      String.Format(@"Could not set custom property {0} to value {1} for object {2}", 
      key, value, principal.Name);

      throw new Exception(message, e);
   }
 }
}

Use it like this:

SetCustomProperty<userprincipal>("streetAddress", "21 jumpstreet", userPrincipal);

Being user-friendly while keeping control? I’m starting to like that little guy.

UPDATE: As an anonymous commenter pointed out, there’s a way to actually map an AD attribute to a property of a class inheriting UserPrincipal. The technique consists of decorating the property with the attribute DirectoryProperty and the field name as parameter (as seen here).

NOTE: code indentation is messy in the examples. I need to fix something in my snippet tool.

CodeProject

TechEd 09 Day5. Lucky Friday Thirteenth
November 12, 2009

Today is the last day of TechEd.

A SharePoint Pattern Language

Non-Microsoft speaker Jim Wilt first made the assumption that we’re feeling like if our brains were about to leak through our ears. Good guess Jim!
He is presenting us an offshoot of the work he’s doing for Microsoft. He won’t be able to tell us everything about it as it is still pure research at this time.

There is a necessity to document SharePoint solutions that are repeatable, extensible, and reliable. But should we have a SharePoint specific pattern-language?

Jim thinks so because there are SharePoint specific concepts to take into account:

First the application level: component, solution site or template levels.
And secondly the tools to use: Out-of-Box, SharePoint Designer or Visual Studio.

The demo pattern was Collecting anonymous user data securely. In this example, the pattern sits at the solution site level using out-of-box and SharePoint Designer.

Jim thanked us for attending this session at 9am on the last day.
A repository of SharePoint Patterns would be a great addition (at another level) to the existing SharePoint Guidance.

Rest of the Day

After that session, I spent some time at the Visual Studio booth. I spoke a little with Marian Luparu, Visual C++ Program Manager who reminded me that Microsoft is basically a C++ factory.

The last session I’ll be attending is about Pex and Code Contracts, which to me are the most interesting additions to .NET 4 and VS2010. I wonder how the automated test generation tool works.

TechEd 09 Day4. Dynamic Morning
November 11, 2009

Developing a Language with the Dynamic Language Runtime

Harry Pierson aknowledges that developing your own language is not a very common scenario. This session was a deep dive into the bit crunching stuff and the implementation behind the new DLR library which extends the CLR’s cross-language support to dynamic languages. With IronPython and IronRuby gaining in popularity it was interesting to see how Microsoft actually architectured those changes in new libraries, improved the performance of dynamic languages while no major changes had to be made in the CLR.

For those who want to dive even deeper into the DLR, the code is open sourced on codeplex.

Dynamic in Microsoft Visual C# 4.0: The Why’s and How’s

The HOW was covered in details by Harry already. Alex Turner first exposed the implementation choices behind the adventures of C# in the dynamic world. In the end the dynamic keyword is used as a type (but it’s more than a type).

So WHY use dynamic at all? In which cases de we actually need some code that will be interpreted at runtime instead of compiling it in the IL?

  1. Use code from dynamic languages (or being a better citizen in the .NET world)

  2. Talk to dynamic object models such as the HTML DOM or Silverlight

  3. Code more naturally with Interop COM interfaces (think Office Dev)

Image 3

Architecture Discovery and Validation with Visual Studio 2010

Peter Provost demonstrated the new tools for Architects available in VS2010 Ultimate. VS 2010 feels more and more like a complete standalone software factory since the inclusion of the UML modeling tool.

To try to understand existing code, the code Analysis tools can provide a valuable help. For the demo, Peter imported a big solution containing 30 projects and went on exploring it using the Architecture Explorer with class diagrams and the new filters. What impressed me the most was the Sequence Diagram Generation.

Image thumb%5b19%5d

Book Shop

At the end of the day I stopped by the TechEd book shop. I often ask to architects if they know about some good books with a bit of theory illustrated by stories from the trenches. I think I finally found what I’m looking for: Microsoft .NET Architecting Applications for the Enterprise.

9780735626096f

As this guy puts it in a review: “A .NET developer looking to move into architecture should make this book their first stop on a long journey”.

TechEd 09 Day3. Today is Architecture Day!
November 10, 2009

Most sessions Kristof and I will be attending today are part of the Architecture Track.

Application Models for Utility Computing

Ulrich Homann spoke about how SharePoint’s Scalability was made with Scale Units in mind for each tier (Database Tier, Middle Tier, Application Tier, Load-Balancing Tier, Storage Tier).

He then went on discussing how we can layer an application to enable virtualization in the enterprise world. For example, the data tier of an application could be scaled down to 2 or 3 servers at night while the others are going back to the image library. This frees computing resources that can either sleep to save energy or be used for crawling. [See Application Patterns for Green IT]

As Ulrich puts it Mainframe developers already did this 20 years ago. I would add that there is fundamental difference: hardware is a lot cheaper now than it was before, cheaper than hiring programmers.

The Role of the Software Architect: Caring and Communicating

Very interesting talk or should I say open discussion about what exactly is an Architect. Architects should be held more accountable according to Magnus MÃ¥rtensson, it’s a matter of pride and professionalism. Magnus quoted yoda to make a point about why Architects should not inspire fear to developers because “Fear is the path to the dark side. Fear leads to anger. Anger leads to hate. Hate leads to suffering”.

Yoda2

Unit Testing Good Practices

Roy Osherove is Chief Architect at TypeMock. His presentation was focused on 3 requirements to write good tests: Tests should be trustworthy, maintainable and readable.

That was definitely the best presentation so far in my opinion. It was technical and straight to the point.

After developing each of these points, Roy challenged some Microsoft-issued code by looking at their tests (the NerdDinner MVC sample, the Unity project). It was really interesting to see why most of them don’t achieve a good readability or are sometimes not relevant enough, especially since I have seen those tests before while learning MVC and found them quite good.

On the side he often plugged his book “The Art of Unit Testing” and made a reference to Code Katas. Roy also does Test Code Reviews on his blog.

Katas illustration

I’ll keep a note to talk more about Code Katas on this blog for learning purposes, but for a good explanation check this Jeff Atwood’s post who quotes Steve Yegge’s blog.

Also this appears to be the founding post of code katas which I will quote:

A kata is an exercise in karate where you repeat a form many, many times, making little improvements in each. The intent behind code kata is similar.

There is an obvious trend in the development world these days and it’s using Ninjas as metaphors for developers: Code Katas, Ninject the dependency injection library and the cover of Roy’s book.

That’s it for today! Stay tuned for Day 4 and Day 5!

Kristofundteebot

TechEd 09 Day2. Deep Dive Into the Serious Stuff
November 9, 2009

UPDATE: MVC Session and the Welcome drink

Day 2 has started. The subway was crowded with developers and IT admins. I’ve never seen that much human computing power at once :)

Be sure to check my previous post as I’m updating it with pictures and videos of the Berlin Wall Fall festivities.

Kristofteebotsmall

Parallel Computing for Managed Developers

The first session of the morning was rather interesting. According to Steve Teixeira (actually he quotes Intel), 80 cores CPU is something reasonable to foresee sometime in the next 5 years.

Nowaday, multithreading is hard to develop and is very error prone. Starting from .NET 4.0, the framework will include new libraries including PLINQ and the Task Parallel Library.

Here’s an interview of Steve explaining why parallel computing is a major shift in the programming world:

VS Team System: A Lap Around the Project Management and Architecture Capabilities

Here’s a few features that I really enjoyed:

Reporting from Excel is really easier now. As Brian already mentionned yesterday, they scaled TFS down with Basic Wizards and Simpler Reports but they also scaled it up with many more features like Scrum integration or Architecture validation.

More importantly everything is now tied together and queriable on a TFS project so as an example we can now directly see all requirements who don’t have Test Cases yet.

On the architect side, we were shown that validation is now really easy to set up. Developers are unable to check in some code that violates the rules defined by the architect.

If you want to know more about the Project Management in TFS 2010, see Brian’s blog.

Code Walkthrough on Azure

That session has a rather self-explanatory title. It was indeed very technical. Our belgian compatriot demoed some code using a Worker Role and a Web Role on Azure. All this looks quite impressive. For some reason he used a local machine instead of the real Azure Services, leaving us a little disappointed.

Speaking of Azure, I found this nice pricing calculator. Is it me or is Azure just really expensive unless you need dozens of servers?

What’s New in ASP.NET Model-View-Controller

Stephen Walther first polled the crowded conference room asking who is currently using ASP.NET MVC. To my surprise most of us were.

So he focused on the new HTML.RenderAction() helper and Areas. Stephen also demoed how validation based on data annotations can be easily bubbled to the client through the Microsoft MVC Ajax scripts.

Beer as in Free Beer

The welcome drink was a huge success, most people attended it and even stayed later that night. I have no idea why those incentives always work.

That’s it for Day 2! (not that I don’t remember what happened after the Welcome drink it’s jsut not that relevant for this post).

TechEd 09 Day1. Berlin, Here We Come!
November 9, 2009

So after a 10 hours drive from Brussels, Kristof and I arrived safe and well at the Hotel yesterday. This morning we took the S-bahn metro to the ICC conference center.

I guess it’s not easy to fit 7000 attendees arriving all at once through the same doors. We waited about an hour to get our badge and a techEd bag full of goodies and software bits.

Helping developers and testers to get along better

I’m currently attending the DEV206 session titled “Team System 2010: A lap around the developer and tester experience”.

Pic131

To summarize this session shortly with a developer bias: What Microsoft mainly did with this release of TFS is to ease the merge process, help developers and testers get along better (sic!) and they made lab testing way easier.

No More No Repro

The most remarkable feature is definitely IntelliTrace which enables developers to track the bugs filled by the testers directly into the code. On top of IntelliTrace, developers from the My Bug pane of Visual Studio can now see a video of what the tester did to reach a bug.

Brian Harry didn’t detail everything as there was so much to cover but apparently there is also a way for the developer to record the bug on his VM and for the developer to replay the bug from the initial machine state.

From my point of view it looks very promising and I already see a few cases where these tools could help in my current project.

Stay tuned for more updates from TechEd 09 in Berlin!

We Don't Usually Know What Kind of Parents Had Our Grandparents
August 26, 2009

(or How to Retrieve a Type of Parent Control Using an Extension Method)

Here’s a situation where I had to retrieve the next Parent Control of a certain type. In this particular case, my label is included in an UpdatePanel to update only when my Label is assigned a new value.

I could have used the Parent attributes of my controls and go up a few levels until I have the right one:

UpdatePanel updatePanel = label.Parent.Parent;
updatePanel.Update();
The ASP:  
<asp:updatepanel id="UpdatePanelMessage" runat="server" updatemode="Conditional">
  <contenttemplate>

  </contenttemplate>
</asp:updatepanel>

Do you see what’s wrong?

And what if the page is modified and the control is included in a new div or in a new panel? You see it coming, the control retrieved won’t be an UpdatePanel because we don’t usually know what kind of Parents had our Grandparents…
So as soon as the asp page structure changes, chances are that casting errors start to appear.

We need a way to look up that control’s ancestry and return the first parent of a certain type. We can achieve that by using the following extension method:

public static Control GetParentOfType(this Control childControl, Type parentType) { 
  Control parent = childControl.Parent; 
  while(parent.GetType() != parentType) { 
    parent = parent.Parent; 
  } 
  if (parent.GetType() == parentType) 
    return parent;  

  throw new Exception("No control of expected type was found"); 
}

Now wherever we need to retrieve the first occurence of any control’s parent of a certain type we just call the method GetParentOfType this way:

UpdatePanel updatePanel = (UpdatePanel)label.GetParentOfType (typeof(UpdatePanel));
updatePanel.Update();  

CodeProject