Author Archive
Fun with JavaScript Closures + Scoping
by Warlock on Jul.10, 2010, under Javascript
It’s easy to forget that variable scoping in JavaScript is at the function level and not a the block level like what you get with C/C++/C#/Java/etc. This can have some counter intuitive implications when you’re dealing with closures. Consider the following example:
var closure;
for(var i = 0; i <= 5; i++) {
var x = i * i;
if( i == 1 ) {
closure = function() { alert(x); };
}
}
closure();
What do you think the output of the alert box will be? At first blush it's easy to think it will be 1 because the variable x is declared within the for loop.
In reality, though, the output is 25 because despite the variable declaration in the for loop, the code is functionally equivalent to this:
var closure;
var x;
for(var i = 0; i <= 5; i++) {
x = i * i;
if( i == 1 ) {
closure = function() { alert(x); };
}
}
closure();
This is important to remember when working with closures in loops.
So how do solve this problem? Manually create a new scope by creating and invoking an anonymous function.
var closure;
for(var i = 0; i <= 5; i++) {
var x = i * i;
if( i == 1 ) {
(function(x) {
closure = function() { alert(x); };
})(x);
}
}
closure();
With the newly introduce lexical scope, the program returns 1 as one would expect.
Naming collision in ASMX web service
by Warlock on Jul.02, 2010, under .NET, C#, xml
I ran into an interesting problem today while working on an ASMX web service.
Everything compiled fine, but when I went to view the ASXM in the browser to manually invoke the methods to test it, the normal automatically generated info page didn’t come up. Trying to grab the WSDL also gave me a blank page.
I then attached the debugger to IIS to observe what was happening when I tried to view the ASMX info page. By breaking on exceptions, I was able to uncover the following error:
The XML element ‘XXX’ from namespace ‘http://tempuri.org/’ references a method and a type. Change the method’s message name using WebMethodAttribute or change the type’s root element using the XmlRootAttribute.
With a little more thinking, I was able uncover what I believe was going on.
I had defined a complex type to return as a response:
public class FooResponse {...}
[WebMethod]
public FooResponse Foo() {...}
Note that here the exact name pairing of Foo/Foo+Response is important. When I changed the method name as follows, the problem went away:
public class FooResponse {...}
[WebMethod]
public FooResponse Fooxxx() {...}
What I believe is happening is .NET is attempting to automatically wrap the response coming from the Foo method with an element named FooResponse. The use of that same name as the object you want to return creates ambiguity. By changing the name of my response object, or the name of my method I was able to avoid this collision.
I have also posted this information in response to a question on StackOverflow.
The speed of jQuery.append(…)
by Warlock on Jun.22, 2010, under Javascript
I’ve been doing some JavaScript performance optimization recently and I thought I’d share some of my findings regarding jQuery.
The project I’m working involves creating large DOM trees of elements from data, and I’ve been trying to speed things up. Initially I was using jQuery.append(...) combined with document.createElement(...) in something along these lines:
var foo = $(document.createElement("span")).attr("bar", "baz");
$(parent).append(foo);
The reason for this style is because I want to be able to keep around references to the created object so I can use it later and not be forced to use selectors.
While doing some profiling, I became concerned that the append call was taking too much time, so I did some testing. Some articles I’ve read indicated that it was better to do string concatenation to create a massive strings of the elements that you wanted to create and the use a single jQuery.append(...) call to create the elements at the end. I tested that scenario as well.
My test code:
(function() {
var start = new Date();
var root = document.createElement("span");
for(var i = 0; i < 100000; i++) {
root.appendChild(document.createElement("span"));
}
var end = new Date();
alert("Raw appendChild: " + (end.valueOf() - start.valueOf()));
})();
(function() {
var start = new Date();
var root = $(document.createElement("span"));
for(var i = 0; i < 100000; i++) {
root.append(document.createElement("span"));
}
var end = new Date();
alert("jQuery append: " + (end.valueOf() - start.valueOf()));
})();
(function() {
var start = new Date();
var root = $(document.createElement("span"));
var inners = "";
for(var i = 0; i < 100000; i++) {
inners += "";
}
root.append(inners);
var end = new Date();
alert("jQuery from string: " + (end.valueOf() - start.valueOf()));
})();
(function() {
var start = new Date();
var root = document.createElement("span");
var inners = "";
for(var i = 0; i < 100000; i++) {
inners += "";
}
root.innerHTML = inners;
var end = new Date();
alert("innerHTML: " + (end.valueOf() - start.valueOf()));
})();
The numbers I get are as follows on my Mac in Firefox are as follows (creating 10k span elements).
Raw appendChild: 304 ms
jQuery append: 5492 ms
Concatenated string (jQuery Append): 6040 ms
Concatenated string (raw innerHTML): 208 ms
My results were somewhat inconsistent. Initially when I was running this test I did see jQuery append with the concatenated string to be faster, but when running tests later, it was a bit slower. In general, I think the conclusion of the article is correct. String concatination is better than many calls to jQuery.append(...), but it doesn’t hold a candle to just doing the raw DOM manipulations. This makes sense since jQuery still has to parse the string you give it (it doesn’t feed it raw into the innerHTML) and then call the raw DOM methods directly. Lesson learned.
Tri-State Checkbox
by Warlock on Jun.20, 2010, under Javascript, User Interfaces
I’ve created a WAI-ARIA compliant javascript checkbox control (MIT/BSD/GPL licensed).
Your browser does not support iframes.
Demo available here.
Source code is available here.
This continues on my previous post regarding checkbox images, I’ve enhanced the images to include a disabled state for both the mixed and checked states.
TTStyledText problems with ampersand (’&')
by Warlock on Apr.25, 2010, under Cocoa, iPhone
I ran across an interesting problem today where I was trying to use TTStyledText from the Three20 project to create a TTStyledTextLabel that had text with links nested within it. I was trying to
Map here.
I was doing this with the following (simplified code):
[TTStyledText textFromXHTML:@"Map <a href=\"http://www.google.com/maps?f=q&hl=en\">here</a>." lineBreaks:YES URLs:YES];
As soon as I tried to put a URL in that had multiple URL parameters (and thus an &) things would disappear.
From briefly looking at the Three20 source code, I believe this because the parsing of the XHTML text is being done with an XML parser. As soon as I replaced the &s with &s things started to work. This can be done using the following code:
[@"Map <a href=\"http://www.google.com/maps?f=q&hl=en\">here</a>." stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
XSLT with Optional Extension Object
by Warlock on Dec.08, 2009, under .NET, C#, xml
Extension objects provide a convenient way to allow an XSL transform to interact with the outside world. They can also be used to offload computations that are difficult to express in XSL.
Recently, I ran into a scenario where I wanted to write an XSLT that would use an extension object to record some additional information about intermediate steps of the transform. The extension object was not required, however, and I wanted to leave it up to the user of the XSLT as to if they wanted to use the extension object.
The question then became how to conditionally execute calls to the extension object. Suppose you have the following extension object defined in C#:
public class FooExtensionObject
{
private List<string> recordedValues = new List<string>();
public void RecordValue(string val)
{
recordedValues.Add(val);
}
}
Now suppose this extension object is used in the following XSLT:
<xsl:transform
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:foo="urn:FooExObj">
<template match="/">
...
<xsl:value-of select="foo:RecordValue(@bar)"/>
...
</template>
</transform>
The extension object is supplied to the XSLT through the arguments:
XslTransform transform = new XslTransform();
transform.Load("SomeFile.xsl");
XsltArgumentList args = new XsltArgumentList();
FooExtensionObject aFoo = new FooExtensionObject();
args.AddExtensionObject("urn:FooExObj", aFoo);
XmlTextWriter myWriter = new XmlTextWriter("output.xml", null);
transform.Transform(xpathDoc, args, myWriter);
In the case where the extension object is not supplied, however, this XSLT will cause an error. To correct this issue, you can use the function-available function. Change the transform as follows:
...
<xsl:if test="function-available('foo:RecordValue')">
<xsl:value-of select="foo:RecordValue(@bar)"/>
</xsl:if>
...
The conditional statement blocks out the use of the extension object when it does not exist. Unfortunately, you must do this where ever you wish to use the extension object.
XML Comments
by Warlock on Nov.24, 2009, under .NET, C#, Visual Studio
Today I was looking for a reference for the proper notation for the cref attribute of the <see cref="..."> C# XML comment tag, and after finding it, I thought I’d post it here for future reference.
The cref (code reference) tag is prefaced by a single character, then a colon, followed by the reference in question. The character defines what is being referenced, as defined by the table below.
| Character | Description |
|---|---|
| N | Namespace |
| T | Type (class, interface, struct, enum, delegate) |
| F | Field (member variable, constant, etc) |
| P | Property (including indexers and indexed properties) |
| M | Method (including special methods like constructors – #ctor – operators, etc) |
| E | Event |
| ! | Error string |
The full reference for the prefixes is available here, with the full XML comment documentation available here. The Code Project also has an article on the topic.
Determining SQL Server Version Number
by Warlock on Aug.03, 2009, under SQL
I’ve recently had to write some conditional SQL depending on which version of SQL Server I was running on.
This MSDN article shows that for modern versions of SQL Server, the following will get the full version number:
SELECT SERVERPROPERTY('productversion');
The problem with this is that it is in a string format (FYI you will need to cast it to VARCHAR), and it uses nested decimal notation (e.g. 10.0.1600.22 for SQL Server 2008). This format is very difficult to reason with, as what I am looking to do is conditionally execute SQL for SQL Server 2000 and for everything else execute some other SQL. I don’t care about minor revisions or service packs. To my knowledge, Microsoft does not provide any functions to work with nested decimals.
To make things easier, I constructed the following SQL to pull the major version number out of the string, convert it to an integer, and stick it in a variable:
DECLARE @MajorVersion int
SELECT @MajorVersion = CAST(substring(CAST(SERVERPROPERTY('productversion') AS VARCHAR), 0, Charindex('.', CAST(SERVERPROPERTY('productversion') AS VARCHAR))) AS int);
Messy, I know. If anyone else has a better method, please leave it in the comments.
Mapping Enums to custom strings in NHibernate
by Warlock on Jul.02, 2009, under .NET, Database
Many times when working with a legacy relation model and a newly developed C# object model that sits on top of the relational model, you may need to map enum values to/from arbitrary strings in the database using NHibernate.
For example, suppose you have a a work order object that three possible states: request, approved, denied. To represent this, you might use the following enum:
enum WorkRequestState
{
Request,
Approved,
Denied
};
But let’s assume that the legacy relational model has represented these values as strings: REQ, APR, DEN. You can’t change the values for the relational model, and you certainly don’t want to use these values in your enum because they are not as readable as the values shown above.
By default, NHibernate will automatically convert you enum to a string value that matches the name of the enum values if the table field a string, or it will convert to the integer value for the enum options if the table field is an integer.
To do the above custom mapping we must implement a custom NHibernate type.
First, create a new class that inherits NHibernate.Type.EnumStringType. In your constructor, pass the type of the enum you are handling, and the maximum number of characters that the enum values will be to the base class constructor:
class WorkRequestStateEnumStringType : NHibernate.Type.EnumStringType
{
public WorkRequestStateEnumStringType()
: base( typeof(WorkRequestState), 3)
{
}
...
}
Next, override the GetValue(...) method to map the enum value to the equivalent string.
public override object GetValue(object enm)
{
if( null == enm )
return String.Empty;
switch( (WorkRequestState)enm )
{
case WorkRequestState.Request : return "REQ";
case WorkRequestState.Approved : return "APR";
case WorkRequestState.Denied : return "DEN";
default : throw new ArgumentException("Invalid WorkRequestState.");
}
}
Override the GetInstance(...) method to map a string value to the equivalent enum value:
public override object GetInstance(object code)
{
code = code.ToUpper();
if( "REQ".Equals(code) )
return WorkRequestState.Request;
else if( "APR".Equals(code) )
return WorkRequestState.Approved;
else if( "DEN".Equals(code) )
return WorkRequestState.Denied;
throw new ArgumentException(
"Cannot convert code '" + code + "' to WorkRequestState.");
}
Finally, in the NHibernate mapping file, specify the property’s type as the derived EnumStringType class.
<class name="WorkRequest" table="work_request_table">
<property
name="Status"
column="status_field"
type="my.namespace. WorkRequestStateEnumStringType, MyAssembly" />
...
<class>
Note that when specifying this type, you must use the assembly-qualified name because the NHibernate code doing the mapping is in a separate assembly from the type you created.
This information has been derived from Jeremy Miller’s original post here.
Cocoa/UIKit BulbView
by Warlock on Jun.18, 2009, under Cocoa, iPhone
In my continuing saga to bring old-school displays to new-school (word?) devices, I’ve created a “bulb view” that displays characters in a grid of “lights”. The best way to describe it is probably just to see it:
Like previous LCD view you can set the colors for the lit & dim bulbs, but improved from the LCD view, you can use letters, numbers, and most punctuation/special characters. Again the rendering is done in pure Quartz2D.
The source, including demo apps for both the Mac and iPhone, can be found here. With this view I was smart and made it conditionally compile various parts so that it can be used on either the iPhone or the Mac, without needing separate files.

