Allow Me To Share My Toolset Choices for Developing On .NET

There was a question in a tech facebook group I co-manage about what tools you’d use if starting a new project today.


I don’t know for sure. It depends -of course- is the expected answer. For example, there’s some idea I had I mind I considered using MongoDB or CouchDB for, while still using .NET, and then I wasn’t sure if I go extra mile in DB I’d go for Node or Rails as well or would prefer .NET for my personal productivity. I also often use Node/Bower when checking libraries with many dependencies.

So, for this question, I thought what tools I might use in a company project. Thinking back, I found that most tools I use now are good enough for what they do. So, I thought I’d list these.

These tools are my personal experience though. While some of them are widely adopted in Readify, some others may have been specific to some clients or Readify teams I worked with. Every team is free to choose the tools that work best for them and make it easier to deliver high quality deliverables in sensible time, so, even if you are at Readify, your mileage may vary…

The Tools

Server Side Web


  • SQL Server (or SQL Azure, although I don’t like SQL Azure, because it’s not compatible with some scripts generated from SSMS, which I sometimes use to generate migration scripts)

  • DbUp for DB migrations (there are some other nice options now)

  • Special SQL views + Web API OData + MS Excel for reporting

Client Side Web

  • Angular.JS on the client when I have the choice, Knockout.JS and jQuery UI (being deprecated now) at some big client I keep going back to every few gigs

  • LESS for CSS, or SASS (SCSS) when the CSS is handled by one of our favourite design agencies

  • Chrome devtools for web debugging (obviously), unless it’s IE issue of course.


  • Phonegap (most just the open source part of it, Cordova) and Ratchet CSS framework (considering alternatives, like TopCoat) for mobile development, with Angular.JS

  • Considering Xamarin as their work seems to be VERY cool, and I recently get access to their stuff via my company (OT: Also considering Neo4j DB for similar reasons).

IDEs and Text Editors



Internal Communication

  • Several kinds of wikis used by different clients, often with OneNote

  • HipChat for team communication, sometimes Skype and/or Lync as well

  • AnswerHub (Stackoverflow clone) for internal questions forum where I can safely quote client sensitive information in my question

  • Yammer for internal company social network

How about you?

What tools do you you use when developing?

Let me know in the comments, via email, or on twitter!

Enforcing ASP.NET MVC Conventions With Unit Tests, Or Solving The AJAX HTML Redirect To Login Page Problem

This blog post is about an ASP.NET MVC workaround we implemented in a previous project. We solved the problem by enforcing using a class that extends one of ASP.NET MVC classes, which in itself created another problem, as new developers joining the project may always use the old class. The solution to this problem was not something that I invented, but it’s also not a very common practice.

So, if you are interested, here’s the entire story…

Detecting Session Timeout In AJAX Requests

We wanted to solve a problem where in an AJAX heavy ASP.NET MVC application, if the user triggers an AJAX action after staying inactive for longer than our application timeout, the call to the controller action, which normally gets a JSON response, would instead get the HTML of the login page.

This is a known issue in ASP.NET (particularly System.Web). A feature that’s on by default is returning a redirect to the login page instead of a HTTP Unauthorized Status code (401). After the redirect the response returned is a successful (HTTP Status Code 200) load of the login page. That means even our Angular.JS error interceptors (or jQuery handlers, etc.) don’t notice there was an error.

A fix for this was turning this feature off. We inherited the Authorize attribute as below:

SuppressFormsAuthenticationRedirect is the property that disables the login redirect. Microsoft set it to false by default so that it’s backwards compatible.

ASP.NET MVC doesn’t recognize AJAX requests through Request.IsAjaxRequest() via Accept header or so. It does via checking X-Requested-With header. Most AJAX-capable frameworks like jQuery and others offer a way to intercept all requests and add extra headers, for example, in that app, we configure Angular.JS to include the header with some code similar to this:

Enforcing The Convention

The obvious problem with the previous solution is that we are ignoring The Power Of Defaults. Any other developer who may join the project needs to know that using Authorize is a no-no, and even for old devs (myself included),
it’s very easy to just forget and use Authorize not AuthorizeRedirect just out of habit.

Solving this problem was quite easy though, we added the following test to our Unit Tests project:

I hope the code is self explanatory. We check the web project assembly for all ASP.NET MVC Controllers, then we check the Controllers and all their Action methods for existence of the AuthorizeAttribute. We filter those that use the correct attribute (AuthorizeRedirectAttribute), and we Assert that there are no the no Controllers or action remaining, otherwise, we tell the developer which Controller or Action needs to be fixed, and how to fix it as well.

Room For Improvement

The drawback of this is that our Unit Test project had to reference the ASP.NET MVC assemblies and gets more stuff than most tests should need. We can overcome this by moving our “convention” tests into another project completely, but for this project the conventions were very few and it seemed fine.

Of course the same method can be applied to any other convention you enforce in your project. One obvious example is ensuring all Controllers inherit from a custom base Controller class instead of the ASP.NET MVC class directly. I know people who already do this, as I mentioned in the opening the technique is not new by any means, but it’s worth even more popularity.

Speaking of improvement, the code for this test class was optimized a bit while writing this blog post, there is always room for improvement :)


In case you were reading the code carefully, the IsNullOrEmpty() method I used in assertions is a custom extension method we had in the project, a very simple one as you may expect:

And That’s it!

I hope you found the technique useful if you haven’t used it before, or found the post a good place to reference it to those who didn’t.

Using Visual Studio Developer Command Prompt With PowerShell

Running Developer Command Prompt for Visual Studio

The Visual Studio developer command VsDevCmd.bat only works with the cmd.exe command line shell/processor, which is still the native command prompt in Windows. Try writing some command in Start->Run or Explorer’s address bar, and you’ll find that you need to use the cmd/batch command syntax (for example, using %SOME_NAME% syntax for variables).

What if you want to us VsDevCmd.bat? You want the stuff it adds temporarily to the PATH and all the other goodies it brings, but prefer to work in Powershell?

Using VsDevCmd With PowerShell

You can try to run VsDevCmd.bat from PowerShell, but this will execute another command prompt shell on top of it.

However, you can also easily do the opposite. Run the VsDevCmd.bat, and from the command prompt, just type PowerShell and press ENTER. The new Powershell session will inherit all the fluff that VsDevCmd.bat added to the command prompt session.

A Quick Shortcut

You can always have a simple shortcut to load VsDevCmd.bat with Powershell instead of writing everytime.

Simply create a new text file, and enter the following in it:

Save the file and change its extension to .bat. When you run it, it will run the command prompt and keep it open, run VsDevCmd.bat, and then powershell.

You can test it by running, ensuring the prompt shows the PS > prompt for PowerShell, then run msbuild to ensure it was added to the PATH by DevCmd.bat.

Using By Default, ConEmu

On my personal machine, I use ConEmu as my all-time console environment. If you don’t know about it, Scott Hanselman described it in depth.

Among many other things, ConEmu allows you to create tasks that can be executed by default when you open a new console tab. This allows you to have for example some preset (task) for sat Bash/cygwin, another for cmd.exe, another for PowerShell, etc. Maybe even another task that loads some extra variables or whatever that you don’t want always attached, but still want them handy when you use the console. It also allows you to optionally choose one task to be the default when you open ConEmu.

So, for me, the task I set to be the default in ConEmu is the following:

the first * > bits are ConEmu specific, telling it to run task as admin and make it active tab (if you can set multiple tabs in the same task). And the -new_console: switch allows passing other parameters to ConEmu when starting, like d:D:\_data, which sets the start-up directory to a prefered directory I have. The rest in the middle is the simple command which calls VsDevCmd.bat and then starts PowerShell.


How to set the initial selected value of a select element using Angular.JS ng-options & track by

I have been doing Angular.JS in production projects for months, that it did surprise me recently how I haven’t used drop-downs in it. Well, I mean how I haven’t used them enough to get into several problems I had in my current project, and other friends at the same office had in their project as well.

To save you the pain I went through, I’ll list some problems and solutions here, and then give you a video that shows going through all of them ans the thought process that led to the solutions.

Initial selection

Assuming someObject in the model has the same properties and values as someObject in the objectList, it will still not be selected.

It’ll only be selected if someObject was actually one of the objects in objectList, like objectList[0] or whatever. Otherwise, Angular.JS will insert an empty option tag with no value or text and select that.

Root Cause

Angular.JS uses native JavaScript comparison for comparing the objects. In JavaScript, unrelated to Angular.JS or anything, comparing objects (object literals) is “by reference”, so it doesn’t factor the similarity of the objects. Only checks if the two references compared point to the same object in memory or not.


An un-documented (AFAIK) feature in ng-options is that you can use some bits from the ng-repeat directive with it, like track by. This allows us to choose some property as the comparison key.

If the key property is a simple type, like Number or string, JavaScript will consider it equal to any other object that has the same value, so we don’t have to use the same objects.

Invalid Value Sent On Server-Side Submit

When Angular.JS writes the <option> tags from an ng-options directive pointing to an array, the value of the option is always the index of the element it maps to in the array. This is not important if you process the selection on client side because you only deal with the result of ng-model anyway, you can use this later to create an AJAX request or whatever.

However, if you intend to submit the form using a normal server submission, and only use Angular.JS for say validation or managing complex form interaction (client-side tables containing sub-items with add/remove/sort for example), this may be a road blocker to using Angular.

Root Cause

By default Angular.JS uses the index of the array to track which object maps to which <option> element.


Similar to the previous problem, use the track by syntax. Angular.JS will use the track by property value as the <option>‘s value. Most of the time your tracked property is the key property you want to send to the server anyway, so, this should be good enough.

Simple Properties Scenario When Combined With Server-Side Submit

Let’s say you want something as simple as this:

This syntax will work very well, if you only use this value from JavaScript, you are all set. But if you plan to send it directly to the server (a normal non-AJAX form submit), you’ll want to consider using the track by syntax, like track by

However, if you do this, you’ll notice that the select is no longer usable. No initial selection, and changing selection although updates the model, it does not show the new selected value.

Root Cause

The track by syntax expects an object, with the property you use to track. It does not honor the key part used in the key as text syntax (which in our example is as g.text), so, it wants the ng-model to point to an object with the tracked property, it cannot be the key itself directly.


I didn’t call this a solution, because it’s pretty much a hack.

We created a new property (which I liked to prefix with _ to show it doesn’t normally belong to the model object), initialized it to a new object that contains only our key property id set to the original simple value genderId, and then used that as the model (as in ng-model).

We created and assigned the property in ng-init, then synchronized the changes to the simple property via ng-change. This allows the code everywhere else in the application (like the controller, or other parts of the markup) to only interact with the property we want (genderId in this example), without knowing about our hack. This makes things a bit cleaner, although it still remains a hack rather than a solution.

You can view an example of using this hack here.

Adding extra selection items to the dropdown

One thing you notice if you are affected by the “initial selection” problem, is that the empty <option> tag that Angular.JS adds when it can’t match the ng-model to the array from ng-options disappears when the use changes their selection. We have gone through how to avoid showing the empty option by mistake already.

But if you do want to have that option, it’s easy, just, um, add it!


If you are using Angular 1.4+, check the much smaller 2nd part of this article, about how to use track by correctly.
Using track by correctly with Angular 1.4 select ng-options – Why can’t I select this option?

The Video

If you want to dig these problems really deep and see what they look like in action, and what was the thought process for solving them like and in some cases other possible solutions, I have put all this in a (rather long) video here:

Serializing A PagedList Using JSON.NET In ASP.NET MVC – Gotcha And Workaround

Recently I discovered that there’s no one standard way for AJAX-driven server-side paging in ASP.NET MVC (in Web API, you can expose an IQueryable). For the case in hand, I decided to use PagedList for the server bit of the game.


The PagedList interface looks a bit like this (for demonstration only, real code is a bit different, check its source code for the real stuff):

It provides nice properties for paging, and exposes itself as enumerable and has an indexer. Apart from this snippet, the library also provides an extension method ToPagedList() to apply to any enumerable and allow it to populate the properties from it (by enumerating on it, and by calling the Count() method).

We were also using JSON.NET for JavaScript serialization, which is pretty much defacto standard nowadays.

The JSON.NET Serialization Problem

JSON.NET has a nice implementation, if you serialize a class that implements IEnumerable<T>, and you don’t have a special treatment rule for it (via what JSON.NET calls “Converter” classes), when you serialize an instance of the class to JavaScript, it will be serialized as a JavaScript array, where the enumerated objects are the contents of this array. Makes lots of sense right?

Well, yes, except when you have a custom collection like PagedList, and you want to treat it as an object that has several properties, not as an array. JSON.NET does provide a solution for this actually, all you need to do is apply the [JsonObject] attribute to your class.

Unless you don’t own the source code of this class.

In this case, you need to inherit from it. By doing this, I lose the nice ToPagedList() extention method (because it creates an object of the PagedList class directly), but luckily it does nothing but calling new PagedList() with the parameters we give it, so, we don’t lose much.

Here’s how my implementation looks like:

Apart from having to copy the constructors to pass parameters to the base ones, have you noticed the extra Items property in there?

That’s because the Subset member it includes is actually a field, not a property, and JSON.NET won’t serialize that by default, I could override it somewhere else, but since I’m fiddling with this here, it made sense to just stick a property to the class.

Bonus: A Bit More On Implementation

In my actual code, I have added the Dynamic Linq NuGet package, and assumed a single property for sorting (which was fair for the situations where I intend to use this), so, I complemented the code above with another class that looks like this:

This allows the controller to instantiate an instance of the SerializablePagedList class, pass it all the way to whatever repository method I have.

The repository method will take it as a parameter, work out what IQueryable it needs, and instead of passing it to UI, it calls CreatePagedListFromQueryable(), which returns an innocent-looking PagedList object (because SerializablePagedList inherits PagedList) that the repository can pass back to the controller, which can serialize it to JavaScript without a problem, then the rest is all JavaScript code to work out how create the paging parameters, and how to use the returned paging hints.

Even more, now that I think about it, maybe I should change the return type to SerializablePagedList, to make the Items property visible to the developer (because they’d think it’s magic, and in coding, magic is BAD). I’ll leave this as an exercise for you :)

Final Words / Disclaimer

The motivation behind this post is that I found the problem of serializing PagedList using JSON.NET a challenge and I wanted to help others work it out faster than I did. Is this how I’d recommend doing paging? Well, I don’t know, but if it’s what you choose, I hope that I have saved you some time.

And more importantly, is it good enough to be the defacto standard I mentioned I was after in the beginning of the post? Not really. I think it’s not bad, but definitely not the best. I’d love to see less clever (read: hacky), and more simpler solutions.

My Quest To Find The Best NodeJS Http Client With HTTPS and Basic Auth

This may be a completely useless post, but it took me a bit to figure out some of the pieces until I got here, so, I thought maybe it’s worth sharing!

What’s this & how did I come by it?

Instapaper is a nice service that provides you with “read it later” bookmarklet. You use this bookmarklet to add any web page to their log and you can read that page later via their site, a mobile application (from them or 3rd party), or via Kindle (or other book readers)!

Apart from their bookmarklet, they provide a simple API to add URLs programmatically. This is useful if you for example want to extract URLs from other services, say twitter favourites. They also provide a Full API (OAuth API) for doing everything their site and apps do, except some things in this so called Full API are (at least to be) only for paid subscribers.


Instapaper’s simple API is quite interesting though, according to the docs, you can use HTTP and provide only username (email) -not even password- to add a URL, and you can use POST or GET. That’s scary for anyone who thinks about security, but -maybe- OK for what the API does. They also provide the API in proper HTTPS with basic HTTP authentication (and if you want more, you can always use the Full API’s OAuth).

I wanted to use their API in HTTPS using POST and Basic Authentication. In my tests I was happy to try HTTP and/or GET and/or sending username in clear-text. I also thought I’d write this in Node because I thought it should be easy. Node people often serve REST/HTTP APIs, so, they must be good at consuming them too (even though in reality most consumers are client JS not node), right? Well, maybe yes.

The Code

I can explain the challenges, how I overcame them, and then show the final code, but I have spoken too much already, let’s begin with the code.

var basicAuthenticationParams = {
username: ‘MY_EMAIL’,
password: ‘MY_PASSWORD’

var requestParams = {
url: ‘’
};“”, {
form: requestParams,
auth: basicAuthenticationParams
function (error, response, body) {
// This is only returned for network errors, not server errors
if (!!error) {
console.log(“Network Error:”);
throw error; // it’s actual JS Error object not string

var statusCode = !!response ?
parseInt(response.statusCode, 10) || null
: null;
// I could have checked for 200,
// but technically 200-299 are success codes,
// and more importantly, Instapaper sends 201 for success
if (!!statusCode && statusCode >= 200 && statusCode < 300) {
console.log(); // Extra line separator

console.log(“HTTP Status:”);
console.log(); // Extra line separator

// In instapaper’s case, by default,
// they just send status code in body too


See? It was all very straight forward. Well, it wasn’t for me. I tried several NPM packages to get this effect, and none was going well. The “request” package was the one that did the trick. this is generally accepted in Node, the built-in API is very low level and there is some NPM package that gives you the nicer one.

For all the other packages I tried, they didn’t have any dependencies on other packages. This “request” package gave me the usual shock seeing so many NPM packages downloaded and installed, but this is the philosophy of NPM, build small reusable pieces built on top of other pieces.

Getting the request headers right (Oh my!)

While the packages were not working, interchanging HTTP status codes between 403 (invalid credentials) and 400 (missing parameters), it was very hard to tell what I needed. Even associating to proxy to get the output to Fiddler didn’t go well with for example the “easyHttp” package (there is a similarly-named NuGet package for .NET BTW, but it’s not related at all I think).

I went to my favourite Chrome Postman extension, which works nicely like Fiddler for the “compose request” part (actually, arguably is even way easier). The request parameters (was using username as another request parameter, not using Basic Authentication, just to test) didn’t seem to work until I changed the default “form-data” to “x-www-form-urlencoded”


Which added the following header to the request: “Content-Type: application/x-www-form-urlencoded”. This kind of makes sense. This overly permissive API feels more optimized for sending from web-pages, where forms are a front concept.

I tried to add the header when I was using other packages but that didn’t seem to tick it. I tried this one, and as you can see didn’t even need to set that. I just used the “form” property of the options though instead of “body” or “”json” properties.

This is why I’m posting this, to hopefully help someone googling get up and running quicker than me. This is not just Instapaper, this can be very helpful in so many situations.

For the rest of you (.NET / non NodeJS devs)…

If you are not a Node person but still want to have a fiddle, after you install Node (which includes NPM package manager by default), then you save the code to a JS file “some-file.js”, preferably in a new folder.

Assuming Node and NPM are in the PATH (installer default), you can open Cmd or PowerShell console in that folder and run npm install request then node some-file.js (no quotes in both), and see the results in front of you.

Twitter OAuth, Persistent OAuth, TweetSharp: Presentation & Code Nuggets

This is a PowerPoint Presentation (and extraction of the contents) I made as per a couple of friends’ request (@EmadAshi and @AmrEldib) to show how OAuth works along with Twitter and how easy it is to cache OAuth credentials.

As I was doing related work for TweetToEmail. I felt a PowerPoint presentation will be even better than a blog post for this one, but here you get the two.

The Presentation

The Contents

Application Registration

  • A Twitter user creates a Twitter Application
    • If the application is web based, it needs to provide a URL. “Localhost” is not accepted as a domain for this URL
  • A Twitter Application gets two pieces of information
  • Consumer Key
  • Consumer Secret
  • A Twitter Application will use these in all coming requests.

Initializing The Process

  • User comes to the application and it decides to authenticate against Twitter
  • Application makes a request using Consumer Key and Secret to obtain “Oauth Request Token”, which consists of two parts
    • Token
    • Token Secret
  • Application makes authentication URL including the “Oauth Request Token” parameter, and optionally a “Call-back URL” (if different than default URL in first step)

User Authentication

  • The user is redirected to Twitter, the URL contains the “Oauth Request” to identify application authentication session
  • Assuming the Twitter User being logged in and authorizes the Application
    • If the application is a desktop application, Twitter gives the a user a number “Verifier” to manually write back to the application
    • If the application is a web application, the user is redirected back to the application call-back URL with a complex “Verifier” parameter in the URL

Obtaining the Access Token

  • The Application makes a request to Twitter including the “Oauth Request Token” and the “Verifier”
  • It obtains an “Access Token”, likewise it consists of two-parts:
    • Token
    • Token Secret
  • The application needs to send the Consumer Key and Secret and Access Token in every future request that needs the Twitter User privileges

Caching Credentials

  • The application needs at least one authorization process as before
  • The Access Token returned can be saved in session/DB/whatever and then re-used later
  • The application can later use the Access Token directly along with the Consumer Key / Secret to communicate with Twitter without going through any of the previous steps

Sample Code (TweetSharp v 2.0)

Request Token & Redirect


Getting Access Token


Hints for Web Applications

  • The method GetAuthenticationUrl() has an overload that accepts a call-back URL for the user to be redirected to after obtaining verifer
  • The important part in RequestToken is the Token part, not the secret.
  • All parts of AccessToken are important and required
  • When the user is redirected back from Twitter to your application, you get the following QueryString parameters sent to you
    • oauth_token: The Token part of the Request Token
    • oauth_verifier: The verifier required to obtain the Access Token later

Using Cached Access Token


Related Links

Typed Eager Loading Using Entity Framework (& What is Eager Loading vs Deferred Loading)

If you don’t know what eager loading is, Jump to “What’s eager loading?”.

Eager Loading Syntax

If you are eager loading Products for example in a typical (Categories 1<->* Products) relation, the standard syntax would like:


What is the problem with that?

The “Products” part. The word “Products” is a string. If I rename the Products table to ShopProducts or whatever or even remove it from this data diagram and have it elsewhere, or even something wrong happens and the relation is removed from DB/diagram by mistake, my code will still compile, but will fail when it runs. This is BAD BAD BAD.

How to solve this?

Since I always believe that if something exists somewhere you shouldn’t do it yourself unless its totally broken (and I mean REALLY REALLY BROKEN), I started searching inside the Entity Framework itself for something to get the entity name from.

At first it seemed super easy. Every entity class has a static property “EntityKeyPropertyName”, so, I thought I can write something like:

DbDataContext.Categories.Include(Product.EntityKeyPropertyName); // But this didn’t work

Where Product is the entity class generated for table “Products”. Note that singularizing the name (Products becomes Product) does not happen automatically like in Linq-To Sql, you’ll have to change it manually, which is not required for the code here of course.

As you an see n the comment, this didn’t work. The value of property was always “-EntityKey-”, the default value of the abstract class “StructuralObject” which all entity classes inherit.

I kept searching all over until I found that the only place I can get the name from was an Attribute generated on the class somewhat like this:

[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName=”DatabaseNameFlowModel”, Name=”Products”)]

My requirement was simple. if the diagram has something wrong that the relation between ParentTable and ChildTable tables but not about the entity classes themselves, My code should not still compile and fail on run. I need to use some code that depends on the relation so that if something is wrong with the relation this code fails early and I know about it the problem the next time I build the VS project.

The Final Solution

I tried badly to get the entity name from the API, after frustration, I ended up writing this code:

This enables you to write:

DbDataContext.Categories.Include( (cat)=> cat.Prodycts);


DbDataContext.Prodycts.Include( (prod)=> prod.Category);

According to your need.

For things like: Order.Customer.Address (multiple levels), you’ll have to write code like:

DbDataContext.Orders.Include( order => order.Customer ).Include( customer => Customer.Address );

What’s Eager Loading? (in case you don’t know)

Let’s say you have tables Products, and Categories with relation 1<->* between them (Any category has many products; one product has one category). Let’s say you want to display a page of all products grouped by categories. Something like the following list but with much more information of course:

    • Category 1
      • Product A
      • Product B
      • Product C
    • Category 2
      • Product X
      • Product Y
      • Product Z

If you are using some ORM / Code generator that creates for you classes like “Product”, “Category” and gives you properties like “myCategory.Products” , “myProduct.Category”, how would you create such page?

Normally you’ll put a repeater or such for products inside a repeater for categories.


The products repeater will have its data source set to the current category item of the Categories repeater, something like “( (CategoryEntity)Container.DataItem ).Products”. Fine with that? Familiar?

OK. Now, if the code generator that generated the “Products” property has something like that:

public List<PRoduct> _Products;

public List<PRoduct> Products




if (_Products == null)


_Products = (from products in DB.Products

where products.CategoryID == this.ID

select products)



return _Products;



* Nevermind the LINQ syntax. It’s just like writing “SELECT * FROM [Products] WHERE …” with all the dataset/datareader stuff.

Lazy Loading (AKA. Deferred Loading)

If the generated code (or your code) looks like this, this means that that for every category in the database, you’ll have a separate DB call to get the products of this category.

It also means that the products of each category will not be loaded until someone writes code that calls the getter of the Products property. That’s why this style of coding (not loading the related objects until they’re asked to be loaded) is called Lazy Loading.

This is good for a single category where you may be seeking just the basic information of the category and will not try to load products, since then they will not be requested when you don’t ask for it.

However, this is very bad for our example page. Because it means that a new DB call for each category. Imagine that you have 20 or 50 or 100 Category there, this will give you how many DB calls? (Hint: N Categories + 1 call for the category list itself).

Eager Loading

What if the code in the getter above was in the constructor?. Imaging something like:

public Category(int categoryID)


// Code that laods category info from DB. Does not matter here.

//Could be in factory method or such. Not our topic

_CategoryID = categoryID;

// …. …. …. Continue Loading Logic

//The important part

_Products = (from products in DB.Products

where products.CategoryID == this.ID

select products)



This is good in case you know that in every situation when you use the category, the Products will be needed. This is probably not useful in a Product/category Scenario but think of a Person table and Address table where most likely whenever you load a Person you’re going to load his Addresses.

This is also useful especially when using ORM/code generator as in the first example. Lets get back to the Repeater example. If you use Entity framework or similar ORM, and you set the Categories query to load the Products eager loading (meaning each Category is created with its Products loaded already), Entity Framework can have a single connection and only TWO database hits, one for the Categories, and one for the Products. This is very useful in many listing scenarios. It also help especially when you have many parent objects (say Categories) or if the parent object needs to load entities of many different classes (say User needs to load Roles and Permissions and Personal Information and History and …. (if such case is applicable for you of course.

Now that you know what eager loading is, you can go up and check how the Entity Framework does that.