I experimenting with writing Vista/W7 gadgets. In my experiment I want to write the modification date of certain files on the system. Problem is that if I want use string manipulation functions the gadget just stops writing its output. Part of the gadget's code looks like this:
function format_lmd(lmd)
{
// Parse something like "Sun Aug 26 17:13:22 UTC+0200"
var lmdFields = lmd.split(' ');
//weekday = lmdFields[0];
//month = lmdFields[1];
//monthday = lmdFields[2];
//moment = lmdFields[3];
//return monthday+' '+month+' '+moment;
return lmd;
}
function paintGadget()
{
var fileitem = System.Shell.itemFromPath("c:\\myfile.txt");
//canvas.addTextObject(' '+fileitem.modifyDate, 'Segoe UI', 9, 'white', text_offset, 21);
var result = null;
result = ' ';
result += format_lmd(fileitem.modifyDate);
canvas.addTextObject(result, 'Segoe UI', 9, 'white', text_offset, 21);
}
The call to split (in the function format_lmd) seems to halt the script (or better: throw an exception). Although documentation seems to indicate that the split function can be used to split a string in multiple parts, it doesn't work in my case.
Questions:
Thanks, Patrick
EDIT: I found out how to enable the debugger for Javascript (see http://msdn.microsoft.com/en-us/library/bb456467%28v=VS.85%29.aspx#_sidebar_overview_debugging_basic). A debug window now pops up and says "Object expected", but this doesn't really help me.
This is one of the major issues with the Windows Desktop Gadgets API and System.Shell namespace. Some of the commands return types that aren't handled natively by JScript. Fortunately, this isn't one of those times but the issue is similar. I'll get to the answer, but first, a bit of side-note rambling.
You noticed when checking typeof lmd
in the function, "date" is the result. What's strange about this is that there is no native date type JScript/ECMAScript - typeof new Date()
will result in "object". The reason for this is that many System.Shell.* methods are mapped to the .net equivalent methods and the result is just returned to the JScript with no effort to convert the data into a JScript native type. A very short-sighted implementation by Microsoft.
When outputting lmd to a debugger you'll see a string result, something like:
Wed Nov 25 11:06:30 UTC 2009
This is because a function that expects a string will convert a non-string argument to a string. System.Debug.outputString() is no exception here. Realizing this, the solution becomes clear - force the type conversion from "date" to a string:
var lmdFields = String(lmd.split(' '));
// or
var lmdFields = (lmd+"").split(' ');
//-> ["Wed","Nov","25","11:06:30","UTC","2009"]
If you want to convert the date to a JavaScript Date object, you can just pass it to the Date() constructor:
var lmdFields = new Date(lmd);
System.Debug.outputString(lmdFields.toLocaleString());
//-> "25 November 2009 11:06:30"