C# DispatchTimer

I was trying to port an old app from c# 2.0 to WPF in 4.0. In one place I was using a Timer to handle filtering of a list from a text box. This kept the list from constantly being updated while the user is typing because it was getting data from the database. I set a 250 millisecond interval so whenever they paused it would update the list.

The Timer class apparently got completely redefined in .Net 4.0. It used to have a Tick event, but this was changed to Ellapsed. Also I found out that it didn't work very well with the UI thread. When I tried to access the text field in the UI I would get a concurrency exception.

Finally I found a new class called DispatchTimer under the System.Windows.Threading namespace that does exactly what the old Timer class used to do. It allows you to do timer events that interact with the UI.

Getting Query Parameters in Javascript

I find myself needing to get query parameters that are passed into a web app on the URL quite often. At first I wrote a function that creates an associative array (aka object) with all of the parameters as keys and returns it. But then I was looking at the revealing module pattern, a nice javascript design pattern designed to hide private functions, and came up with a way to do this without even calling a function.

What I came up with was this nice little object that automatically initializes itself into the same associative array that the function call did previously.

// Creates associative array (object) of query params
var QueryParameters = (function()
{
    var result = {};

    if (window.location.search)
    {
        // split up the query string and store in an associative array
        var params = window.location.search.slice(1).split("&");
        for (var i = 0; i < params.length; i++)
        {
            var tmp = params[i].split("=");
            result[tmp[0]] = unescape(tmp[1]);
        }
    }

    return result;
}());

Now all you have to do to get the query parameters is just reference them from the QueryParameters object. There is no need to create a new object or call any function to initialize it.

var debug = (QueryParameters.debug === "true");

or

if (QueryParameters["debug"]) doSomeDebugging();

or loop through all of the parameters.

for (var param in QueryParameters) var value = QueryParameters[param];

Hope you find this object useful.

HTML5 localStorage and JSON

I've been working on an HTML5 application called Virtual Hamronograph. Since JavaScript can't save to the local file system I use localStorage to allow users to save harmonographs. I find this to be a good alternative. If you don't know, localStorage is a new global object in HTML5 that allows you to save up to 5MB of data in the browser. You save values by calling localStorage.setItem(key, value). You get values by calling localStorage.getItem(key). You can remove items by calling localStorage.removeItem(key). To get a list of all keys you can iterate over the localStorage object, just like you would any other object. Unfortunately localStorage only stores strings (not objects).

That's where JSON comes in. JSON is also a new global object in HTML5. It is used to convert JavaScript objects to and from JSON strings. You convert an object to a string by calling JSON.stringify(object). You convert a json string to an object by calling JSON.parse(json). Now you have a way to get objects in and out of local storage.

One thing to note is that the same localStorage is shared by all apps in the same domain (scheme + host + port). So if you have multiple web apps on your web site you could have the chance of overwriting some other apps data if it has the same key. To guard against that I prepend all of my keys with the apps name. So for example in my harmonograph app I prepend all keys with "Harmonograph.".

You can look at what is in localStorage in your browser's development tools. For instance, in Chrome if look under the Resources page there is a Local Storage item in the tree. Expand that and you can see all of the items in local storage for your site.

Happy coding!

Path.Combine

Here's a little used gem in .Net. In the Path class there is a Combine method. What this method does is to properly combine two parts of a file path. For example, you may have a path that you want to write a file to and a name of the file to write. I've seen a lot of code where in this case most programmers just string concat the path and file name. This doesn't always work right if you don't think about it.

That's where Path.Combine comes in. You don't have to think about the details of combining a file to a path. It does it properly for you. I ran into some code the other day where it was concatenating a path to a temporary directory with a file name to create a temporary file. The problem was that when called from one place it was tacking a backslash onto the end of the path. And from another place it wasn't. So in the second case the last part of the path was becoming part of the filename. This caused the temp file to be placed in the wrong directory.

path = "c:\somefolder\temp";

filename = "tempfile.txt";

filepath = path + filename;

Then filename ends up being: "c:\somefolder\temptempfile.txt".

If they would have used Path.Combine instead it would have created the proper path in either case: "c:\somefolder\temp\tempfile.txt". There's no need to worry about adding a slash at the end of the path or not.

Javascript Application Basics

Now that I've got a few javascript applications under my belt, I'm strating to see a pattern emerge. A javascript app for me always starts with three files. An html, a css, and of course a js file. This is the triangle that makes the base for your application to build upon. The fourth piece that I always include is a reference to jQuery. I wouldn't even try to write a javascript app without it. It's the defacto framework that makes javascript programming tolerable and should be included in any project IMHO.

The first thing I put in my js file is an object to represent my application. Since there's just one instance of the app I just define an object literal, there's no need for a constructor. But I do give it an init() method as the place to get things started.

MyApp={
  init: function() { // do something... }
};

Then of course I add the jQuery document ready handler that calls the object's init() method. The document ready handler is the entry point into the app and is equivalent to the main() function in a lot of other programming languages.


$(document).ready(function() {
  MyApp.init();
});

A javascript application's domain is the html DOM. Use jQuery to manipulate the DOM to make your application do what you want it to do. You can read user input, hide and show elements, and all of the other things that applications usually do. Heck, you can even make games if you want to. I've done it. And with the new additions provided in HTML5 you are going to get even more powerful features like canvas, local storage, etc.

Yes, javascript is a real programming language, and you can write real applications with it. Now go out there and write your own and show us what you got.

Performant Conditional Statements

I was looking through some code today and came across something like this.

if (checkSomeValueInTheDatabase() && someValue == someOtherValue) // Do something...

Now this is a completely legitimate conditional statement. But it's not very performant. You should always use boolean short circuits to your advantage when writing conditional statements. Start with the conditions that are the easiest to evaluate then work your way down to the ones that use a lot of resources, like hitting the database.

The example above I would change around like this.

if (someValue == someOtherValue && checkSomeValueInTheDatabase()) // Do something...

It gives you the exact same result as the first one but it doesn't go out to the database unless the first condition that checks if 2 variables have the same value is true.

I see this a lot when looking through code. So it seems to be a pretty usual problem. That's why I'm writing about it. So the next time you write a conditional statement with many parts to it take a moment to make sure it is optimized to save resources and run faster.

JavaScript Inheritance

I've spent the last few weeks trying to comprehend OOP and inheritance in JavaScript. After that amount of time I've come to the conclusion that harly anyone really understands it and everyone implements it a different way. Just look at this question someone posted about the best library to use for JS inheritance. I thought it was funny because although there were a lot of answers, I think everyone proved his point, that there are many of them and no one could agree on the best.

stackoverflow.com/questions/711209/which-javascript-library-has-the-most-comprehensive-class-inheritance-support

Being simple minded and wanting to find the simplest way to do some class inheritance I read a number of books and blogs. Every one I read made me more confused. It can't be that hard, I thought. But JS is a strange beast, and prototypal inheritance doesn't translate very well for someone used to classical class inheritance.

I think the main problem is there are too many different ways to define objects in JS. In other languages such as C# or Java there's pretty much one way to do it, and it's simple to understand. You create a class, then you create a child class that extends it and adds to or overrides the parent's behavior.

I could have just used the first way I found and forgot about it and kept programming. But not me. I kept thinking there has to be a better way to do it. There has to be an industry standard. Right? Not! So finally I just kind of combined the best parts of all the solutions I could find and came up with something that worked and looked good. Most of the ideas I got came from Gavin Kistner's site, which does a good job of explaining JS inheritance without creating a bunch of helper functions first.

phrogz.net/js/classes/OOPinJS2.html

The only difference from Gavin's example is that I define all of my child class functions inside of the object definition instead of using the prototype. I don't know if there is some reason not to do it that way but it worked for me.

Shape = {
   name: undefined,
   init: function(name) { this.name = name; }
   getName: function() { return name; }
}
function Circle(radius) {
    this.init("circle");
    this.radius = radius;

    this.getArea = function(){ return Math.PI * this.radius * this.radius; }
}
Circle.inheritsFrom(Shape);

var myCircle = new Circle(4);
myCircle.getArea(); // 50.265
myCircle.getName(); // circle

I define an init function in the base class so I don't have to worry about calling the base class's constructor. That solves problem #1. In my child class, Circle I call the init function and then do any other child initialization like setting the radius. Then I define all of my child class behaviors, in this case getArea(). Finally, outside of the child class definition I call the inheritsFrom function to link it to the parent. The inheritsFrom is defined at the page linked above. It simply sets the prototype to the parent object and sets the constructor.

Tha was the simplest thing I could come up with. I hope it saves someone else from days research.

ASP.NET Session Keep Alive

I was recently tasked with coming up with a way to keep the session alive in ASP.NET as long as the user had the web page open. That way if they started filling out a form, then went to lunch and came back, they wouldn't lose all of the information just because their session timed out.

The concept is actually pretty simple. You just need to make a call back to the server every once in a while before the session expires to update the session timeout. We figured as long as the user has the browser open on one of our pages they are still working on our site and want their session renewed. Once they leave our site the session can go ahead and expire normally. This would also allow us to reduce the session timeout so we could reclaim session resources on a more frequesnt basis for users that hit the site for a moment then leave.

The primary way I found to accomplish this by asking at the almighty Google was to have a blank image on the page and use javascript to update the image source so that the server is pinged and the session updated. But with ajax why bother? I figured I could do it a lot easier with a simple ajax call that didn't require any image on the page.

What I did was to create an empty aspx that didn't have anything in it, just the default html that Visual Studio generates. Then I created a javascript file that simply uses jquery to do an ajax get request to the empty page. The code is below.

SessionKeepAlive =
{
    delay: 10000,
    url: undefined,
    run: function()
    {
        if (this.url)
        {
            $.get(this.url + "?d=" + escape(new Date().getTime()));
            setTimeout("SessionKeepAlive.run()", this.delay);
        }
    },
    start: function(delay, url)
    {
        // Set ajax timeout to 2 seconds
        $.ajaxSetup({ timeout: 2000 });
       
        // Convert delay to millis
        this.delay = parseInt(delay) * 60000;
        this.url = url;
        setTimeout("SessionKeepAlive.run()", this.delay);
    }
};

You start the keep alive process by calling SessionKeepAlive.start() passing the number of minutes to wait and the url of the page to call. It uses setTimeout() to wait the specified amount of time before calling run(). In run() it does the get request and calls setTimeout() again so it keeps repeating until the user leaves the page. Note that I had to add a parameter to the url to get it to work right in IE. Without adding a unique parameter value to the url, IE was just using the cached results instead of going back to the server. I used the Date.getTime() function to get a unique parameter value.

Since all of my pages extend the same base class I was able to programatically add a link to the javascript file and also register a startup script to call the start() function in page_init.

ClientScript.RegisterClientScriptInclude("keepSessionAlive", "keepSessionAlive.js");
ClientScript.RegisterStartupScript(GetType(), "SessionKeepAlive", "SessionKeepAlive.start(10, 'ping.aspx');", true);

You could also do this in a master page, but I have a number of different master pages and only one page base class, so it was easier to put it in the base class.

Wirth's Law and the AntiVirus

I've been experiencing Wirth's law firsthand lately. Wirth's law basically states that "Software is getting slower more rapidly than hardware becomes faster". This is no place more apparent than the antivirus programs we are all forced to run on our computers these days. I have a pretty good development machine with dual core processors and lots of memory. Yet I constantly find my machine bogged down taking way too long to do things. Especially in Visual Studio. It gets very frustrating when you're trying to get some work done. <whisper>Don't tell anyone, but sometimes I turn off my antivirus so I can get my work done on time.</whisper>

So have the terrorists really won? Here we are using half of our computing power to protect our computers against attacks from a bunch of shortsighted jackasses who think it's funny to write viruses. Like most terrorists they don't realize that they are also hurting themselves. Unless the people who write viruses don't protect their own machine from other people's viruses.

It reminds me of the old addage from Benjamin Frankin. "They who can give up essential liberty to obtain a little temporary safety, deserve neither liberty nor safety". Replace liberty with productivity. Do we really need to much computing power reserved for protecting ourselves from viruses? Should Visual Studio be optimized so that it doesn't use so many system resources? Probably a little of both. But no one seems to care about optimizing their code any more. It's all about pushing out new features, not making things run faster.

 It's OK though

ExplorerCanvas and JQuery

I am working on a Javascript app (CloudGraph) that uses HTML5 canvas and JQuery. I'm using ExplorerCanvas to support canvas in IE. I recently came across an interesting problem.

What I was trying to do is restore the user's settings when the page is loaded by reading some information from a cookie that I set the last time the user accessed the application. One of these settings is the size of the canvas. I decided that the best place to do this would be when the document is ready using JQuery $(document).ready().

This worked fine in browsers that natively support the canvas element. But in IE it kept getting errors the first time I would hit the page. It seemed that the excanvas element wasn't initialized yet because I was getting null reference and unknown properties errors. If I refreshed the page the errors went away but the resized canvas wasn't drawing on the entire area of the canvas. It was like the clipping rectangle was still set to the default canvas size.

I found that the canvas element when using excanvas has a div child element which is where the actual drawing takes place. When I changed the width and height of the canvas element in document.ready it didn't change the width and height of the child div. Initially my solution was to also change the div element when changing the canvas element and that worked.

But then I realized that having to refresh the page every time I started the app in IE really sucked. That wouldn't be acceptable for users. Since it seemed like the canvas wasn't getting initialized before I was trying to use it I decided to try to initialize my app at a different time. I figured the next best place was in the onload event. Sure enough, moving my initialization to onload fixed all of the problems.

So, it looks like the canvas shouldn't be manipulated until the onload event when using ExplorerCanvas. There might be ways to do it when the document is ready; I found some posts on initializing excanvas manually. But for me waiting until onload worked just fine.