0

What Is a Race Condition?

Posted in .Net, Asp.Net, Javascript at October 6th, 2009 by Drew / No Comments »

Just thought I would put a post out on something I learnt today that can occur when using ajax- a race condition. A race condition is is where the output or result of something is dependent on the timing of other events/code. A good example of this is below:

function ValidateInput() {
//some slow running code here...
}

function SaveForm() {
//save the form
}

<form>
<input type="text" onchange="ValidateInput()" />
<input type="button" onclick="SaveForm();" value="Submit" />
</form>

The problem here can occur when the user hits the Submit button before the validation method can finish. One way to overcome this is use a semaphore to indicate whether the form still needs validating on the SaveForm method.

0

Javascript – a quick reminder

Posted in Development, Javascript at February 20th, 2008 by Ben / No Comments »

My latest contract has seen my development time focus strongly on Sql Server, Xml and C# server side code.

However, lately I’ve been playing around with all the new Asp.Net 3.5 extensions (MVC) and Linq with VS 2008 and found that I could use a refresher course in all things Javascript – particularly Ajax and JSON.

I found this awesome guide which gives you a quick reminder of the useful techniques required to author some top notch client side code when building web apps.

0

ibox, Prototype, and JSON

Posted in Asp.Net, C#, Javascript at August 2nd, 2007 by Gerrod / No Comments »

In my current project, I’m doing some fancy-pants stuff to lookup UK addresses via a web service, then send them to the client using JSON. On the client end, I’m displaying the results in an ibox and then sending the results back to the main form. Woah!

The first challenge was getting the ibox to open and display the form correctly. I chose to use a hidden div as my “form”, and let the ibox display it on the screen when appropriate. It all seemed to work correctly, however when I tried to read the values out of the fields on the ibox form, it kept telling me they were empty!

After a lot of mucking around, cursing, and rude gestures directed at the computer – you know, the standard debugging drill – I worked out that when you use a hidden div as your ibox, it actually *clones* the entire InnerHTML of the hidden div! So in effect, you get *two* of every field with duplicate IDs. And, since the HTML generated by ibox goes at the *end* of your document, when you call document.getElementById, you get back the *first matching element*, which will always be the one that’s still safely hidden away in your form. Handy – not!!

But never fear, the solution is actually quite simple. You just have to create an external file containing your ibox form, and then use that as the HREF in your link:


<a href="FindAddress.aspx" rel="ibox&height=400" title="Find an address">Find address</a>

Ahh, finally things started working properly! So now that I could read the postcode that the user entered, I wanted to hit a handler to…. err… “handle” the web service request. To do that, I used prototype.js – a javascript library with a whole bunch of wicked cool functionality (all of which is way beyond the scope of this article). Check it out -to execute a cross browser friendly AJAX request, you simply do this:


  var url = "Handlers/FindAddressHandler.ashx?Id=" + id;
  new Ajax.Request(url, {
    onSuccess: OnAddressFound,
    onFailure: OnError
  });

Of course, you can inline the callback functions, but I wanted to separate them for readability. Anyway, the next part was setting up the FindAddressHandler. I won’t go into too much detail here as it’s just a standard implementation of IHttpHandler which then hits a web service. The part I want to talk about though is writing back the address object using JSON. A dude named Jason Newton King has written a brilliant library called Json.NET which makes life a hell of a lot easier!

Basically, you just have to create a JsonWriter, then serialise the properties of your object that you want to send back to the client. So in my case with an Address object (stored in local variable “address”):


StringBuilder builder = new StringBuilder();
using (JsonWriter writer = new JsonWriter(new StringWriter(builder))) {
  writer.WriteStartObject();
  writer.WritePropertyName("PostCode");
  writer.WriteValue(address.Postcode);
  writer.WritePropertyName("Address1");
  writer.WriteValue(address.Line1);
  writer.WritePropertyName("Address2");
  writer.WriteValue(address.Line2);
  writer.WritePropertyName("Address3");
  writer.WriteValue(address.Line3);
  writer.WritePropertyName("PostalTown");
  writer.WriteValue(address.PostTown);
  writer.WriteEndObject();

  writer.Flush();
}

_context.Response.AddHeader("X-JSON", builder.ToString());

Easy, right? So the thing to note here, besides how simple it is to persist your object in JSON, is that I’m sending back the JSON string in a response header called “X-JSON”. Now back on the client side again – one of the bonus features of Prototype is that it automatically interprets whatever is in the “X-JSON” header, and builds your objects for you! So, here’s the code I wrote for my client-side callback:


function OnAddressFound(transport, address) {
    $("txtAddress1").value = address.Address1;
    $("txtAddress2").value = address.Address2;
    $("txtAddress3").value = address.Address3;
    $("txtPostCode").value = address.PostCode;
    $("txtPostalTown").value = address.PostalTown;

    hideIbox();
}

The first argument – transport – is the XmlHttpRequest object which was used. (You can find a great document which outlines the properties of the XmlHttpRequest object on the Apple Developer Connection website). The second argument is the object which Prototype interpreted from the X-JSON response header. You can see also that prototype implements a function – $ – which is effectively a suped-up version of document.getElementById.

Using all of these technologies together was surprisingly easy! I’m super impressed with how you can grab so many rich frameworks to enhance your websites, all for free!

Boy, what a day!

I was working on the weirdest bug with a colleague today where we were receiving a javascript “Object expected” error when we migrated a page into our new ASP .Net Master Page format.

We thought we hadn’t made any breaking changes, all we had done was move the <script> tags into the MasterPage file from the content page.

That didn’t work, so we created a header content place holder in the master page <head> element and in the content page put back the <script> includes. That didn’t work either.

We then included the <script> tags in both the master and content page. That seemed to work. Very odd.

In the end after many attempts to figure out what was going wrong, we found the problem was with how MSIE parses <script> tags, it cannot use self closing tags or an empty element – ie. <script … />.

It has to have the <script></script> tag.

For more info check out quirksmode.org.

1

Javascript – Inheritance

Posted in Development, Javascript at December 5th, 2006 by Ben / 1 Comment »

There are many ways to perform inheritance using objects in javascript. I recommend reading chapter 3 and 4 from Professional Javascript for Web Developers” to get a full understanding of how the language can be utilized for inheritance.

Below I have listed a hybrid method that incorporates using the call() method and prototype chaining to simulate inheritance that matches closely to how you would use it in a typed language like Java or C#.



function File(name, path) {
	this.name = name;
	this.path = path;
}

File.prototype.getName = function() { return this.name; }
File.prototype.setName = function(name) { this.name = name; }

File.prototype.getPath = function() { return this.path; }
File.prototype.setPath = function(path) { this.path = path; }


Using the prototype keyword, means that the method is assigned to the File class. Without it, the function would be a new instance for every instantiated File object.

The following subclass utilizes the call() method which in this case is analogous to the super keyword in java or the base keyword in C#.

It then uses prototype chaining to assign/copy all the prototype functions of File to itself, before defining further functions that relate specifically to itself.


function ExcelFile(name, path, numberOfWorksheets) {
	File.call(this, name, path); // equivalent to calling base(name, path)
        this.numberOfWorksheets = numberOfWorksheets;
}

// this is how you inherit all the prototype values of the base class.
// ensure to place this before defining new functions as this will blat out
// all prototype functions currently declared for the class.
ExcelFile.prototype = new File(); 

ExcelFile.prototype.getNumberOfWorksheets =
	function() { return this.numberOfWorksheets; }

ExcelFile.prototype.setNumberOfWorksheets =
	function(numberOfWorksheets) { this.numberOfWorksheets =
							numberOfWorksheets; }


The following shows how you would instantiate your classes and prove that the inheritance worked.


var file = new File("RecipeDetails.txt", "c:/temp");
var excelFile = new ExcelFile("Business.xls", "c:/temp", 6);

alert(excelFile instanceof File);
alert(excelFile instanceof ExcelFile);
1

function $

Posted in Asp.Net, Javascript at November 16th, 2006 by Gerrod / 1 Comment »

A while back, Bender sent me a link to a prototype.js file that pretty much claimed to be a web developers best friend. It certainly has some interesting features, and one that I really liked was the “$” function. Basically, the developer had written the function to return you an array of the elements that you asked for by id. So in effect, if you wrote -

var elements = $("txtName", "txtPhone", "txtCountry");

- then you would be returned an array containing a reference to each of those form elements (presuming that they exist, of course ;-) )

Well that’s all fine and dandy, but more often than not I find myself trying to find elements in that are declared as: runat=”server”. And if those elements are nested in a UserControl, then you have to know how their id will be transformed at runtime by ASP.NET (for example, “txtName” may become “ctl00_main_sidebar_txtName”). So, with this in mind, I wrote my own version of the $ function which took care of this situation for me:


/*
 * Find an element based on the provided strings
 *
 * elementId:   Server-side id of the element to find (e.g. "txtName")
 * tagName:     The runtime tag of the element (e.g. "input")
 * elementType: The runtime value of the "type" attribute for the element,
 *              if it exists (e.g. "text")
 */
function $(elementId, tagName, elementType) {
    if (!tagName || tagName == "") {
        return document.getElementById(elementId);

    } else if (tagName) {
        var elements = document.getElementsByTagName(tagName, "gi");
        var typeRegex = elementType && elementType != "" ? new RegExp(elementType) : null;

        for (var i = 0; i < elements.length; i++) {
            if (typeRegex) {
                if (!elements[i].type || !typeRegex.exec(elements[i].type)) {
                    continue;
                }
            }

            if (elements[i].id && elements[i].id.indexOf(elementId) >= 0) {
                return elements[i];
            }
        }
    }

    return null;
}

It’s possibly not the most efficient piece of code that you’ll ever come across, but it does the job perfectly.