A Simple Physics Game using Silverlight and Farseer Engine

Play Now!

Download the Farseer Physics Engine | Download Source

These days, I have become very much interested in physics games. So I decided to search the internet for some good tutorials. In no time I discovered that such games were made using a 2D ‘Physics Engine’. After more searching, I found the Box 2D Physics Engine. I decided to write a small physics based game using Silverlight, but was not able to find a good port of this engine for C#/Silverlight. So, I choose the Farseer Physics Engine which is freely available from Codeplex. As, I said, I am pretty new to using physics engines (and even writing games for that matter !), please don’t expect too much from this tutorial.

Physics Engine Basics

A physics engine is basically a set of classes, that helps in simulating response of objects to forces and collisions. With a physics engine, we first programmatically create a ‘World’ with different types of ‘Bodies’. Then we apply ‘Force’ to one or more body and ‘Step’ through time. The physics engine automatically updates the positions of these objects in the ‘World’ with respect to time.

1
2
3
4
5
6
7
8
private  void Init()
{
world = new World(new Vector2(0,0));
InitializeGameBoard();
CreateStaticObjects();
CreateDynamicObjects();

}

Two crucial things involved in using a physics engine are:

  • Continuously stepping the world forward in time and calculating new positions of bodies.
  • Representing the ‘Bodies’ of the “World” graphically on the game screen using a suitable drawing API.

Given below is the drawing subroutine which I have used in my game:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public void DrawEverything()
{
canvas1.Children.Clear();
canvas1.Children.Add(gameboard);
foreach (Body b in _world.BodyList.Where(n => (n.UserData is ObjectTypes && ObjectTypes.Border != (ObjectTypes)n.UserData)))
DrawItem(b);
}

public void DrawItem(Body item)
{
if (item != null)
{
if (item.FixtureList != null && item.FixtureList.Count > 0)
{
FarseerPhysics.Collision.Shapes.Shape s = item.FixtureList\[0\].Shape;
if (s != null)
{

if (item.FixtureList[0].ShapeType == FarseerPhysics.Collision.Shapes.ShapeType.Polygon)
{
Polygon poly = new Polygon();
PolygonShape ps = (PolygonShape)item.FixtureList[0].Shape;
int vertexCount = ps.Vertices.Count;
poly.Points = new PointCollection();
gameTransform.Rotation = item.Rotation;
if (ps != null)
for (int i = 0; i < vertexCount; ++i)
{ poly.Points.Add(gameTransform.Transform(new Point(ps.Vertices[i].X, ps.Vertices[i].Y))); }
poly.Stroke = new SolidColorBrush(Color.FromArgb(125, 0, 0, 0));

Canvas.SetLeft(poly, (item.Position.X-7.5)/scalefactor );
Canvas.SetTop(poly, (item.Position.Y+7.5)/scalefactor );

if (item.UserData is ObjectTypes)
{
ObjectTypes ot = (ObjectTypes)item.UserData;
switch (ot)
{
case ObjectTypes.Sink :
poly.Fill = SinkColorBrush;
break;
case ObjectTypes.Cubes :
poly.Fill = normalObjectBrush;
break;
case ObjectTypes.Striker:
poly.Fill = StrikerBrush;
break;

}

}

canvas1.Children.Add(poly);

}
}

}
}

}

Basic idea behind the game

My game is pretty basic . It is very similar to carrom with the exception that all pieces are rectangular. The blue piece is called the ‘striker’ which you can move using arrow keys. All other pieces should be pushed in the four holes on the corner of the board, by colliding the striker against them. If you can get rid of all pieces within time, you win,else you loose.

he four white rectangles are of type "Border" and the black ones are "Sink". The 'Border' objects are never shown on the screen.

The actual game screen. The green rectangles are 'Cubes' and the blue one is the 'Striker'.

There are four different categories of objects in the game. These are ‘Border’,’Striker’, ‘Cubes’ and ‘Sink’. Graphically all objects are represented by rectangular shapes. The ‘Border’ and ‘Sink’ objects are “Static”, i.e. they don’t move if force is applied. Rest all objects are “Dynamic”, i.e. they respond to collision and application of force. The ‘Border’ objects collide with all types of objects. The ‘Sink’ objects only collide with ‘Cubes’ (and not with ‘Striker’).The ‘Striker’ collides with all, except ‘Sink’. The whole game has code behind of around 300 lines (excluding comments).

Using BackgroundWorker to do the processing

As shown in the above diagram, refreshing the game screen is part of continuous loop which constantly updates positions of all game objects. The process of calculation of new positions happens when we make the “World” take a “Step” in time . To achieve this in Silverlight application , I have used the BackgroundWorker class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
bool World_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
{
if (fixtureB.Body.UserData is ObjectTypes && ObjectTypes.Cubes == (ObjectTypes)fixtureB.Body.UserData)
{
_world.BodyList.Remove(fixtureB.Body);
}
score = (max_score - _world.BodyList.Where(n => n.UserData.Equals(ObjectTypes.Cubes)).Count());
if (score == max_score)
{ isGameOn = false; button1.IsEnabled = true; }
_worker.ReportProgress(0, score);
return true;
}

void Worker_DoWork(object sender, DoWorkEventArgs e)
{

if ((_worker.CancellationPending == true))
{ e.Cancel = true; }
else
{
_world.Step(1.0f);
gametimectr--;

if (gametimectr <= 0)
isGameOn = false;
}
}

void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{label1.Content = e.UserState.ToString();}

void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DrawEverything();
lblTime.Content = gametimectr.ToString();
if (!_worker.IsBusy && isGameOn)
{ _worker.RunWorkerAsync(); }
label1.Content = score;

if (!isGameOn && max_score == score)
{ ShowEndGameMessage("You Won!"); return; }

if (!isGameOn)
{ ShowEndGameMessage("Game Over!"); return; }

}

The method ‘Worker_DoWork’ is executed via ‘BackgroundWorker’ to ‘Step’ further in our ‘World’. The ‘World_OnCollision’ method is configured to handle all collisions that happen in our ‘World’.Since this method is called from the ‘BackgroundWorker’, it does not have access to UI elements. Hence it calls ‘_worker.ReportProgress’ to update the UI.

Doing more!

As I said earlier, this is my first attempt at using a physics engine. Currently my code only handles rectangles . Soon I will add code to handle more types of objects. I plan to write more articles after exploring features offered by the’Farseer’ engine. I hope you found this article helpful for getting started with physics engines. Do let me know your comments, advice or criticism.

How To Play Your Favorite Melody with Arduino

My Freeduino board playing a melody!

In this tutorial, I will discuss how make Arduino play your favorite melody. There is a nice tutorial which illustrate the basic process here. But to play your favourite melody you will have to get the combination of notes, durations of individual notes and pauses as precise as possible. In this tutorial, I will discuss how to develop a sketch for Arduino to play custom melodies and way to test the sketch on your PC before writing it to Arduino board. Things you will need:

  • Piano notes for your melody.
  • This example as the starting point for the sketch.
  • PC program to test your note sequence. (read on ..!)

Finding notes for your melody/tune

If you can play it on piano, you can easily write them down on paper. If not, then you can search for notes on the web. For this example, I would be using very simple melody containing following notes:

1
2
cdf dfg fga gab abc#
(plays piano keys in this fashion: 123,234,345,456,567)

Writing your sketch

I would advise using the same sketch as mentioned here: http://arduino.cc/en/Tutorial/Tone. However, we are not going to directly modify this sketch. Notice the array ‘melody’ and ‘noteDurations’ in the C code. What we need to do, is find correct elements and their sequence for these two arrays. This is not an easy task and at some point you will always feel the need of a simulator where you could test your compilation. This is where we create a PC program to test note sequence.

Creating PC program to test note compilation

I am using C# to write a simple program (similar to one in example) to test my notes compilation. This program uses PC speakers to generate sound and gives a fair idea of what the notes will sound with Arduino. Also, it is very easy to modify and fine tune your compilation using the C# program. This is how the array values looks like in the C# program for the melody I selected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//Play the following notes
//cdf dfg fga gab abc#
int[] melody = new int[] { NOTE_C4,0,NOTE_D4,0,NOTE_F4,0,
NOTE_D4,0,NOTE_F4,0,NOTE_G4,0,
NOTE_F4,0,NOTE_G4,0, NOTE_A4,0,
NOTE_G4,0,NOTE_A4,0, NOTE_B4,0,
NOTE_A4,0,NOTE_B4,0, NOTE_C5,0};

int[] noteDurations = new int[] { 8,8,8,8,8,4,
8,8,8,8,8,4,
8,8,8,8,8,4,
8,8,8,8,8,4,
8,8,8,8,8,4};


for (int thisNote = 0; thisNote < 30; thisNote++)
{
int noteDuration = 1000 / noteDurations[thisNote];
if (melody[thisNote] > 0)
Console.Beep(melody[thisNote], noteDuration);
else
System.Threading.Thread.Sleep(noteDuration);
}

You can download the full C# code here. Now once, you have perfected your compilation, you can simply copy the array variables along with their values back into your Arduino sketch and just compile it. Given below are snippet of C code after pasting the array values in the Arduino IDE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int melody[] = { NOTE_C4,0,NOTE_D4,0,NOTE_F4,0,
NOTE_D4,0,NOTE_F4,0,NOTE_G4,0,
NOTE_F4,0,NOTE_G4,0, NOTE_A4,0,
NOTE_G4,0,NOTE_A4,0, NOTE_B4,0,
NOTE_A4,0,NOTE_B4,0, NOTE_C5,0};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = { 8,8,8,8,8,4,
8,8,8,8,8,4,
8,8,8,8,8,4,
8,8,8,8,8,4,
8,8,8,8,8,4};

Also don’t forget to change the constant representing array length to correct value in this line of your sketch :

1
for (int thisNote = 0; thisNote < 30; thisNote++) {

Download the full sketch here.

Play the video (below) to listen to the PC and Arduino playing the same melody:

Finally

I hope this tutorial will help you play your favorite melody with Arduino. The approach which I described in this article should work almost all types of microcontrollers. If you know better tools to do this, please drop a me a comment. Suggestions and criticism are always welcomed (as I am very new to Arduino).

Event Log Monitor using C# and WebSocket (HTML 5)

Download code for this article

HTML based client application (uses WebSocket to fetch EventLog entries).
HTML based client application (uses WebSocket to fetch EventLog entries).

Introduction

This article is about creating a simple web based event log monitoring application that uses “server push” to update data. It shows how to use WebSocket to implement “server push” technology using C#. I have written a very simple multithreaded WebSocket server for the example presented in this article. If you are new to WebSocket please visit this site http://en.wikipedia.org/wiki/WebSockets . WebSocket is relatively new technology, with lot of potential. In this article, we will see steps involved in creating a very simple WebSocket based application.

Client Application

The client here is a single page application written using HTML and Javascript. However to run the client , you will require a browser which supports WebSocket. I have developed and testing the application using Google Chrome version 5.0.375.127. It should work with Firefox 4, but I haven’t been able to test. Attached below is a screenshot of the application. Our client application displays EventLog events in real time. As soon as an event is entered in systems EventLog, it is displayed to the user. There are three buttons on the client interface. Clicking on the “Try to Connect” will initiate a WebSocket connection. The “Stop” button will stop listening to server broadcast. This was included to demonstrate two way messaging. The “Close” button will close the connection. Now let us look at the javascript code which makes the client work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function btnConnect_onclick() {
var x = document.getElementById("log");

if ("WebSocket" in window) {
ws = new WebSocket("ws://localhost:8181/demo");
ws.onopen = function() {
ws.send("Hello Server !");
document.getElementById("Button1").disabled = false;
document.getElementById("btnConnect").disabled = true;
};
ws.onmessage = function(evt) {
var node = document.createElement("div");
node.setAttribute("class","item");
node.innerHTML = evt.data;
x.insertBefore(node, x.firstChild);
;
};
ws.onclose = function() {
alert("socket closed");
document.getElementById("Button1").disabled = true;
document.getElementById("btnConnect").disabled = false;
document.getElementById("Button1").value = "Stop";
flag = true;
};

}
else
{alert("The browser doesn't support WebSocket.");}

}

The code above is called when the user clicks on “Try to Connect” button. Here we first create a new “WebSocket” object, by passing the URL of the server. The “ws.onopen” function gets invoked when a connection is opened successfully. Sending data to server after that is as simple as calling “send” method as shown in code above. The “ws.onmessage” function is invoked on successful receipt of data. The good part here is that the protocol makes sure that it is possible to return all data sent by server in one go (as opposed to reading from a stream). The “data” property on the parameter to this function contains data sent by the server. The “ws.onclose” close method gets called when either the “server” or “client”, terminates the connection. In this function we are changing the UI properties of the buttons.

1
2
3
4
5
6
7
8
9
10
function Button1_onclick() {
if (flag) {
document.getElementById("Button1").value = "Start";
ws.send("STP");}
else {
document.getElementById("Button1").value = "Stop";
ws.send("STR");}

flag = !flag;
}

The code above is for two way communication between client and server. There is a common button “Start/Stop” using which user can tell the server to temporarily stop sending updates. To stop/restart listening, client sends the text “STP” and “STR” respectively. So, this is all the code which we need for the client (apart from the HTML). If you have used AJAX , the this code should be strikingly similar. However AJAX and WebSocket are very different technologies, I will discuss that in last section. But the good part with WebSocket is, that there is nothing new to code at the client side. In fact you can very easily port all your AJAX applications to WebSocket. The real difference is at the server side and that is where things start getting a bit complicated.

Writing a WebSocket Server

As I have said earlier, the server is the place were things get complicated. This has nothing to do with the WebSocket protocol, but with mindset of web developers(like me) who generally don’t have too much exposure to sockets programming. Till now life in web development was made easier by HTTP servers and various frameworks. Since WebSocket is emerging technology there are not many tools available to make life easy. So we have to create our own server and code to handle clients (for now at least). The server which I have written for this article is very basic one. It by no means contains comprehensive implementation of WebSocket protocol. My code is monolithic and might have very limited reuse potential. It is basically a TCP server with some additional code to handle WebSocket protocol. It is multithreaded and capable of handling multiple clients. Since the code is pretty complicated, I will only discuss the important points in this article.

Accepting Client connections and Handshaking

Handshaking is the initial exchange of information that happens between server and the client. It basically is a check at each end, to ensure both the parties understands the protocol that is been requested. The server contains an instance of “TCPListener” which listens to incoming TCP request at specified URL and port. I have created a new class called “WebSockClientManager”, which is responsible of accepting a new client connection via the listener and managing the connection. Once a connection is established, I create a new instance of “WebSockClient”, which is another class written by me ; and add it to the instance of “WebSockClientManager”. The idea is, there will be only one instance of “WebSockClientManager” which will manage all clients. Given below is code to initialize a “WebSockClientManager”.

1
2
3
4
5
6
7
8
9
10
11
12
13
TcpListener t = new TcpListener(IPAddress.Loopback, _port);            
m = new WebSockClientManager(_maxConnection,_origin,_location,_port);
t.Start();
while (true)
{
TcpClient c = t.AcceptTcpClient();
WebSockClient w = new WebSockClient(c);
m.AddClient(w);
Thread.Sleep(300);
if (w.WebSocketConnectionStatus == WebSockClient.WebSockClientStatus.HANDSHAKEDONE)
{ w.WriteBuffer = ASCIIEncoding.ASCII.GetBytes("Hello Client "+ w.ManagingThreadId.ToString()); }

}

When “AddClient” method of the “WebSockClientManager” is called, (apart from other things) it creates a new thread to manage this connection, assigning the thread’s id to “ManagingThreadId” property of “WebSockClient” . The following code does this:

1
2
3
4
5
6
7
8
9
10
11
12
13
if (_clientList.Count < _maxConnection)
{
_clientList.Add(c);

Thread clientThread = new Thread(delegate()
{
this.HandleClient(c); ;
});
c.ManagingThreadId = clientThread.ManagedThreadId;
clientThread.Start();
Console.WriteLine("New Thread Started:" + c.ManagingThreadId.ToString());
}

The “HandleClient” method of “WebSockClientManager” is responsible for performing proper handshake and handling requests from client. The client sends a handshake message to which the server responds with something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
//Send Sever Handshake to client.
if (c.WebSocketConnectionStatus == WebSockClient.WebSockClientStatus.CONNECTING)
{
string handshake =
"HTTP/1.1 101 Web Socket Protocol Handshake\r\n" +
"Upgrade: WebSocket\r\n" +
"Connection: Upgrade\r\n" +
"WebSocket-Origin: "+_origin+"\r\n" +
"WebSocket-Location: "+_location+"\r\n" + "\r\n";
streamWriter.Write(handshake);
streamWriter.Flush();
}

For more information on Handshaking in WebSocket please refer to following document:http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-54 . If after transmission of the above text, the client did not drop the connection, it means that the WebSocket connection was successfully established. Once connection is successfully established, we can start sending or receiving data. The “HandleClient” method does two things: performs handshake and if it is done (and everything is OK) reads/transmits data to client.

Reading and writing data to Clients

Now, to write data to all the clients, we simply call the “WriteData” method of “WebSockClientManager”. In this example since we have created instance of a Windows log and have attached handler to “EntryWritten” event. So every time a new entry is made to the log this handler is called which in turns calls “WriteData” and passes information about the new entry:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
if (EventLog.Exists(ConfigurationSettings.AppSettings["LOGTOMONITOR"]))
{
EventLog e = new EventLog(ConfigurationSettings.AppSettings["LOGTOMONITOR"]);
e.EntryWritten += new EntryWrittenEventHandler(e_EntryWritten);
e.EnableRaisingEvents = true;
}
...
...
static void e_EntryWritten(object sender, EntryWrittenEventArgs e)
{
m.WriteData(e.Entry.InstanceId + "::" + e.Entry.TimeGenerated.ToString() + ": " + e.Entry.Message);
}

Inside the “WebSockClientManager.HandleClient” method we listen to data which client is sending. If the client sent “STP” or “STR”, we accordingly change the status of the client, so that it is subscribed/unsubscribed from server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Read data from client. Do whatever is required.
while (n.DataAvailable)
{
if (n.ReadByte() == 'S')
if (n.ReadByte() == 'T')
{
b = n.ReadByte();
if (b == 'P')
{
c.IsSubscribed = false;
Console.WriteLine("Client:" + c.ManagingThreadId.ToString() + " unsubscribed");
}
else if (b == 'R')
{
c.IsSubscribed = true;
Console.WriteLine("Client:" + c.ManagingThreadId.ToString() + " subscribed");
}
}

else
Console.WriteLine("Client " + c.ManagingThreadId.ToString() + "says :" + n.ReadByte().ToString());
}

Addressing Multiple Clients

If you notice the code so far I have used separate threads to handle individual clients. In this case, we will have to terminate threads once a client disconnects or an exception occurs. I have also added a upper limit to number of connections that can be handled by server. If this limit is exceeded, the server simply refuses connection. One problem which I have not been able to solve is detecting disconnected clients. The only place I was able to detect that a client has disconnected, is after trying to send some data to it. If that fails I simply remove the client from the list, so that we free up space for new clients. This is one area where I want to work more with my code, but for the sample application I didn’t bother much. The code to free up closed connection from queue is given below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void AddClient(WebSockClient c)
{
if (_clientList.Count >= _maxConnection)
{ // check if any connection is available
List>int> closedClients = new List>int>();
for (int i = 0; i > _clientList.Count; i++)
{
if (_clientList[i].TcpClientInstance.Connected == false)
{
_clientList[i].TcpClientInstance.Close();

closedClients.Add(i);
}
}

foreach (int e in closedClients)
{
_clientList.RemoveAt(e);
}
}

Configuring the client and server

To run this example, you will have to configure the server and then the client. The server can be configured by modifying its config file. The following entries must be changed:

  • 1
    2
    3
     <add key="PORT" value="8181"/>
    <add key="WEBSOCKETORIGIN" value="http://localhost:49630"/>
    <add key="WEBSOCKETLOCATION" value="ws://localhost:8181/demo"/>
    The “PORT” is the port on which you want your server to listen to requests from client. The value for “WEBSOCKETORIGIN” basically specifies domain/address of webpage which will access the WebSocket server. This is part of security feature of WebSocket which is used to enforce same domain access policy by client browser. It tells the browser that it is alright to allow client page downloaded from “WEBSOCKETORIGIN” to access server at “WEBSOCKETLOCATION”. More details on this can be found here: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-54

  • 1
    2
    <add key="MAXCONNECTIONCOUNT" value="3"/>
    <add key="LOGTOMONITOR" value="Application"/>
    Also you may want to change values for “MAXCONNECTIONCOUNT” and “LOGTOMONITOR”. The first one specifies the maximum number of parallel connections the server should handle , while the later specifies the name of the Windows event log which the server should be monitoring. In the example I am monitoring the “Application” event log, you may want to change it to a different log if you don’t have permissions to this log. In that case you can write a sample windows service/application to write some test entries to your log on some event (just for testing).

  • Once the server is configured, make sure that you change the server address in clients javascript.(In the call to ws = new WebSocket(“ws://localhost:8181/demo “);

Testing the application

After going through all this let me tell you how to run the application.

  • First, start the server.
  • Once the server is up, access your webpage (client) using a web browser which supports WebSocket. DO NOT run the webpage locally, it MUST be hosted on a HTTP server.
  • Once the page has loaded, press the “Try to Connect” button. You will receive “Hello Client” from the server.
  • Now perform some actions that writes to your event log. I generally go to “services” and start/stop Sql Server service to generate events. You can view these events on the clients UI.
  • You can choose to Stop/Start subscribing to the server and it should work. Also try starting multiple client instances.

Multiple clients in action and snapshot of the server

What’s the future

In my personal opinion, WebSocket is going to be next big thing in web development. Its going to take time to mature. Once big players start creating development tools and frameworks for writing client and servers, WebSocket is definitely going to take-off. With things like HTML5 and WebSocket, the browser is, in my opinion, going to replace most applications you use. Hope this article was useful to you. Please share your feedback and criticism via comments. Also you may want to take part in the poll which I created on WebSocket, to share your opinion on this technology.

Quick and dirty network usage meter with C#

Download source code.

Refer to “ReadmeFirst.txt” for instruction on how to run.

I have always been doubtful of my billing by my internet providers. I wanted to write some code that could help me get a rough estimate of bandwidth I was using in every session. In this article, I will show you how to create a very basic network usage meter for serial port/USB/mobile phone modems with only C# (no Win API calls, sockets or fancy stuff).

The network meter's icon (one with yellow dot). Note that network icon status.

The icon's tooltip shows usage. Note that network icon status.

Some entries from the log file.The last entry corresponds to reported usage.

Clicking on 'Exit' menu item will close the program.

I have always been doubtful of my billing by my internet providers. I wanted to write some code that could help me get a rough estimate of bandwidth I was using in every session. In this article, I will show you how to create a very basic network usage meter for serial port/USB/mobile phone modems with only C# (no Win API calls, sockets or fancy stuff). My program is not as sophisticated as others available on the internet, but it does work well for me. It shows usage in current session and logs it in a file. This code should work with many USB modems which actually setup a COM port for communication (example GPRS/3G/HSIA data cards or mobile phones being used as modems).

The basics

The reason, I call this code ‘dirty’ is, it not well tested and was written in hurry. The program revolves around only two concepts:

My program has only been tested with HSIA modem, which gets connected to a virtual COM4 port. The program is written in such a way that it handles frequent connection/disconnection and tries to log usage in every session.

The Code

This is a winforms application. In the constructor of the Form we :

  • Create two performance counters, one for measuring downloads and another for measuring uploads.
  • A Timer to poll the performance counters, so that we can check if they are readable (network/port is available).
  • Attach event handler to ‘NetworkAvailabilityChanged’ event of ‘NetworkChange’ class, so that we are updated when the COM4 port is available.

The code is given below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
static PerformanceCounter dataSentCounter;
static PerformanceCounter dataReceivedCounter;
System.Timers.Timer networkMonitor;
string category, instance, fileName;
static float u, d;

public Form1()
{
InitializeComponent();
category = ConfigurationSettings.AppSettings["Category"];
instance = ConfigurationSettings.AppSettings["Instance"];
fileName = ConfigurationSettings.AppSettings["FilePath"];
dataSentCounter = new PerformanceCounter(category, "Bytes Transmitted", instance);
dataReceivedCounter = new PerformanceCounter(category, "Bytes Received", instance);
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
networkMonitor = new System.Timers.Timer();
networkMonitor.Interval = Int32.Parse(ConfigurationSettings.AppSettings["NetworkPollInterval"]);
networkMonitor.Elapsed += new ElapsedEventHandler(networkMonitor_Elapsed);
}

private void Form1_Load(object sender, EventArgs e)
{
try
{
u = dataSentCounter.NextValue();
d = dataReceivedCounter.NextValue();
}
catch
{ return; }
networkMonitor.Start();
}

In the above code, ‘category’ is set to “RAS Port” and ‘instance’ to “COM4”. The instance needs to be set to correct port number to which your modem is connected to. To get instance name of your COM port you can do something like this:

1
2
3
4
5
PerformanceCounterCategory c = new PerformanceCounterCategory("RAS Port");
//c.GetInstanceNames() gives list of all instance names.
//Typically there will not be many COM ports. Use guess work
// and some experimenting to get the correct name. Make sure that you
// are connected to internet using a COM port before executing this.

Another important value is “Interval” of the timer. It should be sufficiently high (ideally 1-3 seconds). If you keep it too low the code might now work, because it seems the ‘NetworkAvailabilityChanged’ event takes some time to fire once you are physcially disconnected from the network. (Another reason for calling this code ‘dirty’). Two important pieces are the ‘NetworkAvailabilityChanged’ event handler and code for ‘Elapsed’ event of the timer. When the timer’s ‘Elapsed’ event fires, I try to read from the performance counters. If there is an exception reading, or 0 bytes recorded in the read operation, we first log the prior readings to a file. This indicates that the COM4 port was removed or network connectivity was lost. Notice here that, I am NOT relying on ‘NetworkAvailabilityChanged’ change event to inform me of a connection drop. (Why ..I told you, this is a ‘dirty’ approach).Instead we only use the ‘NetworkAvailabilityChanged’ event to check if a new network is available. When network is available we simply start the timer again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void networkMonitor_Elapsed(object sender, ElapsedEventArgs e)
{
float temp_u=0, temp_d=0;
try
{ temp_u = dataSentCounter.NextValue();
temp_d = dataReceivedCounter.NextValue();

}
catch
{
LogUsage();
u = 0; d = 0;
networkMonitor.Stop();
return;
}

if (temp_u == 0f && temp_d == 0f)
{
LogUsage();
networkMonitor.Stop();
return;
}
u = temp_u; d = temp_d;
}
1
2
3
4
5
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{networkMonitor.Start();}
}

As you can see from the screen shot, I have added a notification icon to the Form. When user moves mouse pointer over this icon, it shows the usage. If the user right clicks, a popup menu comes up with “exit” item. On clicking this, our application closes. The code for this part is given below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void notifyIcon1_MouseMove(object sender, MouseEventArgs e)
{
notifyIcon1.Text = string.Format("{0}\nDn:{1} bytes, Ul:{2} bytes",instance,d,u);
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{ this.Close(); }


private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
LogUsage();
dataSentCounter.Close();
dataReceivedCounter.Close();
}

The code for function that performs loggin of the usage in a CSV file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void WriteUsageToFile()
{
if (!File.Exists(fileName))
File.Create(fileName);

string username = System.Environment.UserName;
string logEntry = string.Format("{0},{1},{2},{3}\n", d, u, username, DateTime.Now.ToLongTimeString());
File.AppendAllText(fileName, logEntry);
}

private void LogUsage()
{
try
{
if(u > 0f || d > 0f)
WriteUsageToFile();
u = 0; d = 0;
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
networkMonitor.Stop();
}

}

Finally!

Hope you found this article useful. Download and try running the code with your serial port/USB modems. Add a shortcut to your “StartUp” folder, so that the program starts automatically everytime the system boots. If the above code does not work ‘as is’ for you, try customizing it according to your needs. Next week, I will try to see if I can get this code working with wireless network and LAN. I will add my findings to this post. Please leave a comments to share your thoughts. Thank you for reading.

Using Extension Methods With Typed Datasets

DataTable is one of the most widely used classes in .NET framework. In data layers of a typical ADO.NET application one can see lot of code to work with DataTable and DataRow. In this article I discuss how to do some common tasks involving datasets in more fashionable manner, in LINQ style. This is not a tutorial on LINQ or extension methods or typed Datasets.

I am assuming that most of you already know lot more about them than I do (if not, don’t worry there are always late starters like me :-) ). So, the first question is why only ‘typed’ datasets ? why isn’t this article covering normal datasets. To answer this question, let use create a typed dataset using VS2008 I have created the following dataset, it has two tables:

In .NET 3.5 all tables of a typed dataset inherit TypedTableBase, which in turn implements IEnumerable. If you have been reading about .NET 3.5 stuff, you will realize that this is the interface that has many powerful extension methods defined for it. This enables us to use LINQ’s extension methods with our DataTable classes. If this doesn’t excite you, go thorough the code snippets below:

1. Filtering Rows

The traditional way:

1
DataRow  pr = p.Person.Select("Firstname ='a'");

With extension methods:

1
var prst = p.Person.Where(n => n.FirstName=="a").ToArray<Persons.PersonRow>();

2. Joining tables to get data

Suppose we want to get all PersonInfo rows for persons whose first name contains ‘a’. Now imagine writing C# code for that without use extension methods, and compare it with this:

1
2
3
4
var onlyinfo = p.Person.Where(n=>n.FirstName.Contains('a')).Join(p.PersonInfo,
n => n.PersonId,
m => m.PersonId,
(n, m) => m).ToArray<Persons.PersonInfoRow>();

3. Summing up a particular column

To get sum of all Ids (kinda of vague but just for example :-))

1
int sumofids = p.Person.Sum(n => n.PersonId);

4. Getting a set of continus rows

Get row no. 3, 4 and 5

1
var x= p.Person.Skip(2).Take(3);

5. Sorting by a particular field

Sorting by last name

1
var o = p.Person.OrderBy(n => n.LastName);

Sort by “LastName,FirstName”

1
var y = p.Person.OrderBy(n => n.LastName+","+n.FirstName).Reverse();

6. Join using LINQ syntax

Here we join two tables using LINQ syntax. What the query does is fetches custom resultset for all persons whose PersonId < 5

1
2
3
4
5
6
7
8
9
10
11
var tm = from l in p.Person
join q in p.PersonInfo
on l.PersonId equals q.PersonId
where l.PersonId < 5
select new { l.PersonId, q.PersonInfoId, l.FirstName, l.LastName };

var myarr = tm.ToArray();

Console.WriteLine("{0} {1} {2} {3}",
myarr[0].FirstName, myarr[0].LastName,
myarr[0].PersonId,myarr[0].PersonInfoId);

These were just some examples of what you can do with typed datasets .NET 3.5. In many cases, using extension methods will reduce the amount of code you write drastically.

Creating self updating animated charts with Fusion Charts and ASP.NET

See Live Demo | Download Source

In this article I will show you, how to create cool self-updating charts using Fusion Charts , ASP.NET and some AJAX. If you are getting impatient to see how they look, click here to see a demo. You should read this article if :

  • You want to integrated animated charts into your ASP.NET pages.
  • You are looking for free and feature rich charting tool.

About Fusion Charts

Fusion Charts is a flash based charting package that can be used with almost any server side programming language. The free version of their charts includes some 22 different types of charts which can be animated. The best part of the free version is,it comes with unbelievably liberal license agreement, which allows you to use them even in your commercial applications. You can read the license for free version here: http://www.fusioncharts.com/free/TermsOfUse.asp .

Downloading and Installing Fusion Charts

  • Download ‘Fusion Charts Free’ from this link. Before downloading please read the terms of use.
  • Download my source code and unzip to a folder, say C:\…\SelfUpdatingCharts\
  • Open the C:\…\SelfUpdatingCharts\ folder as a website in VS 2008 or VWD 2008.
  • Unzip the fusion charts zip file and copy contents of ‘Charts’ folder (all *.swf files) to C:\SelfUpdatingCharts\Charts folder.
  • Copy the FusionCharts.js file from C:\..\..\FusionChartsFree\JSClass folder to C:\SelfUpdatingCharts.

After performing the above steps your solution explorer would look like attached image.

Thats it! we are all set up. After this step you should be able to run the Charts.aspx file and see the charts in action. In the remaining part of article, I will discuss step by step how to include charts in a newly created page.

Creating a new *.aspx Page

Create a new *.aspx page. Add a script manager to it. Make sure that the ‘EnablePageMethods’ property is set to ‘true’.This is required, since we will be using WebMethods via AJAX to fetch data for our graph at regular interval.Now add a reference to the FusionCharts.js file in our new aspx page. Somewhere on the page create a DIV tag and assign it an id of “mychart”. We will use Fusion Chart’s javascript API to create and display a new bar chart inside this div.

Writing server side code

I am going to create a six data point bar chart. So we write a “WebMethod” in the code behind ,which returns an array of six numbers. The code is simple:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[WebMethod]
public static string GetDataForBarChart()
{
if (IsDataChanged(20) || HttpContext.Current.Session["StartedBC"] ==null)
{
StringBuilder sb = new StringBuilder();
Random r = new Random();
sb.Append(r.Next(2000)); sb.Append(",");
sb.Append(r.Next(2000)); sb.Append(",");
sb.Append(r.Next(2000)); sb.Append(",");
sb.Append(r.Next(2000)); sb.Append(",");
sb.Append(r.Next(2000)); sb.Append(",");
sb.Append(r.Next(2000));
HttpContext.Current.Session["StartedBC"] = 1;
return sb.ToString();
}
else
{ return "NULL"; }

}
private static bool IsDataChanged(int someid)
{
Random r = new Random();
int i = r.Next(10);
return (i % 9 == 0)?true:false;
}

The code is pretty straightforward, except for the ‘IsDataChanged’ and ‘Session’ part. The first one is a function that in real world scenario would hit database and check if there are any changes. If no changes were recorded after last request, it would return “NULL” instead of returning data. In this way I have tried to preserve bandwidth and prevent the charts from updating unnecessarily. The code involving session object makes sure that data is always transmitted for the very first time. There can be various ways of achieving this, this is my method.

Writing the javascript

The javascript for chart can be divided into three parts. The first one creates the chart object, second one does AJAX to get new data and last one generates XML required for binding to the data returned by server. One thing I want to tell here is, you can directly return XML from the server, instead of CSV. I used CSV, because I felt it was lighter and XML generation could be handled at the client end using javascript. Given below is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<script  type="text/javascript"  src="FusionCharts.js"></script>
<script type="text/javascript">
function init()
{
var chart1 = new FusionCharts("Charts/FCF_Column3D.swf", "chart1Id", "500", "400");
chart1.setDataXML("<graph></graph>");
chart1.render("mychart");
PageMethods.GetDataForBarChart(OnCompleteBarChart,null);
}

function OnCompleteBarChart(a)
{ if(a != "NULL")
updateChartXML("chart1Id",GenerateXMLForBarChart(a));
window.setTimeout("PageMethods.GetDataForBarChart(OnCompleteBarChart,null)",10500);
}

function GenerateXMLForBarChart(x)
{
var arr = x.split(",");
if(arr.length==6)
{
var xml= "<graph caption='Page Visits Summary' subcaption='For the year 2009' xAxisName='Month' yAxisName='Page Visits' yAxisMaxValue='2100' >";
xml+="<set name='Jan' value='"+arr[0]+"' color='AFD8F8' />";
xml+="<set name='Feb' value='"+arr[1]+"' color='F6BD0F' />";
xml+="<set name='Mar' value='"+arr[2]+"' color='8BBA00' />";
xml+="<set name='Apr' value='"+arr[3]+"' color='FF8E46' />";
xml+="<set name='May' value='"+arr[4]+"' color='008E8E' />";
xml+="<set name='Jun' value='"+arr[5]+"' color='D64646' />";
xml+="</graph>";
return xml;
}

}
</script>

The first function, ‘init’ is called on the ‘onload’ event of body. It creates a new ‘Chart’ object by specifying the path of swf file ,id of the chart and its dimension. The ‘FCF_Column3D.swf’ file creates a 3D bar chart for us. Immediately after creating the chart we assign it empty XML and make an AJAX request using PageMethods object. When the response of our request arrives, ‘OnCompleteBarChart’ gets called, which in turn calls ‘GenerateXMLForBarChart’ and updates the bar chart display. One important thing to note here is that the format of XML varies depending upon the chart type. You can have a good idea of the XML for various chart types by checking examples provided with Fusion Charts. The ‘GenerateXMLForBarChart’ method takes a CSV string returned by server and transforms it into XML required for the graph.

Thats all!

Now run the page, you should be able to see the chart. In my code, I have specified a timeout of 10500 ms between two AJAX calls for updating the chart. This should be sufficiently high, other wise the chart would refresh before. Thanks for reading. Hope you found it useful. For suggestions,questions or criticism , please drop a comment.

Self updating animated charts with Fusion Charts and ASP.NET Demo

Go back to the article.

Javascript Based Demo

This is a javascript based demo of the sample application.

This demo uses Fusion Charts Free available under following licensing terms: http://www.fusioncharts.com/free/TermsOfUse.asp init();

Using Client-Side Custom Events in ASP.NET Applications

Download Code

These days many average developers like me find themselves breaking their heads to implement ‘desktop like’ behaviors for web applications. Many ASP.NET controls (like Button and ModalPopupExtender) have public properties for attaching javascript handlers to client side events. Now a common problem is,

"you want to notify multiple controls about an client side event."

For example:

  • When value inside some control of a grid changes , sum and average needs to be calculated and displayed.
  • You may want to perform validation and few calculation on ‘click’ event of an ASP.NET ‘button’ control.

In more complex scenarios, it might be required to be able to dynamically add and remove handlers, in addition to things mentioned above. I have seen developers do lot of ugly ‘wiring’ of javascript functions to achieve this. Of course it works , but it is a nightmare to maintain. In this article we will see how to make use of ‘client-side custom events to simplify coding for such scenarios.

What are ‘Client-Side Custom events’ ?

DOM elements have some standard events defined, like ‘click, onmouseover, onblur..etc’ . But what if we wanted to define new event that didn’t exist and use them (just like we do in C# ). The answer to this is ‘custom events’. There are many javascript libraries which make it possible to create and use custom events. In this article I will use jQuery, since it is believed to be supported in next version of Visual Studio. Custom events are similar to once we use in C# or VB.NET coding. We basically think of an event name, attach one or more handlers to this event and raise the event whenever required.

Sample Scenario

I have taken up a very simple scenario, where I will show how use of custom events make things pretty as opposed to tradition methods. I have a grid like display , where each row performs a specific operation on value input by the user using a AJAX modal popup. Attached below is the screen shot. When the user brings up the modal dialog box , enters value and clicks ‘OK’ following things happen:

  • Input is validated.
  • In first row results of the operation : value * 2 is displayed.
  • In first row results of the operation : value + 2 is displayed.
  • In first row results of the operation : value / 2 is displayed.

Screenshot of the sample application.

Doesn’t look like a big deal ! So why use custom events, when it is lot easier to write a single function to do all this, and hook it up to ‘OnOkScript’ property of the ModalPopupExtender. We could do that , but what if , we had 20 such operation ? wont a single function be too long and complex ? And what if we wanted the ability to add/remove handlers dynamically? In the above screen , I have placed checkboxes to facilitate dynamic attaching /detaching of handlers.

Using Custom Events

For the above scenario, I thought of an custom event named ‘okbuttonpressed’ . To the ‘OnOkScript’ property of the modalpopupextender, we assign the ‘GetNumber()’ javascript function. Given below is the code:

1
2
3
<ajaxToolkit:ModalPopupExtender PopupControlID="Panel1" ID="ModalPopupExtender1" runat="server" 
TargetControlID="Button1" CancelControlID="btnCancel" OkControlID="btnOK"
BackgroundCssClass="modalBackground" OnOkScript="GetNumber();" >
1
2
3
4
5
6
7
8
9
function GetNumber()
{
var i = $("#txtVal")[0].value;
var val = parseInt(i);
if( val != i)
{alert("Please enter a valid integer.");$("#txtVal")[0].value=0;}
else
{ jQuery(document).trigger('okbuttonpressed', val);}
}

Here , ‘txtVal’ is id of a texbox inside the modal popup where user enters a value. As a best practice, I should have tried to fetch ‘ClientId’ (since its a severside control) and use it, but since we are not dealing with repeaters and usercontrols , I am using the id directly (also because I am bit lazy). So when ‘OK’ button is clicked , the above function gets called and the ‘okbuttonpressed’ custom event gets triggered.

Attaching handlers to custom events

On check/uncheck of a checkbox in any row, I have written code to attach /detach a handler for the custom event ‘okbuttonpressed’ . For example, when ‘chkAdd’ is selected, we attach a handler ‘AddVals’ . Here is complete code:

1
2
3
hkAdd.Attributes.Add("onclick", "AddChkChanged(this)");
chkMul.Attributes.Add("onclick", "MulChkChanged(this)");
chkDivide.Attributes.Add("onclick", "DivChkChanged(this)");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  function DivChkChanged(x)
{
if(x.checked)
jQuery(document).bind('okbuttonpressed', DivVals);
else
jQuery(document).unbind('okbuttonpressed', DivVals);
}

function MulChkChanged(x)
{
if(x.checked)
jQuery(document).bind('okbuttonpressed', MulVals);
else
jQuery(document).unbind('okbuttonpressed', MulVals);
}

function AddChkChanged(x)
{
if(x.checked)
jQuery(document).bind('okbuttonpressed', AddVals);
else
jQuery(document).unbind('okbuttonpressed', AddVals);
}

Thats all ! Now if you run the page, you can see for yourself how the custom events work. Be sure to check any of the checkboxes, before brining up the modal popup to see calculated result. Thats all from me. Though this was a very simple example, the attempt was to illustrate how using ‘custom events’ can help in clean coding. Without them our javascript would have been inelegant and full of ‘if’ statements and global variables. Custom events are much more useful when dealing with more complex scenarios. They pave the way for better event driven programming in javascript.

Introduction To Web Development Using Javascript Templates

Screenshot of the application.

Download Files | View Live Demo

Javascript templates is upcoming technology for creating dynamic UI in web applications. The core of this technique is a javascript engine, that can generate HTML using a predefined template. In this article, we will see how to use open source TrimPath engine from Google Code website to create a basic application. It fetches images from Flickr’s public feed which match tags specified by the user, and displays their thumbnails along with other information.

What is a ‘javascript template’ ?

‘Javascript templates’ is one of the upcoming technology for use in Web 2.0. It relies on client side javascript, to generate, whole or part of a web page. This way, there is decoupling between data and the view (UI).Developing using javascript templates is very similar to designing reports. In classic web application, we rely on server side code to generate and send back the HTML. Using javascript templates, the server is relieved of this work. We will discuss the pros and cons of this technique in a bit detail, later in this article. I have created a simple diagram to illustrate what goes on in this type of applications.

How Javascript Templates work

About Flickr’s Public Feed

Before we start our application, let me tell you about Flickr’s public feed. Basically its an URL, which, when accessed, gives back list of images. The URL contains ‘tags’ for which we want so get images in the query string. It is possible to specify multiple tags separated by commas. This feed can be forced to return data in JSON format by specifying ‘format’ in the query string.

The feed URL with tags and output format specified as JSON:

1
http://api.flickr.com/services/feeds/photos\_public.gne?tags=mumbai&format=json 

The feed URL: The URL fetches results for tag ‘Mumbai’ and tells the service to give results in JSON format.

More information on using the feed can be found here: http://www.flickr.com/services/feeds/docs/photos_public/.

If you paste this URL in Firefox, you should see something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
jsonFlickrFeed({
"title": "Recent Uploads tagged mumbai",
"link": "http://www.flickr.com/photos/tags/mumbai/",
"description": "",
"modified": "2009-01-07T16:24:05Z",
"generator": "http://www.flickr.com/",
"items": \[
{
"title": "ABC",
"link":"http://www.flickr.com/....
"media":{"m":"http://farm4.static.flickr.com....
....
}\]})

As you must have realized,this is basically a call to Javascript function. The page which requested this data, is required to have a function with same name. This method of passing JSON data is called JSONP. We see this in more detail very soon.

Building basic ‘Search’ UI

1
2
3
4
5
6
7
<body>
<p>Tags:
<input id="txtTags" type="text" /><input id="btnSearch" type="button"
value="Search" onclick="return btnSearch\_onclick()" /><br /></p><hr />

<!--DIV serves as container to script tags !-->
<div id="srcDiv"></div>

Writing Javascript for our application

Our javascript is short and sweet. Every time the user enters some ‘tags’ and clicks ‘Search’ the ‘btnSearch_onclick’ function gets called and following things happen:

  • A new URL pointing to Flickr’s feed is constructed, which contains tags entered by the user.
  • A new script tag is created with the above URL as the value of ‘src’ attribute.
  • This script tag is dynamically inserted inside a placeholder, which triggers an AJAX request.

If you remember, ‘jsonFlickrFeed’ is name of callback function used by our feed. I have created a function with same name in javascript. This gets invoked automatically when , the AJAX call receives a response. The function contains only two lines of code which bind the data to our HTML template. In my page I have placeholder DIV with id ‘showphoto ‘, to display content.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script src="trimpath-template-1.0.38.js" type="text/javascript"></script>
<script type="text/javascript">
var myphotos;
function btnSearch\_onclick()
{
var tags = document.getElementById("txtTags").value;
var flickrURL = "http://api.flickr.com/services/feeds/photos\_public.gne?tags="+tags+"&format=json";
var container = document.getElementById("srcDiv");
var el = document.createElement("script");
el.setAttribute("src",flickrURL);
container.appendChild(el);
}

function jsonFlickrFeed(data)
{
var result = TrimPath.processDOMTemplate("photos", data);
document.getElementById("showphoto").innerHTML = result;
}
</script>

Creating a javascript template

The ‘trimpath-template engine’ (wired name..isnt it !) is a single javascript file. To use it we need to define a template inside our HTML page. Documentation of the template engine suggests that we use a hidden ‘textarea’ to host our template. Let us have a look at our template :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!--template code starts -->
<textarea id="photos" style="display:none">
<h1>${title}</h1>

{for i in items}
<span class="imgitem">

<div class="imgdiv">
<a href="${i.link}" >
<img src="${i.media.m}" style="border:0px" />
</a></div><br />
<span>
<span class="content"><strong>title:</strong>${i.title}</span><br />
<span class="content"><strong>author:</strong>${i.author}</span><br />
</span>
</span>

{/for}
</textarea>
<!--template code ends -->

<!--Container for HTML generated after binding to the template-->
<div id="showphoto" style="font-family:Calibri"></div>

For now, let us assume that we have a javascript object, which has been created from JSON returned by Flickr’s feed. Visit the feed URL (preferably in FireFox) and you should be able to see the ‘title’ and ‘items’ field. Inside each item there are more fields like ‘author’,’title’,’media’,’link’ etc. In the above template, text enclosed between curly braces ‘ { }’ are javascript statements. Those preceded by a ‘$’ sign, are expressions returning value. This is the convention followed by our template engine. The ‘${i.media.m}’ , points to URL of a thumbnail of an original image. By looking at the template it is clear, that we want to display a thumbnail, followed by title and name of the author of an image. I have used some CSS to make each item of same size (since sizes of thumbnails vary). Thats all to this application. With very few lines of javascript and HTML, we created a fairly useful application.

The Future

Javascript templates methodology is by no means going to completely substitute server side HTML generation. It has its own strengths and weaknesses. The major strengths are:

  • Separates UI from data.
  • Very easy to work with. Only knowledge of javascript and HTML required.
  • Since UI is generated at client, this eases load on server the a bit.
  • By combining this method with some powerful javascript libraries and things like REST, cool application can be created.

Now the drawbacks:

  • Requires javascript. Could be a problem for portable devices.
  • Designing AJAX based application is more painful than convention webapps.
  • Can’t bookmark !
  • Not search engine friendly.
  • Try pressing the ‘Back’ button on your browser ;-)

Hope you enjoyed this article. Please drop me a comment for any suggestions and criticism.