Creating a simple C# like string.Format() method for JavaScript

Recently I started working on some interesting HTML 5, CSS 3 and JavaScript bits (involving jQuery and jQuery UI). I have worked with all of them before, but not as extensively. Most of my work is some reusable stuff that I can develop generic demos out of (from scratch, unrelated to the custom stuff required here), however, the size of each made me always lazy to take the opportunity to share some nice stuff with you via GuruStop.

I decided to encourage myself to stop laziness by sharing a very small part, then hopefully follow with the real interesting stuff.  Today we look at a simple String.Format() function, similar to the one available in .NET / C#, meaning it uses {0}, {1}, etc… as placeholders.

Look at the code, click the “HTML” tab for the sample HTML used for this one(just a div with an ID), and “Result” for trying it out yourself.  You can also click the “+” button at the right and edit it if you like to!

Note that this one is intended for simple scenarios only. If you need complex / flexible templates, use some templates library like JsRender or knouckOutJS templates.

Did you like this post?

If yes, next post will be another simple one, implementing a Ruby-like format method, where you have {namedArgument} instead of just {0}, {1}. After that we’ll start getting more interesting stuff with CSS and maybe HTML 5.

Stay tuned!

The Easiest Way To Write Async Code – Reading #FunnelWeblog Code

This one is a Back-To-Basics style post. Last month, I was checking some code for the relatively new .NET open source blog engine, FunnelWeb, and noticed this bit of code:


This is just a real easy way to make async call, right?


BTW, you can learn more about the ThreadPool.QueueUserWorkItem() method from MSDN here.


More Interesting Stuff

Playing with it after reading, I found that Matt Valerio seems to have very interesting takes on this method, making you use it in many elegant ways:


I highly recommend the first two articles especially, the code is really elegant.


What IS This Post???

I felt a strong desire to blog something before I go to work today and wanted to see if that’s possible.

Not sure if I should write more posts like this, or am I then converting the blog here to a micro-blog/twitter/tumblr of some kind.

You might help me by telling what you think in the comments.

Generic SaveOrUpdate Method To Persist New/Dirty Entities With Entity Framework 4

In NHibernate there is a Save(entityObject) method, which creates a new row in the database with the given entity object, also, has an Update(entityObject) which updates the row corresponding to the entity object with the property values of this object. It also has a SaveOrUpdate(entityObject) method, which checks the whether the entity object corresponds to an existing row in the database, and chooses whether to call Save(…) or Update(…) based on that.

The way I usually do web applications across multiple tiers, when not using view models specifically, makes me encapsulate much code in Services layer that sometimes does not need to care about whether the given entity is persisted in database or not. Thus wanted to have similar method using Entity Framework as ORM.

Of course I have implemented the method number of times and the code evolved based on which version of Entity Framework I’m coding against, and my knowledge of the framework internals as well.  Actually, when you work with so many ORMs like I did, a new ORM or ORM version turns to only sound like “What’s new in the manual?” thing.

The Method

You must have heard about the new Entity Framework 4 Feature CTP 4.  I was playing with the example code of the Code First enhancements walkthrough, and writing some tweaks, I found myself implementing this function this way in the process ….

The method is implemented as an extension method to the ObjectContext class to call it on any context instance. Also, no namespace is there so that it’s available without having to add any using namespace … statement to fine it available.

Also, toy notice the method does NOT call context.SaveChanges(). This is on purpose so that the calling code is still in control when to submit the context changes, and makes the method similar in effect to other ObjectContext methods.

The Calling Code

A sample calling code to this method would be similar to below. This is not the code I used when testing it but the easiest to understand, as most people know the repository pattern already. Also, in many places there have been over-simplifications on purpose (no extra base classes or DI containers etc..)), but this is to serve the sample clarity purpose solely.

I’m assuming you have checked the walkthrough already, but if not, it’s enough to know that Book is a class that represents an entity, and BookCatalog is a class that inherits ObjectContext.

Conclusion / Disclaimer

This method is not special at all. I just noticed that I have not posted code into my blog for very long, and wanted to change this by creating something as small as this one, hopefully to be followed by more advanced stuff that I should be taking out from my internal helper/toolkit libraries. I have stuff related to Entity Framework, NHibernate, Spark, ASP.NET, and others, but those are to come at another time…

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.

Design Patterns Via C# 3.0 – Presentation Featured on SlideShare!

Slideshare is quickly becoming the defacto standard for sharing presentation slides, just as YouTube for videos, and Flickr for images. I recently got into the habit to share my presentations there and use the embed feature to include it in my weblog, and this was the same for the "Design Patterns Via C# 3.0" session.

This morning I got this email from SlideShare

Hey Mohamed_Meligy!
Your slideshow
Design Patterns Via C# 3.0 has been featured on the SlideShare homepage by our editorial team.
– the SlideShare team

WOW .. I couldn’t believe it until I went to and saw it myself …

Featured Homepage


Thank you SlideShare. I never expected the slides to be interesting to that extent :D :D :D.

dotNETwork 7th: Design Patterns Via C# 3.0 Slides and Demos

Design Patterns Via C# 3.0
View SlideShare presentation or Upload your own. (tags: design patterns)

Yesterday was my 2 part session about Design Patterns as part of dotNETwork 7th gathering. Thank you all guys for being there, There was so much interesting stuff about the audience. The conversation we all had even before the session starts, the interaction with all parts of the session, and the great questions.

Thank you all.


You can find the slides for the 2 parts combined in single downloadable file.

Download the Presentation Slides

For the code examples/demos, you can find them in single ZIP file as well.

Download the Code Samples


I hope you enjoyed the session.

Related Links

dotNETwork 7th Gathering: Delivering Design Patterns via C# 3.0

dotNETwork, the most active offline user group in Egypt is having its 7th gathering next Saturday, August 30, which will have two parallel tracks for the first time in the group gathering. BizTalk Introduction, and C# 3.0 Design Patterns, which I will be delivering!

Facebook Event

If I were you to attend the event, it would have been a hard choice too (unless you go simply for BizTalk) ! BizTalk beginner introduction as a topic was not delivered in public sessions before. The only BiTalk sessions I know of were either advanced ones or introducing newer version to those familiar with old version. If you are my friend or you are pretty much into patterns, you may want to give what I have to say a look.

The session parts were primarily intended to be in a couple of dotNETwork gatherings. Now that dotNETwork decided to try out the parallel tracks model having two sessions in the same topic in each track (which is a decision I really like, except that I’d love more distinction between the topics), it was logical to have them in the same gathering / track. I have been thinking whether this should go for the simplest level possible ever, then, decided to stick to the original plan, and even use the long time available for the presentation (1:30h for each part) to go say more about related topics, as I have so much interest in delivering this in certain way for long time now.

About the Session

I’m still messing around with the agenda / exact sequence of the components to be delivered in the session, but I’m going for making an intro to so many topics. The session is meant to target a very wide range of developers. Pretty much anyone who knows a little about C# 2.0+. I’ll start by identifying what a "pattern" means, and then go talking about different object oriented design principles, meaning things like OCP "Open Closed Principle", not "what’s the different between class and interface?" or "what are abstraction, polymorphism ?" stuff) assuming basic knowledge of the latter but still going through it.

I’ll present around 2 examples of each category of the gang of four object oriented design patterns, and probably a couple more from other sources, highlighting few C# 3.0 features using examples from O’reilly "C# 3.0 Design Patterns" book. Building on the object oriented patterns and principles, I’ll go introducing some enterprise patterns (yeah, pretty much Martin Fowler work), and end with a small introduction to "Domain Driven Design", which I plan to deliver in a long session (may another two part one, with dotNETwork or maybe ITWorx CuttingEdge Club or public SilverKey DemoDay – if any) with respect to ASP.NET MVC framework in similar manner to Rob Conrey’s StoreFront series.

This can move the range of fresh and classic developers knowing just the basic language features and getting that to work in small project to see the trends in the software industry world wide, and in the same time provide some exciting topics for the experienced developers willing to know more about the rarely discussed topics in Egypt developers community. Needless to say, the key to the session is audience interactivity. I’m dying for questions and discussions from now already.

Of course this is not going to be fully covering any of the topics. After all, this is still a presentation, not a course!

About the Day

The event will be next Saturday, August 30th at the Canadian International College, in "El-Tagamo3 El-5ames".
There will be buses at Nady El-Sekka (11:00 AM – 11:30 AM)
Remember, this is a FREE event.


12:00 – 13:30

Tec-Talk Wiz BizTalk (Part 1)
Tamer Mohammad Fathy AL-Khouly,
Mohammad Yousri El-Farsi.

Design Patterns via C# 3 (Part 1)
Mohamed Ahmed Meligy.

13:30 – 14:00


14:00 – 15:30

Tec-Talk Wiz BizTalk (Part 2)
Tamer Mohammad Fathy AL-Khouly,
Mohammad Yousri El-Farsi.

Design Patterns via C# 3 (Part 2)
Mohamed Ahmed Meligy.

Sessions will be video recorded. Good that I’m not missing the BizTalk track completely :).

Related Links


Please drop me a comment here or email via blog contact page if you intend to come and have certain tip / suggestion for the session.

Link List 20080617

· Everything You Wanted To Know About MVC and MVP But Were Afraid To Ask

· Functional Programming in C# 3.0: How Map/Reduce/Filter can Rock your World

· MbUnit 2.4 – Avoiding Crappy Data Resulted From The Test

· Managed Extensibility Framework

· IronRuby at Tech Ed 2008

· Velocity: A Distributed In-Memory Cache from Microsoft

· Must See WF/WCF Influencer MSDN Webcasts

· WCF Webcast Series (Old but good)

· Using CSS to Fix Anything: 20+ Common Bugs and Fixes (Found by Mohamed Tayseer)

· A jQuery Client Status Bar

· jQuery for MVC preview 3

· Hands on Labs for Web Client and Smart Client (Web Client Software Factory, Smart Client Software Factory)

· Code Style Review Using Microsoft Source Analysis

· Did you know… You can use Tracepoints to log “printf” or “console.writeline” info without editing your code? – #237

· SOA: Making The Paradigm Shift Part 9 of N

· Functional C# – Learn from F# and LINQ

Link List: Language Topics, Data Service, jQuery,F#, Spec#, Specs Reading, etc…

It all started with an email Mohamed Hossam (AKA, Bashmohandes) sent to SilverKey Tech. (the company I work for) local office here in Egypt, referring to the article "Foundations of Functional Programming – Part 1 – B# .NET Blog".

It inspired me to send few more language links:

I also referred to the latest version of DLR hosting spec., stating that it’s quickly changing and already not up to date still.

Besides, I included some more reading bonuses:

So, I thought I should share them here as well!, although I hate to keep the habit of just "sharing links" rather than "writing my own posts", but let it be … for now!