Today I gave my session about signalR at Sela Developer Practice.
It went great and I wish to thank all attendees.
Furthermore,I wish to thank everyone who helped me through the
day with my ill baby who I had to bring to the conference.
Here are the demos, including some additional demos we didn’t
go through.
Here, you can see the slides from today’s presentation
Yesterday, I had a great time speaking about signalR in front of WDCIL audience.
We had some problems at the beginning when we couldn’t
duplicate my screen display.
Fortunately Yaniv Rodensky came to the rescue with his
own laptop,and surprisingly all demos worked well.
I want to thank all attendees who came to hear me speak.
Below, you can see the slides from my presentation,
and download demos Here.

Debugging your signalR application on both client and server
can consume time. To save time we might go to Fiddler, or
use the Network tab on our browser’s developer tools.
signalR offers simple logging mechanism for javascript clients.
in this post I’ll briefly show how to enable this log, what it
writes when enable, and how to add some custom log records.
Enable logging
To enable logging you simply need to add the following
$.connection.hub.logging = true;
After enabling the log you’ll see what client events were
triggered by the server.
For example, when you call in your Hub code (server side) you
call Clients.All.sendMessage, this is what you’ll see on your
console tab (taken from Chrome console)
[12:02:21 GMT+0200 (Jerusalem Standard Time)] SignalR: Triggering client hub event 'sendMessage' on hub 'chatHub'.
Custom logging
Apart from simply using the console.log() function, you
can use the $.connection.hub.log() function provided
by signalR. This function won’t do anything if logging
is disabled, end write to the console log if enabled.
Let’s see an example:
In the following code example we call sever side’s chat method
and log our call write away.
sendMessage : function () {
viewModel.hub.server.chat(this.message());
$.connection.hub.log("Sending " + this.message() + " to the server");
this.message("");
}
And this is what we’ll see on our console:
[12:59:08 GMT+0200 (Jerusalem Standard Time)] SignalR: Sending Hi fellows to the server
Summary
signalR logging is simple yet very handy tool to monitor our application
at development time. You may find it useful and all you have to do
when going to production is to disable the log.
First signalR eBook was published yesterday. The book was
authored by Jose M. Aguilar, Microsoft ASP.NET MVP.
The book is free of charge along with code samples.
Click here to download.
SignalR Protocol
After showing how to get started with SignalR, how to use it with .Net client and how
to self host it, I wish to show what SignalR does on the network level. In this post
I will review the protocol SignalR implements and see what data is sent at the various
stages.
Negotiation phase:
One of SignalR best qualities is its ability to support various communication
techniques without its API user have to change his/her code. Therefore both
client and server needs to “negotiate” their communication capabilities.
The browser requests the URL of /SignalR/negotiate with a number in the
query-string parameter and gets a JSON response, lets have a look at
some of its members:
ConnectionId: a unique ID for the signalR client, will be used at further requests.
ProtocolVersion: A SignalR protocol version. (If you’re running RC2 you’ll get 1.1
on its value)
TryWebSocket: a boolean value, if true – the client can try use WebSocket (because
the server supports that, otherwise false.
KeepAlive: The time in seconds for the server to send empty message to the client
to see if it is stile “alive”.
Url: The base Url for all SignalR requests. it will be relative to the SignalR hosting
site Url.
WebSocketServerUrl: Deprecated, and always bee null.
Connect phase:
After negotiating with the server, both parties have agreed on the underlying
communication technique, then the client sends a “connect” request with two
query string parameters:
Transport: The communication technique used (WebSocket, ServerSentEvents,
ForeverFrames or LongPolling)
ConnectionId: The unique id given for this client at the negotiation phase.
Update for the released version (1.0)
After the negotiation, the server returns also a longer string of ConnectionToken,
this string replaces the connection id at the connect phase request.
Connect phase data
Apart from query string, the client can call the server and vice versa. These
messages will look like the following:
Client –> Server :
{H: “hubName”, “M”: “MethodName”, “A”: [arguments] , “I” :, messageNumber }
That’s a JSON message sent to the server with the following parameters:
H: Hub name, the hub activated on the server
M: The method to operate on the hub
A: the methods arguments,
I: Message index, where each client has its own counting.
Afterwards, the server will respond (if no error will occur) with {I: messageIndex}
where the message index is the same as the one received from the client.
Server –> Client
In here we’ll see the same structure inside some larger message, starting with the letter C,
then after the first letter M you can see the same structure only the method name is the
method should be run on client side.
{"C":"B,6|O,0|P,0|Q,0","M":[{"H":"hubMane","M":"clientMethod","A":[arguments]}]}
Note: Both server and client doesn’t send any parameter names, but sending the
argument in an array. Therefore, with signalR there shouldn’t be any overloading
of methods.
If you wish to see the actual frame while running your application
you may see it on Chrome development tools, or by fiddler. You may
read more about using fiddler with SignalR.
Summary:
This was a short glance at the network transport used by SignalR, It
can help us better understanding and more easily debugging our applications.
About embedded & external resource files
Recently I was asked by a colleague of mine to help him with a problem.
He had tried numerous times to work with resource files on a web project
and got many errors until he had moved the files build action from content
to embedded resource.
What’s the difference?
Embedded resources are files that are put inside the compiled assembly when compiling it.
However, when a resource file build action is content, only the .designer.cs file that
comes with it is compiled (you can see that its build action is compile) and the .resx file
is copied as is when publishing the application.
However, when adding resource (.resx) file into another application or class library, its
default build action will be Embedded Resource instead of Content . The .designer.cs
file will have the same build action, Compile (as every code file).
You may see it from both screenshots below:
Please note another two different values on the CustomTool property. The CustomTool
is the component in charge of creating the code in the .designer.cs file. This property is
overlooked. The Embedded Resource has ResXFileCodeGenerator custom tool while
the other one has GlobalResourceproxyGenerator custom tool.
And what is the difference between the two custom tools?
The main difference is in the .designer.cs . This file contains class with static properties
where each property uses ResourceManager.GetString method in its getter, to return
the value.
Here’s the code (on both generated files)
internal static string MyResource {
get {
return ResourceManager.GetString("MyResource", resourceCulture);
}
}
However, the ResourceManager property is created differently. Let’s have a look on how it
is created in the with the file generated with ResXFileCodeGenerator custom tool
(Embedded resource).
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MyClassLibrary.ClassLibraryResource", typeof(ClassLibraryResource).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
And the one generated by GlobalResourceproxyGenerator (in use in web applications,
Content buld action).
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Resources.MyWebResource", global::System.Reflection.Assembly.Load("App_GlobalResources"));
resourceMan = temp;
}
return resourceMan;
}
}
The difference is the Assembly of the resources. While the first code snippet goes to
the assembly holds the class inside the .designer.cs file (which is the class library
compiled DLL), the web application code loads assembly by reflection.
And what is the assembly it loads?
Well, the aspnet compiler generates assemblies from all markup code, where each
folder is compiled into different assembly. Therefore the actual resources are
located in different assembly than the code behind (which compiled by the
aspnet compiler as al content files) and therefore published as is to the target
server where our web application runs.
Summary:
Although looks the same and has very similar code, when having resource file
on ASP.NET applicationis by default not embedded resource.
To have the resource outside of the ASP.NET application’s
assembly we must have the right custom tool chosen.
Self Hosting SignalR

SignalR, as shown in the earlier posts, can be hosted within a regular ASP.NET application
(in other words, on IIS), but can also be self-hosted. You may want to do so if you don’t
want the SignalR hosting machine to have IIS installed. In this post I’ll show a simple way
of doing so with a console application. It won’t be much different with windows service
and I’ll explain how to do it there as well.
Step 1: Install Nuget packages
There are two nuget packages that you need to install:
1. Microsoft.AspNet.SignalR.Owin
2. Microsoft.Owin.Host.HttpListener
3. Microsoft.Owin.Hosting
These three packages will install also the OWIN package (dependency of all three packages),
Microsoft.Aspet.SignalR.Core (dependency of Microsoft.AspNet.SignalR.Owin) and
Newtonsoft.Json (dependency of Microsoft.Aspet.SignalR.Core).
Step 2: Write your Hub / Connection code
In here, there is no difference between the hosting environments.You may find example on
some previous signalR posts.
Step 3: Start your Host
To start your host, use the Microsoft.Owin.Hosting.WebApplication class from Microsoft.Owin.Hosting
assembly. This class has static method named Start. This method has 3 overloads, we will use the generic
one and give it a custom class as type parameter. This class should contain a method named Configuration
that expects IAppBuilder as a parameter. This parameter will be supplied by the Start method of
WebApplication class.
This is how the method call should look like:
using (WebApplication.Start<MyStartUp>(url))
{
Console.WriteLine("Server is running, Press <Enter> to stop");
Console.ReadLine();
}
The Start method will use the url parameter, call the Configuration method of
MyStartUp class and returna Disposable object. All we have to do here is wait
for some user action and until that don’t leave the using block,
so the Dispose method won’t get called.
In real-life you might use windows service to host SignalR. If so, you may use a
private IDisposable member on the service class. on the OnStart method of the
windows service call the Start method initializing the IDisposable member
with its return value, and calling its Dispose method on the OnStop or Dispose
method of the service class.
Now, let’s look at MyStartup class
internal class MyStartUp
{
public void Configuration(IAppBuilder app)
{
app.MapHubs();
}
}
You can see above the call for MapHub method , very similar to the call we
make in ASP.NET application, on Global.asax file. However It is not the same
method. This method comes from Owin.OwinExtensions
class.
Step 4: Consume
Your SignalR server is up and running, you may consume it’s services in any way you like.
No difference between the fact that it is hosted in a self hosting environment and not IIS.
Summary
Self- hosting SignalR is easy. Hosting it on a windows service comes with the regular
”headache’ of any windows service however the SignalR code itself almost looks the same.
Update: I’d just realized that I’ve copied the wrong namespace of
System.Runtime.CompilerServices instead of Owin on step 4.
Thanks @davidfowl for correction.

Sela SDP conference, the biggest one yet, will be held May 5-9, 2013.
This conference includes 5 conference days, 3 days of full tutorial workshops, and
2 days of breakout sessions.
In this conference you’ll also have the chance to meet with some international experts
You can check out our list of sessions and speakers .
I will speak there about SignalR , new and exciting ASP.NET project I’ve recently
posted about.
Our last conference had a record in terms of attendance, a record that we hope to break
once again. I advise you to register in advance to save you a spot and also to enjoy the
lower price of our early-bird registration.
Hope to see you there.
Using SignalR with .Net client
In my previous post I demonstrated how to use SignalR with javascript client.
After this post, I got an email from my extremely talented colleague
Bnaya Eshet asking if there’s a way to to SignalR with .Net client.
I said “yes” of course so now I want to demonstrate how to do it.
The server side code is the same as in my previous post, this is just
another client example.
Step 1: Create .Net client project:
Add some .Net project, any project type will do, I will demonstrate with
a WPF project works with MVVM. The code samples will be from the
View-Model.
Step 2: Install SignalR .Net client nuget package
On the project you’ve just created, install Microsoft.AspNet.SignalR.Client
package.Make sure that both server project described in previous post has
the same version. If you didn’t, you will get an error of
“incompatible protocol version“ while trying to connect.
Step 3: Create SignalR connection instance
Using the namespace of Microsoft.AspNet.SignalR.Client.Hubs on
Microsoft.AspNet.SignalR.Client assembly (referenced to your project after
NuGet package installation) has a HubConnection class. This class used for
keeping persistent connection.
That’s how you create an instance of this class:
_connection = new HubConnection("http://localhost/RanWahle.Blog.SignalR.Demo");
//useDefaultUrl = true
Where the first parameter is the site address, and the second parameter
named useDefaultUrl tells you whether to use the default hubs URL or not.
You should set this parameter according to the way your hubs are registered
on your server.
The default value for that parameter is true, you need this one only if
the hubs aren’t registered at the default URL (thanks @davidfowl)
Step 4: Create proxy hub
Another component you can work with is the hub proxy component.
This componentis created by the connection in previous step, using its
CreateHubProxy method. This method returns an IHubProxy interface.
by default it will create a HubProxy class that implements it.
That’s how hub creation looks like:
IHubProxy proxy = connection.CreateHubProxy("soccerResultsHub");
Step 5: Handle server messages
The proxy created on previous step now needs to handle server messages. as seen in
my previous post The server calls Client.All.someMethod pseudo method where
someMethod is actually a message that is sent to the clients. There are several
extension method of the IHubProxy interface, the recommended on is the On method
which accepts the event name as string, and the arguments as a collection of parameters.
This is how it looks like:
proxy.On<string, string>("updateTeams", (homeTeam, visitorTeam) =>
{
HomeTeamName = homeTeam;
VisitorsTeamName = visitorTeam;
});
We’ve used here two strings as a type parameters because the server sends two strings to the client
Here’s the corresponding server code.
Clients.All.updateTeams(_game.HomeTeam, _game.VisitorsTeam);
Step 6: Invoke server methods
In here, we use another IHubProxy method (a non extension one this time) called Invoke.
This method accepts the server side method as a string and a collection of parameters.
This is how it looks like:
proxy.Invoke("UpdateHomeTeamName", HomeTeamName)
Where the corresponding server method named UpdateHomeTeamName and accepts
one string as a parameter.
Summary
SignalR has a library for .Net client as well as javascript clients. If you are a .Net client
programmer you can also interact with the server suing SignalR . The steps above
demonstrate how you can do this very easily.
The full code example can be found here
Enjoy, I’m sure you will.
Getting started with SignalR
Recently I’ve begun testing ASP.NET.SignalR, an open source project that supports real-time web functionality in our application.
SignalR can be added to an existing ASP.NET application and help as easily gain real-time functionality
in no-time. It can run with browsers that supports HTML5 WebSocket or long polling (IE 8).
SignalR has both server and client code, its client code is based on jQuery
In this post I’ll demonstrate how to work with SignalR along with a few basic terms related to it.
Install SignalR nuget package
First, you should install Microsoft.ASP.NET.SignalR nugget package, you can do so either by running install command on
nuget management console, or do so by searching the package on the nugget packages GUI. It will install another 4 SignalR
related packages along with jQuery and JSON.Net packages which SignalR packages depends on.
Server Side Code
Now, what we need to do is to have some code that will act as our service, in SignalR terms it is called Hub.
Our hub will be named SoccerResultsHub and will enable to update the home and visitor team, increment score
for each and update the time left.
For some separation of concern (even a demo needs it) here’s a class to manage hold game data
public class SoccerGame
{
private Timer _timer;
public event EventHandler UpdateTimeLeft;
public SoccerGame()
{
TimeLeft = 90;
_timer = new Timer();
_timer.Elapsed += (sender, args) =>
{
TimeLeft--;
if (UpdateTimeLeft != null)
UpdateTimeLeft(this, null);
};
_timer.Interval = 60000;
_timer.Start();
}
public string HomeTeam { get; set; }
public string VisitorsTeam { get; set; }
public int HomeScore { get; set; }
public int VisitorScore { get; set; }
public int TimeLeft { get; set; }
}
This class will be used in our hub that looks like that:
public class SoccerResultsHub : Hub
{
private SoccerGame _game = new SoccerGame();
public SoccerResultsHub()
{
_game.UpdateTimeLeft += (sender, args) => UpdateTimeLeft();
}
public void UpdateHomeTeamName(string teamName)
{
_game.HomeTeam = teamName;
Clients.All.updateTeams(_game.HomeTeam, _game.VisitorsTeam);
}
public void UpdateVisitorTeamName(string teamName)
{
_game.VisitorsTeam = teamName;
Clients.All.updateTeams(_game.HomeTeam, _game.VisitorsTeam);
}
public void UpdateTimeLeft()
{
Clients.All.updateTimeLeft(_game.TimeLeft);
}
public void ScoreForHome()
{
_game.HomeScore++;
Clients.All.updateScores(_game.HomeScore, _game.VisitorScore);
}
public void ScoreForVisitors()
{
_game.VisitorScore++;
}
}
}
For each method on our Hub class, SignalR will create corresponding javascript code enables us to invoke from our client side.
Note the Clients.All.<method> , Clients property of Hub class has the connection context, and its type is self explanatory ConnectionContext .
It has several dynamic properties of which we can add method calls to, the SignalR engine will support extending its javascript , the All property of Clients
Client Side Code
On our HTML document we need to reference jQuery , SignalR base javascript library and the javascript proxy code generated by SignalR for our Hub above.
<script type="text/javascript" src="Scripts/jquery-1.6.4.js"></script>
<script type="text/javascript" src="Scripts/jquery.signalR-1.0.0-alpha2.js">
</script>
<script type="text/javascript" src="SignalR/Hubs">
</script>
We’d also use knockoutJs and that’s how our entire Html will look like:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<label for="txtHomeName">Home Team:</label>
<input type="text" id="txtHomeName" data-bind="{value : homeTeamName}" />
<button data-bind="{click: updateHomeTeamName}">Update</button>
<button data-bind="{click: homeTeamScores}">Scores</button>
<span data-bind="{text : homeTeamScore}"></span>
<br />
<label for="txtvisitorName">visitor Team:</label>
<input type="text" id="txtvisitorName" data-bind="{value : visitorTeamName}" />
<button data-bind="{click: updateVisitorTeamName}">Update</button>
<button data-bind="{click: visitorTeamScores}">Scores</button>
<span data-bind="{text : visitorTeamScore}"></span>
<br />
<span>Time Left:</span>
<span data-bind="{text : timeLeft}"></span>
<script type="text/javascript" src="Scripts/knockout-2.2.0.js"></script>
<script type="text/javascript" src="Scripts/jquery-1.6.4.js">
</script>
<script type="text/javascript" src="Scripts/jquery.signalR-1.0.0-alpha2.js">
</script>
<script type="text/javascript" src="SignalR/Hubs">
</script>
<script type="text/javascript" src="GameViewModel.js">
</script>
</body>
</html>
Using knockoutJs lets us have our client code deals with the data itself and doesn’t involve any DOM manipulation
In our javascript code we declare a view-model and inside it declare a member named gameHub. This member will be declared as the Hub connection
to the server. it will use to start the connection, call server methods and extend the client so the server can call functions on it (it is bi-directional right?)
You can see that gameHub member has client and server members used for both purposes mentioned above
That’s how our javascript code will look like:
var viewModel =
{
gameHub : null,
homeTeamName: ko.observable(),
homeTeamScore: ko.observable(),
visitorTeamName: ko.observable(),
visitorTeamScore: ko.observable(),
timeLeft: ko.observable(),
homeTeamScores : function()
{
this.gameHub.server.scoreForHome();
},
visitorTeamScores: function () {
this.gameHub.server.scoreForVisitors();
},
updateScores: function (home, visitors) {
this.homeTeamScore(home);
this.visitorTeamScore(visitors);
},
updateHomeTeamName : function()
{
this.gameHub.server.updateHomeTeamName(this.homeTeamName());
},
updateVisitorTeamName: function () {
this.gameHub.server.updateVisitorTeamName(this.visitorTeamName());
}
};
$(document).ready(function () {
ko.applyBindings(viewModel);
viewModel.gameHub = $.connection.soccerResultsHub;
viewModel.gameHub.connection.start();
$.extend(viewModel.gameHub.client,
{
updateTimeLeft: function (timeLeft) {
viewModel.timeLeft(timeLeft);
},
updateTeams: function (home, visitors) {
viewModel.homeTeamName(home);
viewModel.visitorTeamName(visitors);
},
updateScores: function (home, visitors) {
viewModel.updateScores(home, visitors);
}
});
});
Summary
SignalR let’s us have bi-directional communication between the client and server. It runs on browsers that support websockets and long-polling
while signalR knows which of those features to use. It depends on jQuery on client side and Newtonsoft.Json (and ASP.NET) on server side.
It is still in alpha stage but sure worth a try, knowing how to use it will help you create great Http based applications.
The entire sample can be downloaded here.
ASP.NET MVC 4 Lab files
Sela Developers Practice is over. I’ve had a great time speaking about jQuery
in a tutorial day about javascript with Gil Fink and Elad Katz, and on ASP.NET MVC 4
in a tutorial day again with Gil and Sebastian Pederiva, .
Demos from our MVC4 lecture can be found on Sebastian’s SkyDrive here, and some
hands-on labs can be found on my SkyDrive here.
I wish to thank all attendees and hope to see you all again on SDP13.
About signing assemblies, GAC and friends
Recently I was asked by one of my colleagues to explain to a customer of his about signing assemblies, putting them into GAC etc. So I’ve decided to put some terms in order, for you to understand what it’s all about.
I’ll try to make it as short as possible saving you allot of technical details and stating all problems you may have ran into.
What is a signed assembly?
A signed assembly is a .Net assembly (EXE or DLL) that has been signed during compilation.
It has been signed by a key file (usually with .snk extension which stands for Strong Name Key) that can be generated by visual studio or from command line (with StongName tool ).
You’ve probably came across a type declaration in a configuration file looking like that:
type="NameSpace.class, Assembly, Version=VersionNumber, Culture=cultureName Or
neutral, PublicKeyToken=SomeHashCode or null" />
The assembly, when signed will have some value on it’s publicKeyToken attribute
at it’s name (instead on null).
Why sign an assembly?
Well, The only reason I see right now is that If you wish to put your assembly in the machine’s Global Assembly Cache (GAC) you must do so. The GAC demands that the assembly will have strong named and it can be provided by signing it.
What is GAC?
the Global Assembly Cache (i.e. GAC) is a place on the machine, where heavily used assembles can be located. The GAC allows as to have assemblies with the same file name differs by their versions. Some of you may have encountered the term “DLL hell” referring to DLL registration where different DLLs with the same file name couldn’t be registered together, the GAC then comes to solve that problem. GAC registration can be done by using GacUtil command line tool that comes with Windows SDK installation or with Visual Studio.
And why register my assembly to the GAC?
You may want to put your assembly into the GAC if the assembly is shared by more than one application. The .Net runtime will look for assemblies on GAC before it goes to the application working directory. Loading assembly is also more efficient from GAC than from a regular file system location. You must’ however be aware of versioning when deploying into GAC because redeployment with the same version may harm backward compatibility.
How do I sign?
Well, That’s easy. On visual studio’s solution explorer, go to the desired project, right click
and choose properties, than go to “Signing” tab
You may want to browse for an existing SNK file or create a new one by choosing “New”
Choosing “New” on the combo box will cause a dialog box to pop, you can then state your SNK file name and choose, if you want, to protect it with password as shown below:

SNK files can be shared between projects, you may note that Microsoft assemblies has the same publicKeyToken, that’s probably because of that.
OK – My assembly is signed, what problems do I face?
Singing an assembly requires that all project references will be from signed assemblies.
That is because when register your assembly to GAC, the runtime will search and try to
load all referenced assemblies from there too. Trying to reference a non signed assembly from signed assembly project will cause a compilation error. The referenced assemblies doesn’t have to be signed with the same SNK
However, the other way around is OK, You can have reference to a signed assembly from non-signed assembly, you’ve probably done so because all Framework assemblies are signed and registered to the GAC.
One other problem you may face is when signing an assembly is when you already have references to it. When signing an assembly and replace the non signed assembly with the signed one, you change the assembly’s signature and therefore it becomes a whole different assembly “all of a sudden”. This will cause visual studio to raise errors because it didn’t find the referenced assembly, Re-adding the signed assembly as a reference can solve the problem.
On production environment you have to make sure that you keep the non signed assembly on the application’s working folder.
Summary
In this post, I briefly explained the basics about signing an assembly and register it to the GAC. At many stages when deploying an application you may come across this issue, I hope this post will help.
Programmer’s Backdoor Trap
Today I’ve encountered something that made a programmer happy but made me sad.
He had to pull data out of Data Warehouse and use it for his system.
Later, he was informed that DWH personnel made his life easy: They’ve decided to write the data into his own database so he wouldn’t have to work so hard.
Unfortunately this news made him happy, and therefore he went on with it, which made me even sadder.
What’s wrong with it?
Well, allot.
1. It opens a backdoor to the system because you have to give permission to another to your
database.
2. It’s hard to maintain. What happens when you deploy\move your database to another
server? Starts making calls to the other system’s owner so he will update his own?
3. Let’s assume you gave the permissions so the other system’s will update your database,
What happens when it fails to do so? Who will know? (a hint, not you, not at first at least).
4. What happens when you need to change your DB schema? How many system owners
will you need to inform? do you wish to keep track? (you probably won’t).
There are more reasons but I think I can leave you with the one’s written above, feel free to come up with some more on your comments.
That’s was a classic programmer’s trap
It is very tempting to have your job easier at the beginning but the price is opening a backdoor to your system, which is too high.
Fortunately it took only a while to persuade everyone that it is not the way to do things. Now, exchanging data between the databases was replaced by reading the data through a web service.
That's was one system I’ve caught at development stage. This also exists on many production systems at the customer I work for. They mainly let the integration system to write on various system’s databases which I struggle hard to prevent.
If you, as a developer, a team leader or an architect see this trap, please identify it, don’t fall and don’t let others fall into it.
KnockoutJS–Dependencies

One of the things we’ll probably need is to be able to have dependency tracking in our bounded data. For example – if we have a customer’s list, we’d like to see the customer’s orders whenever we click on a customer. In this post I’ll demonstrate how to do it using the dependentObservable function of KnockoutJS
Let’s look at the following JavaScript code:
var viewModel = {
customers: ko.observableArray([]),
selectedCustomer: ko.observable(),
orders: ko.observableArray([]),
order: function () {
return { itemName: "", description: "", unitPrice: 0, units: 0 }
},
customer: function () {
return { firstName: "", lastName: "", joinedDate: new Date(), orders: ko.observableArray([this.order()]) }
},
addOrder: function () {
this.orders.push(this.order());
},
addCustomer: function () {
this.customers.push(this.customer());
},
setSelectedCustomer: function(customer)
{
this.selectedCustomer(customer);
}
};
In here, I’ve declared two data structures: customer and order. I’ve also exposed two data members: customers and orders which have the types above respectively. I’ve also exposed the selectedCustomer data-member which will be used for us in the future.
Now, let’s go to our HTML content.
In here we’ll have two tables – one for customers and one for orders. We’ll use templates for our data binding so it will look like that:
<body>
<table>
<thead>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Joined Date
</th>
</tr>
</thead>
<tbody data-bind="template : {name: 'customersTemplate', foreach: customers}"></tbody>
</table>
<button data-bind="click: function() {viewModel.addCustomer()}">Add customer</button>
<table>
<tbody data-bind="template: {name: 'ordersTemplate', foreach: orders}">
</tbody>
</table>
<button data-bind="click: function() {viewModel.addOrder()}">Add Order</button>
<script type="text/html" id="customersTemplate">
<tr data-bind="click: function() {viewModel.setSelectedCustomer($data)}">
<td>
<input type="text" data-bind="value: firstName" />
</td>
<td>
<input type="text" data-bind="textvalue: lastName" />
</td>
<td>
<input type="datetime-local" data-bind="value: joinedDate"/>
</td>
</tr>
</script>
<script type="text/html" id="ordersTemplate">
<tr>
<td>
<input type="text" data-bind="value: itemName" />
</td>
<td>
<input type="text" data-bind="value: description" />
</td>
<td>
<input type="text" data-bind="value: unitPrice"/>
</td>
<td>
<input type="text" data-bind="value: units"/>
</td
</tr>
</script>
You can notice from the HTML another three things:
1. There’s a button to add customer, when clicked it calls the addCustomer function
2. There’s a button to add order, when clicked it calls the addOrder function.
3. Whenever a customer row clicked, the setSelectedCustomer function is called.
All setSelectedCustomer does is assign the customer who’s row was clicked on, to the
selectedCustomer data member. The dependentObservable function will do the rest.
All of that is achieved using the event bindings of KnockoutJS
Now, Let’s have dependencies between the selected costumer and it’s orders:
ko.dependentObservable(function () {
if (this.selectedCustomer()) {
this.orders(this.selectedCustomer().orders());
}
}, viewModel);
What does it do? whenever the selectedCustomer member is changed, it assigns it’s orders to the orders data member, and that’s how we’ve achieved dependencies between the customer and it’s order.
In the function of it’s first parameter, we can have all our dependency tracking code (and that’s all our dependency tracking). The word “this” inside the function refers to the view-model we’ve provided on the second parameter.
Summary
Dependency tracking is something we’d probably want when having data binding with complex data (parent-child structures for example), having master-details view or even computed values. The dependentObservable function of KnockoutJS allows as to do so in a very easy manner. All we have to do is plant our code in the function at it’s first parameter and well… that’s it.
Here is the full example:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript" src="../scripts/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../scripts/jquery.tmpl.min.js"></script>
<script type="text/javascript" src="../scripts/knockout-latest.js"></script>
<script type="text/javascript">
var viewModel = {
customers: ko.observableArray([]),
selectedCustomer: ko.observable(),
orders: ko.observableArray([]),
customerFirstName: ko.observable(),
order: function () {
return { itemName: "", description: "", unitPrice: 0, units: 0 }
},
customer: function () {
return { firstName: "", lastName: "", joinedDate: new Date(), orders: ko.observableArray([this.order()]) }
},
addOrder: function () {
this.orders.push(this.order());
},
addCustomer: function () {
this.customers.push(this.customer());
},
setSelectedCustomer: function (customer) {
this.selectedCustomer(customer);
}
};
ko.dependentObservable(function () {
if (this.selectedCustomer()) {
this.orders(this.selectedCustomer().orders());
}
}, viewModel);
</script>
</head>
<body>
<span data-bind="text: customerFirstName"></span>
<table>
<thead>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Joined Date
</th>
</tr>
</thead>
<tbody data-bind="template : {name: 'customersTemplate', foreach: customers}">
</tbody>
</table>
<button data-bind="click: function() {viewModel.addCustomer()}">
Add customer</button>
<table>
<tbody data-bind="template: {name: 'ordersTemplate', foreach: orders}">
</tbody>
</table>
<button data-bind="click: addOrder">
Add Order</button>
<script type="text/html" id="customersTemplate">
<tr data-bind="click: function() {viewModel.setSelectedCustomer($data)}">
<td>
<input type="text" data-bind="value: firstName" />
</td>
<td>
<input type="text" data-bind="value: lastName" />
</td>
<td>
<input type="datetime-local" data-bind="value: joinedDate"/>
</td>
</tr>
</script>
<script type="text/html" id="ordersTemplate">
<tr>
<td>
<input type="text" data-bind="value: itemName" />
</td>
<td>
<input type="text" data-bind="value: description" />
</td>
<td>
<input type="text" data-bind="value: unitPrice"/>
</td>
<td>
<input type="text" data-bind="value: units"/>
</td
</tr>
</script>
<script type="text/javascript">
ko.applyBindings(viewModel);
</script>
</body>
</html>
KnockoutJS–Event binding

After binding the data into our page, we wish to be able to create an interactive page. This means that we want to be able to add some behavior to our view-model, triggered by an event on the page. (A button being clicked for example).
You can bind to the click binding the same as you bind to the value only that now it’s expects a parameter-less function. In case you have a method that expect parameters you can have a binding expression like that:
<button data-bind="click: function() {viewModel.setSelectedCustomer(yourParameter)}">Set customer </button>
On that binding you’re operating a function on your view-model triggered by the button click.
The click binding is not restricted to buttons of course, you can triggered event for every clickable HTML element.
If you wish to bind to another events such as mouseover, keypress etc. you need an event-binding. It’s syntax is slightly different but there isn’t a big change.
All events you wish to bind are to be kept inside one block ({event1: handler, event2: handler }) every handler is a parameter-less function however you can bind to an expression the same as the click binding above.
See below, example for event binding with mouseover and mouseout:
<input type="text"
data-bind="value: channelUrl, event: {mouseover: function() {viewModel.title('Get Items')}, mouseout : function() {viewModel.title('')}}" />
Summary
In order to add interactivity to our page (otherwise it won’t be an application) we need to bind events to functions on our view-model. The function expected to be bound are ones without parameters however we can bind to an expression by having the event name, followed by the function() keyword and then, our Javascript expression.
When the event is fired, the bounded function on our view-model will execute. On that function we ought to change another bounded data, call server side by AJAX and so on.
More Posts
Next page »