Sync clients with SignalR

SignalR gives you a very easy framework to sync clients. In the ComicsTale project we used it to show a client that another client has changed the same story so he can refresh and see the changes.

Before using SignalR, you need to download the nuget package Microsoft ASP.NET SignalR.

SignalR is called from client side. You need to create a client side proxy that will connect to server side SignalR component.

Full project can be found on GitHub.

Create a class that inherits Microsoft.AspNet.SignalR.Hub:

This will create a proxy in javascript, see that join and notifyHasUpdates are exposed in client side:

When a client starts, he need to decide what to do when he gets a message from server and to call the join method:

The connection name comicStoryNotificationsHub is determined in the HubName attribute on the top of our StoryNotificationsHub class. We create a new method notifyHasUpdates that when called will show a refresh button by notifying the observable collection of knockout. Then we start the connection and when it is started we call the join method to join the group of clients dealing with the same comic story.

When a client change something in a story, all he needs to do is call the server NotifyHasUpdates method through the proxy:

The NotifyHasUpdates method on the server side will call the notifyHasUpdates (that initiated in initConnection client method) on each client except from the caller client.

Posted in javascript, SignalR at June 30th, 2013. No Comments.

Free Team Foundation Service @ is released

On October 29 Microsoft released the free Team Foundation Service. You can add up to 5 users in the free plan and there is no other restriction. You can connect to the service with the web access or Visual Studio or even Eclipse.

Posted in Team Foundation Server at November 1st, 2012. No Comments.

Entity Framework 5 and Enum support – Part 2

In my previous post, I showed how to populate an enum to a lookup table using EF Code First and a new database. Although you might think that having a database prior to coding force you to go to the Database First workflow, you’d be happy to know you can still use the Code First workflow with the help of EF Power Tools to reverse engineer your database to a Code First starting point.

The database schema for this post is:

Lookup table:

Students table:

In addition to this, StudentStatusType.ID is the PK for the FK column Students.StatusTypeID.

The steps to reverse engineer a database are:

  1. Install EF Power Tools extension.
  2. Create a project (Console, web etc.).
  3. Add Entity Framework NuGet package.
  4. Right click on the project. In the context menu click on Entity Framework -> Reverse Engineer Code First.
  5. In the connection dialog enter your server and database name and click OK.

In your project you have now some more files in the Models folder.



In your [dbname]Context.cs you have a standard DbContext class with DbSet for Student and StudentStatusType. In addition you’ll see a folder named Mapping with mapping details using the FluentAPI.

In an earlier post I showed how to generate an enum from a lookup table in the Database First workflow. Although we’re using the Code First workflow, we can use a similar method since the database was created first.

The things we need to change are:

  • Create an enum in addition to the the StudentStatusType class named StudentStatusTypeEnum and populate it with the data in the StudentStatusType table.
  • The PK StudentStatusType.ID should be of type StudentStatusTypeEnum instead of int.
  • The FK Student.StatusTypeID should be of type StudentStatusTypeEnum instead of int.

In order to change the reverse engineer process, right click again on the project but this time click on Entity Framework -> Customize Reverse Engineer Templates (No icon for you buddy, it is still beta).

In the project there are now three more T4 files in CodeTemplates\ReverseEngineerCodeFirst folder:

  • – generates the class that inherits DbContext
  • – generates the entities Student and StudentStatusType
  • – generates the FluentAPI mapping classes
I advise you to install the Tangible T4 Editor. It has a free version and it really helps editing T4 templates.

Creating the enum

Assuming any table name ending with Type should be populated as an enum, we need to add the following code in right before the enclosing bracket of the namespace:

Inside the enum we need to read the table data and populate the enum values. First, just like we did in Database First Workflow, we need to find the connection string in the application config file. With the Database First workflow we used a T4 template who its host can give you access to the Visual Studio environment classes that allows you to enumerate the project files. In our case though, the T4 template host only exposes the model data (it is still beta). Fortunately, the source code of EF Power Tools can be downloaded and changed in a way you’ll get the connection string ready to use!

The steps to do that are:

  1. Download EF source code from
  2. Download Visual Studio 2012 SDK
  3. Open the Power Tools solution. The sln file is in the root folder of the source code.
  4. Open the EfTextTemplateHost class and add this property:
  5. Open the ReverseEngineerCodeFirstHandler class. This code is responsible to open the connection dialog when you reverse engineer a database. The line that do it is:

    After a few rows the connection string is extracted:

    In this class, every place an EfTextTemplateHost is initiated, set its ConnectionString property with the value of the connectionString variable, for example:
  6. Build the project.
  7. Copy EFPowerTools.dllfrom the output directory to the extension directory. The directory should be

    The last folder name might be different. This path can also be found in the registry in this key


    Close all Visual Studio windows if you can’t replace the file.

Now that we got the connection string in our hand we can add code to query the database and populate the enum:

Add these two lines after the first row in the file:

Add this code where we created the enum before:

Change the PK and FK columns type

In file there is a foreach loop that creates the properties for each table column. Inside it we need to add some code that will find out if the current property is the PK or the FK and change the type accordingly:

I used some mapping classes that can be found with MSDN help and also by debugging the EF Power Tools. Now that we have the source code we can attach the VS debugger with the source code to the VS with our project.

Save the T4 template we edited and reverse engineer again. In StudentStatusType.cs you’ll see our enum, and the PK and the FK properties have the type of the new enum.

Run this code and see if you get a new row in the Students table:

What would we do if the lookup table will have more rows? Well, Code First Reverse Engineer is still one time action. You can do that again but it will override all your code and you still want to use Code First. Incremental reverse engineering might come in the future, but I think that after reverse engineering you should only edit your code. If you add more enum values, you can add them to the lookup table with Migrations as I’ve written in my previous post.

Posted in Code First, Entity Framework, Enum at October 23rd, 2012. 1 Comment.

Entity Framework Code First and Enum Support

In my previous post, I showed how to use the new EF 5 Enum support and have your lookup table populated as enum values. This post was for the Database First workflow which we all used when we started using Linq to Sql or the first EF release. We used to see an O/R Mapper as one that reflects database structure in object oriented manner, so building your model from a database looked like the right way to go.

Starting from EF 4.1, you can start with your code and let EF make the database for you – the Code First workflow. With this workflow, you can forget about adding tables, columns and relations with the database tools.

Note: For using Code First with existing database look in this post.

For this demo, the classes structure is as follows:

1. An enum for the possible status of a student:

2. A Student class:

3. A DbContext class:

Running this code will create the database:

As expected, there is only one table named Students in the database. A lookup table for the enum was not created since it doesn’t have a corresponding DbSet, and we can’t add one since the generic type of a DbSet must be a reference type and enum isn’t. We would like to create a table for the enum, fill it with the enum values and add a FK in Students table to this table.

EF Code First mechanism has some conventions which determine how to create the database structure. For example, if your class has an integer property named “ID” (case-insensitive) or “YourClassNameID”, EF will create a primary key column for this property.

There are several ways to customize the way Code First acts:

  1. Using Data Annotations. You can customize column or table names, add keys, add constraints and so on. You can’t create a new table with no DbSet.
  2. Overriding DbContext.OnModelCreating. Inside this method you can use the Fluent API to customize the model creating process. You can do more advanced changes but still you are limited to an existing DbSet.
  3. Using Migrations. This method allows you to add code to apply more changes to the database after you’ve created it in the first place. Here you can also create more tables and add plain Sql code.

To start using Migrations, you have to enable it first. Open the Package Manager Console From Tools -> Library Package Manager -> Package Manager Console. In the tool window make sure your project is selected in the Default Project: drop down.

Run the following command: Enable-Migrations

After running the command, you’ll see a new folder in your project named Migrations. In this folder there are two files. One is Configuration.cs which applies to the migrations configuration. The other is InitialCreate.cs (prefixed with a number) that has the following code:

This code is creating your database according to your classes. The method Up is executed when the database is upgraded to this version. The method Down is executed when the database is downgraded from this version, and should rollback the changes made in the Up method.

I prefer to add another migration to change the database and not change the initial one. This way it will be easy to go back to the default behavior of Code First.

To add a migration, go back to the Package Manager Console window and run the following command: Add-Migration AddEnum. The AddEnum is the migration name and you can change it.

After running this command you’ll see another file in the Migrations folder named AddEnum and prefixed with a number. This file has a class with empty Up and Down methods.

In those methods we would like to add the lookup table as follows:

  • In the Up method:
    • Create the table.
    • Fill it with data.
    • Add a FK to the Students table.
  • In the Down method:
    • Remove the FK.
    • Delete the table.

The code for this migration:

To run the migration run the following command in the Package Manager Console window: Update-Database

After running this command, we have a lookup table with the enum values.

Now what should you do if you add another value to your enum later? You can add another migration and add only the values that are not in the table, however each migration run only once and you’ll have to add another migration with the same code but other values anytime you add a new value.

What we need here is a method that run every time we run the Update-Database command. For that we can use the Seed method in the Configuration.cs file mentioned before. (Notice that every time you update the database you see a message Running Seed method). There is no need to write a downgrade code for this since in the AddEnum code we delete the table completely.

We should add the following code in the Seed method:

Now any value we add to the enum will be added to the table when we run the Update-Database command even if there is no migration that wasn’t applied before.

This solution is much more cleaner than my solution to the Database First workflow. Using designers is fun and I love it but hook into them is much more complicated. Using Code First you got much more simple control over the model generation.


Posted in Code First, Entity Framework, Enum at October 17th, 2012. No Comments.

Free WordPress Hosting – Search Results

Recently I wanted to add my own domain name to my blog. I bought ““ from HostingDude for less than 8$ (Tip: add the domain name to cart but don’t pay yet. Soon you’ll get a 10% discount offer by mail).

I was surprised to see that in I had to pay 13$ a year to add my domain name to my blog, so I decided to look for a free WordPress self hosting.

The first place I found was They have a free no ads plan with 250MB disk space and 6GB monthly traffic. Setup was easy and my blog was up very quickly. Admin tools are very simple and easy to work with. Unfortunately, when I tried to install a plugin (Can you imagine WordPress without plugins?), I got an error message:

“An Unexpected HTTP Error occurred during the API request”

There are some reasons that can bring you to see it, but here the problem was that blocks any script call from your site to outside server. DownVote!

Next try was with You get there 1.5GB of disk space and unlimited traffic! (Actually if there is no hit in a month they delete your account). There are no ads at all, and for skeptics they named the server Registration is very simple. Actually it is so simple that you don’t get any much admin tools beside tools to administrate only the exact hosted domain. If you want to register a subdomain, you need to start from the beginning. Also, about 50% of my http requests ended up with 404 error. Application installer doesn’t work (they say it is due to an upgrade, didn’t say until when). I left this server leaving my account undeleted (no way to do that).

Next station was at The plan has 10GB of disk space and 100GB traffic and no ads. registration is simple and admin tools are simple and powerful. Traffic is very fast, 100% availability. There is no outside scripting limit, so WordPress is fully functional. There is a restriction that you can’t add more than one domain in 24 hours (Doesn’t bother me).

There are many free PHP/MySql hosting providers out there. Meanwhile I stay with

Currently I keep looking for an ASP.NET/MSSSQL free hosting with not much success. Till now I found with 100MB disk space (for MS???) and 2GB monthly traffic. This provider claims it is only for learning. Using it is very hard. Most of the admin pages covered with large ads and you always have to scroll down to see them. Admin tools are very very poor and look like a first year student work. Also, after you go all over the long registration process you find out that your account will be deleted every 90 days, so I’ll keep looking…


Posted in Hosting, WordPress at September 2nd, 2012. 2 Comments.

Keep WCF Client Configuration in a Class Library app.config

When building a WCF client with Visual Studio with the simple “Add Service Reference” feature, you get your client configuration (system.serviceModel section) in your app.config file. If the project that holds the config file is an application (Winform, WPF, ASP.NET etc.) then probably you’re just in the demo phase. Usually you have several projects that need to call the service, and you don’t want to add the service references in each. Also, you don’t want to bind all other project to the WCF technology, so you want them to call a library that communicates with the WCF service.

After creating you class library with the service references and app.config file, you can create a layer over the service calls like that:

Now any call to the WCF service is unaware of the WCF technology:

When running this simple and “obviously should work” code, you’ll get the following famous exception:

Could not find default endpoint element that references contract ‘Service1.IService1′ in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

The reason for that is simple. Class libraries don’t have a configuration file of their own in run-time and they rely on the configuration file of the app they run within. You end up copying the system.serviceModel section to the app.config or web.config of your application and also to your tests project (as said here and here). Although you might accept the duty to do it every time your class library config file gets updated (adding service reference, changing address, changing security etc.), there are scenarios this is not acceptable, for example when you develop your ServiceAgent project for an existing product that you’re not allowed to edit its application config file.

Although this is a very famous issue, there are not many solutions for that (except to copy). Possible solution to the problem you can find here, however the code that generates the client is very complicated. A better solution can be found here, but it assumes that you know the endpoint name and it is hard-coded.

My solution is based on the latter, but is dynamic. Microsoft added a new class in .NET 4 called ConfigurationChannelFactory. This class allows you to create a channel with custom configuration source, for example:

For the above code to work, you need to load your configuration and know the endpoint name. Loading the configuration from file is easy with the ConfigurationManager.OpenMappedExeConfiguration method:

The app.config file is the class library config file. You can have it copied to the application output directory by setting “Copy To Output Directory” to “Copy always” in the file properties.

As for the endpoint name, in order not to make a switch-case for all service reference? you got, you need to find it in the config file. In the config file the endpoint may appear like that:

Knowing the contract name can help you find the endpoint name. The interface hierarchy in the generated client code is:

With an instance of IService1Channel you can call the service and close connection since it is IDisposable, so this is the type you should pass as the generic T parameter to the ConfigurationChannelFactory constructor.

The interface IService1 has an attribute with the ConfigurationName that corresponds to the contract attribute value in the config file:

In order to find this attribute we can find the interface that IService1Channel inherits from and find the attribute with GetCustomAttributes:

With the configuration and the contract name you can find the endpoint:

All above code is making the complete client generation helper method:

With this helper method you can write your ServiceAgent like that:

With this code you have achieved abstraction over the WCF technology and you no longer need to inject XML into the application config file as long as you library app.config is in the application bin folder.

Posted in Configuration, WCF at August 9th, 2012. 3 Comments.

Namespace for Extension Methods

Recently We had a discussion about what namespace would you give to an extension method. Most answers to this question say you should put it in something like “Extensions” or “YourCompany.Technology.Extensions” (like here and here).

The problem with that is probably known to any developer. Since Visual Studio 97 where IntelliSense was added, you learn about the class functionality from the Intellisense list, but the extension method won’t appear in the list until you add the extension method namespace in your using list. Sure it happened to you when you wrote something like “myControl.Nodes.” and you were surprised to see there is no “Where” method. You must have asked yourself “Did they forget to implement IEnumerable<T> when .NET 2.0 was out?”, and after that you try to find the “OfType“ method but you don’t find it either. A quick look will show you that the “using System.Linq;” statement is missing.

This namespace is not there because of possible two reasons:

  1. This file was created before .NET 3.5 where Microsoft added this namespace to any C# file template.
  2. You used the “Remove Unused Usings” feature when no IEnumerable<T> was in use in that file. (Use CodeMaid to do that. It has a white list for that, among many other great features). BTW, unused usings don’t have any effect on run time, only design and compile time. Look here and here.

Same goes for any extension method you write. If your colleague won’t remember the method you wrote (and probably you either won’t remember it after a while), he won’t have any clue about its existence. Even if you add this namespace to any C# template in your organization (Try to change the namespace after that!), it could be deleted.

So why won’t we go back to the days of the big Utils class?

I think we should name extension method namespace after the first parameter (the one with “this“) type namespace. For example, if you’re extending DataObjects.Person, give your extension method the DataObjects namespace. Most times when you use a class in your code you have its namespace inside a using statement (unless you got the instance from somewhere else).

Now what if you want to extend System.String. Someone might think that writing your extension method in System namespace is not allowed / won’t compile / not possible. Well, it is possible and won’t cause you any problem (I’m not an attorney, though).

Think of an extension method as a method you want to inject into the class being extended, so why not inject it into its namespace also?

MSDN namespace naming guidelines say:

You should make every effort to avoid name collisions with types in the core namespaces

As for extension methods, this is not going to cause any collision at all. The thing your should be aware of, is that if Microsoft will ever write a method with the same name and parameters in the class you’ve extended, all your method calls will now go to their code, ignoring your extension method without any compile error or warning. However, it doesn’t matter what is the namespace you have chosen, or which using statement you added.

You just need to find a class name and a method that won’t collide with the core types ever. “iPhoneGoogleFacebook” might be a good prefix. They are not going to buy all of them, don’t they?

Posted in Extension Method at August 2nd, 2012. 2 Comments.

Entity Framework 5 and Enum support

Starting from EF 5 (currently RC, available as a NuGet package), you can use enums in your data model. In older versions, you always needed to use casting if you wanted to compare a property value against an enum value.

Note: This post is using the Database First workflow. Have a look also on my posts about Code First and Code First with existing database.

In the following code, Student.StatusID is an FK column with a constraint to the StatusID column in the StudentStatusType lookup table that has another column StatusName (nvarchar).

For the above query to work right, you had to hold an enum with values that follow the values in the StudentStatusType table, which was a little risky if for some reason you had to change your data in the StudentStatus table.

With EF 5, you can set a property to be of type enum. To do that, right click on the property in the model designer, and select “Convert to Enum”. After establishing your enum, you have to set both sides of the relation to be of type enum, since like in sql, both sides of a relation must be of the same type.

Now with this enum support you can write:

Although your code will look nicer, this feature lacks the ability to generate the enum from the lookup table, so you still need to copy the lookup table to your code.

Fortunately, EF code generation can be customized with T4 templates, and you can start with a template from Visual Studio Gallery. The template that can be used to generate code exactly like the Visual Studio does is still not available for EF 5, but you can use the DbContext generator meanwhile.

The idea is to create the enum as above in the edmx designer, but to query the database in the T4 template.

The original code to generate enums in the template is:

I replaced the foreach loop with:


First we need to find the project config file and load it. This is not so simple since the T4 template code is not running in the context of your project and regular config code won’t work here. For this I used the SettingsManager class available here. Note: Although this code works you can’t debug it in Visual Studio 2012 because it fails iterating ProjectItems collection.

Now you need to get the connection string. The connection string key can be found with the container name. The container is initialized in the template used to generate the DbContext code and you can copy it from there.

In case your database is in your app_data folder, you need to resolve the “|DataDirectory|” macro by yourself since this macro will lead you inside Visual Studio installation folders.

Now before using the connection string, you need to extract just the connection string itself without the metadata info since SqlConnection doesn’t like it.

Now that we got the connection string, we are ready to “select * from”, but we still need to know the table name. So we need to find the entity type that represents the lookup table. Because we set earlier its primary key to be of the enum type, it’s very easy:

The entity type name won’t always be identical to the table name. There is no built-in way to get that, but there is a tricky way. I just assumed that the entity name is the table name. If you want you can use the trick.

It’s time to get the data!!!

I assumed the first column is the primary key and the second is the name, and I didn’t deal with whitespaces and capitalization. You can improve that code like in here.

Well this was quite an ugly code. I hope MS will add a capability to set the lookup table name when you create the enum type.

Posted in Entity Framework at July 24th, 2012. 2 Comments.