Showing posts with label JScript. Show all posts
Showing posts with label JScript. Show all posts

Monday, September 28, 2015

[JScript] jQuery without IE

For those who looked, this is mod of plasticgrammer's post. Most of the comments are Google Translates attempts at the original programmer's Japanese.

The single biggest difference from the previous posting is that Internet Explorer is not called into to manage jQuery. Instead the htmlfile object is used.

jQuery expects a few global symbols (it is after all a browser library), so the beginning of the code declares them: document, window etc. Then the jQuery file is dragged across the internet and eval'd in the context of the script.

You'll notice that the jQuery version is quite ancient. This is another problem with this approach. I imagine that it's just a case of declaring some more public symbols. If anyone tries this, please let me know how recent you can go before things break. And if you succeed in using more recent jQuery libraries, please do let me know what modifications were required.
// To prepare, such as window or document to the global name space
(function (url) {
  if ("undefined" === typeof document)
    document = new ActiveXObject("htmlfile");
  document.write("<" + "html" + ">" + "<" + "/html>"); // this important
  if ("undefined" === typeof window)
    window = document.parentWindow;
  if ("undefined" === typeof alert)
    alert = function (s) {
      return window.alert(s);
    };
  if ("undefined" === typeof confirm)
    confirm = function (s) {
      return window.confirm(s)
    };
  if ("undefined" === typeof location)
    location = window.location;
  if ("undefined" === typeof navigator)
    navigator = window.navigator;
  if ("undefined" === typeof window.ActiveXObject)
    window.ActiveXObject = ActiveXObject;

  var XMLHttpRequest = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
  var o = XMLHttpRequest.open("GET", url, false);
  var s = XMLHttpRequest.send();
  eval(XMLHttpRequest.ResponseText);
  return true;
})("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js");
Now a bit of demo code. Notice how we tell JScript what $ means. Possibly that could go in the earlier block of code as yet another global.
var $ = window.$;

// Operation example of a simple jQuery object
WScript.Echo($("<" + "div" + ">").attr("a", "fo").get(0).outerHTML);

// Course alert even I can use.
alert($("<" + "div" + ">").attr("a", "fo").get(0).outerHTML);
(Blogspot didn't like seeing div etc as markup, thus the odd syntax).

© Copyright Bruce M. Axtens, 2015

[JScript] Using jQuery in IE

IE is the browser we all love to hate. It's also scriptable and so inevitably ends up being considered for various tasks.

The following fragment demonstrates the first of two mechanisms I've found for instantiating jQuery in an IE session under script control.
var oIE;
  try {
    oIE = new ActiveXObject("InternetExplorer.Application");
  } catch (errIE) {
    WScript.Quit();
  }
  oIE.Visible = false;

  oIE.Navigate("http://www.example.com");
  while (oIE.Busy) {
    WScript.Sleep(100);
  }

  WScript.Sleep(1000); // could be less

  var DOM = oIE.Document;
  var scr = DOM.createElement('script');
  scr.src = "https://code.jquery.com/jquery-2.1.4.min.js";
  DOM.head.appendChild(scr);

  var $ = DOM.parentWindow.jQuery;
The above code is sliced out of a current project. We navigate to the target, create a script tag, point it at jquery's CDN, and append it to the document's head. Then we define a $ to point to oIE.Document.parentWindow.jQuery.

The same technique can be applied to any page, really. I have a bookmark in my browser that has a name of InjectjQuery and an address of
javascript:var script = document.createElement('script');script.src = "https://code.jquery.com/jquery-2.1.4.min.js"; document.head.appendChild(script);

The second method for instantiating jQuery in IE can be found at plasticgrammer. I had difficulty with it, but got it working. It has some good things which I'll discuss in the next posting.

© Copyright Bruce M. Axtens, 2015

Thursday, February 27, 2014

[VBScript] Boosting myself to HIGH process priority

The script gets its own name, then looks through the Win32_Processes for a match with CSCRIPT.EXE and a CommandLine containing that name. Any matches (should be only one, but could be more) are boosted to HIGH process priority.

This demonstrates WMI calls from both VBScript and JScript. Note the need to explicitly define an Enumerator in the JScript version.
Option Explicit

Dim sName
Dim sComputer
Dim oWMI
Dim cProcesses
Dim oProcess

Const HIGH = 256
sComputer = "."
Set oWMI = GetObject("winmgmts:\\" & sComputer & "\root\cimv2")
sName = WScript.ScriptName

Set cProcesses = oWMI.ExecQuery("Select * from Win32_Process Where Name = 'cscript.exe' And CommandLine LIKE '%" & sName & "%'")
For Each oProcess In cProcesses
  oProcess.SetPriority(HIGH) 
  WScript.Echo "Boosted myself"
Next
And in JScript
var HIGH = 256;
var sComputer = ".";
var sName = WScript.ScriptName;    

var query = GetObject("winmgmts:\\\\" + sComputer + "\\root\\cimv2")
    .ExecQuery("Select * from Win32_Process " + 
    "Where Name = 'cscript.exe' And CommandLine LIKE '%" + sName + "%'")

// Enumerate WMI objects
var cProcesses = new Enumerator(query);

for ( ; !cProcesses.atEnd(); cProcesses.moveNext()) { 
    var oProcess = cProcesses.item()
    oProcess.Priority = HIGH
    WScript.Echo( "Boosted myself")
}
© Copyright Bruce M. Axtens, 2014

Friday, September 21, 2012

[JScript] Another Config library


I've been doing a fair bit of JScript of late, and as I find working with Registry for runtime configuration a bit tiresome, I've cooked up a Config object. It's defined using the prototype approach to object definition. Config files are, in this case, ANSI or Unicode (UTF16LE) files, in the form
key=value
Creating an instance of the object involves passing in the name of the config file. I've hit upon the following technique for tying the config file to the script, using the FileSystemObject and the WScript object.
var oFSO = new ActiveXObject("Scripting.FileSystemObject"),
    sHere = oFSO.GetParentFolderName(WScript.ScriptFullName),
    sConfig = oFSO.BuildPath(sHere, 
        oFSO.GetBaseName(WScript.ScriptName) + ".config");
That way one may always be sure that (for example) Melchizedek.js will have a Melchizedek.config next to it.

First, the main function

function Config(sFile) {
    this.kind = "";
    this.oFSO = new ActiveXObject("Scripting.FileSystemObject");
    this.text = "";
    var resp = [];
    this.file = sFile;
    if (this.oFSO.FileExists(sFile)) {
        resp = function(oFSO, sFilename) {
            var forReading = 1;
            var asUnicode = -1;
            var asANSI = 0;
            var resp = [];
            if (oFSO.FileExists(sFilename)) {
                var handle = oFSO.OpenTextFile(sFilename, forReading, false,
                        asANSI);
                var BOM = handle.Read(2);
                handle.Close();
                if (BOM.charCodeAt(0) == 0xFF && BOM.charCodeAt(1) == 0xFE) {
                    handle = oFSO.OpenTextFile(sFilename, forReading, false,
                            asUnicode);
                    resp[0] = "unicode";
                } else {
                    handle = oFSO.OpenTextFile(sFilename, forReading, false,
                            asANSI);
                    resp[0] = "ansi";
                }
                resp[1] = handle.ReadAll();
                handle.Close();
                return resp;
            } else {
                return resp;
            }
        }(this.oFSO, sFile);
        this.kind = resp[0];
        this.text = resp[1];
        this.name = sFile;
        this.filefound = true;
    } else {
        this.filefound = false;
    }
    return this.filefound;
}
Note that the code, in an attempt to deal appropriately with config files being in ANSI or UTF-16LE format, reads the first two bytes of the config file. If the UTF16LE BOM is there, it reads the file as Unicode. Otherwise, it reads as ANSI.

A few other things are set so that the other methods will work, namely for exists, name and kind.

Config.prototype.name = function() {
        return this.name;
};

Config.prototype.exists = function() {
        return this.filefound;
};

Config.prototype.kind = function () {
        return this.kind;
};
Next come the main workhorses of the object: define, retrieve and save.
Config.prototype.retrieve = function(sName) {
        if (arguments.length > 1) {
                var sDefault = arguments[1];
        } else {
                sDefault = null;
        }

        var re = new RegExp("^" + sName + "=(.*?)$", "m");
        var arr = re.exec(this.text);
        if (arr === null) {
                return sDefault;
        } else {
                return RegExp.$1;
        }
};

Config.prototype.define = function(sName, sValue) {
        var sNew = sName + "=" + sValue;
        var re = new RegExp("^" + sName + "=(.*?)$", "m");
        var arr = re.exec(this.text);
        if (arr === null) {
                this.text = this.text + "\n" + sNew;
        } else {
                this.text = this.text.replace(re, sNew);
        }
};

Config.prototype.save = function() {
        var sFile = "";
        var handle = "";
        // allow for save to a different file
        if (arguments.length > 0) {
                sFile = arguments[0];
        } else {
                sFile = this.file;
        }
        if (this.kind === "ansi") {
                handle = this.oFSO.CreateTextFile(sFile, true, false);
        } else {
                handle = this.oFSO.CreateTextFile(sFile, true, true);                
        }
        handle.Write(this.text);
        handle.Close();
};
retrieve accepts two parameters: the key in the config store, and the default (in the event that the key is not found.) Rather than using a Scripting.Dictionary, the config data is stored as a string, and regular expressions are used to extract and update it.

define accepts two parameters: the key in the config file, and the value to be associated with it. If the key is not found in the stored keys and values, it is appended to it.

save accepts one optional parameter: the name of the file into which to write the stored string of keys and values. If no name is given, the filename given when Config() was first called is used.

The code may be used as follows:

var c = new Config("dog.cfg");
'the define() will either add or update the store to 
'    sound=bark
c.define("sound","bark");
'the save() will write the store to dog.cfg
c.save();

'Config reloads dog.cfg
var c = new Config("dog.cfg");
'if "sound" is a key in dog.cfg, the associated value will be displayed
'otherwise the default.
WScript.Echo(c.retrieve("sound","woof"));

'display the kind (ansi or unicode)
WScript.Echo(c.kind);
'... whether the file exists
WScript.Echo(c.exists());
'... and what its name is
WScript.Echo(c.name);
The result of running the above code (from within SciTE):
>cscript /nologo Config.js
 bark
 unicode
 -1
 dog.cfg
 >Exit code: 0
I have recently pushed this code through Google's Closure Compiler and the difference in code size is significant -- the result is about 50% smaller than the original. I expect it runs faster too, though I haven't bothered to check it out thoroughly.
function Config(a) {
  this.kind = "";
  this.oFSO = new ActiveXObject("Scripting.FileSystemObject");
  this.text = "";
  var b = [];
  this.file = a;
  if(this.oFSO.FileExists(a)) {
    var b = this.oFSO, d = [];
    if(b.FileExists(a)) {
      var c = b.OpenTextFile(a, 1, !1, 0), e = c.Read(2);
      c.Close();
      255 == e.charCodeAt(0) && 254 == e.charCodeAt(1) ? (c = b.OpenTextFile(a, 1, !1, -1), d[0] = "unicode") : (c = b.OpenTextFile(a, 1, !1, 0), d[0] = "ansi");
      d[1] = c.ReadAll();
      c.Close()
    }
    b = d;
    this.kind = b[0];
    this.text = b[1];
    this.name = a;
    this.filefound = !0
  }else {
    this.filefound = !1
  }
  return this.filefound
}
Config.prototype.name = function() {
  return this.name
};
Config.prototype.exists = function() {
  return this.filefound
};
Config.prototype.kind = function() {
  return this.kind
};
Config.prototype.retrieve = function(a) {
  var b = 1 < arguments.length ? arguments[1] : null;
  return null === RegExp("^" + a + "=(.*?)$", "m").exec(this.text) ? b : RegExp.$1
};
Config.prototype.define = function(a, b) {
  var d = a + "=" + b, c = RegExp("^" + a + "=(.*?)$", "m");
  this.text = null === c.exec(this.text) ? this.text + "\n" + d : this.text.replace(c, d)
};
Config.prototype.save = function() {
  var a = "", a = "", a = 0 < arguments.length ? arguments[0] : this.file, a = "ansi" === this.kind ? this.oFSO.CreateTextFile(a, !0, !1) : this.oFSO.CreateTextFile(a, !0, !0);
  a.Write(this.text);
  a.Close()
};

Enjoy!
© Copyright Bruce M. Axtens, 2012

Friday, July 13, 2012

[JScript.NET] Parsing the commandline, working with MS Access

JScript.NET: A bit of a backwater these days. I'm told that Visual Studio 2005 was the last iteration of that IDE to have good support for it. Now one must jump through a couple of hoops to use VS2010 for JScript.NET debugging and otherwise one just has the commandline compiler, jsc. Interestingly, every iteration of the .NET framework has had a jsc compiler, so someone out there must still love it a little. In general, however, it's use is deprecated in favour of other .NET languages like IronPython, CS-Script and IronJS.

Still, I've been wanting to get something working in JScript.NET ...

A while back I wrote a tool in JScript to coordinate the Convert and Repair of Access databases. It works fine, albeit a little slowly being interpreted. It's short and, as it turned out, converted fairly easily once I began to get my head around the shift from Windows Scripting Host (WSH) to .NET.

In the original, I connected to the Scripting.FileSystemObject, using ActiveXObject(). I still do that in the JScript.NET version, simply because I haven't found out what the .NET equivalents are yet.
var oFSO = new ActiveXObject("Scripting.FileSystemObject");
Next came parsing the command line. This is very easy in JScript and VBScript thanks to the WScript object's Arguments object, which even parses the command line into a dictionary, so that /name:<thing> is accessible as WScript.Arguments.Named("name") (as below):
var sDatabaseName = WScript.Arguments.Named("name");
var sDataFolder = WScript.Arguments.Named("data");
var sTempFolder = WScript.Arguments.Named("temp");
var sBackupFolder = WScript.Arguments.Named("backup");
However, .NET's System.Environment.GetCommandLineArgs() is nowhere near as helpful, so I had to write something to parse the commandline that would at least come fairly close to the original in functionality.
function argNamed( sname : String ) {
 var result : String = "";
 var aCmdline = System.Environment.GetCommandLineArgs();
 var i : short = 1;
 for ( ; i < aCmdline.length; i++ ) {
  if (aCmdline[i].toLowerCase().slice(0, sname.length + 2) == ( "/" + sname.toLowerCase() + ":" )) {
   var inner : String = aCmdline[i].slice( sname.length + 2 ) 
   result = (inner.charAt(0) == '"' ? inner.slice(1,inner.length-1) : inner);
  }
 }
 return result;
}

var sDatabaseName : String = argNamed("name");
var sDataFolder : String = argNamed("data");
var sTempFolder : String = argNamed("temp");
var sBackupFolder : String = argNamed("backup");
Note that I'm using type annotations in the code to give the compiler a few hints about how to handle the intent of the code. Next, the handling the command line itself. Not a particularly good way of doing it in the original, but hey, it worked.
var bWorking = true;

if ( undefined === sDatabaseName ) {
        WScript.Echo( "Specify database name with /name:" );
        bWorking = false;
}

if ( undefined === sDataFolder ) {
        WScript.Echo( "Specify data path with /data:" );
        bWorking = false;
}

if ( undefined === sTempFolder ) {
        WScript.Echo( "Specify temp folder with /temp:" );
        bWorking = false;
}

if ( undefined === sBackupFolder ) {
        WScript.Echo( "Specify backup folder with /backup:" );
        bWorking = false;
}

if ( ! bWorking ) {
        WScript.Quit();
}
With WScript.Quit() unavailable, I had to find something that would work in JScript.NET. I tried return and break but the compiler complained. Finally, I stumbled over System.Environment.Exit();.
if (  sDatabaseName == "" ) {
        print( "Please specify database name on commandline with /name:" );
        System.Environment.Exit(1);
}

if ( sDataFolder == "" ) {
        print( "Please specify data path on commandline with /data:" );
        System.Environment.Exit(2);
}

if ( sTempFolder == "" ) {
        print( "Please specify temp folder on commandline with /temp:" );
        System.Environment.Exit(3);
}

if ( sBackupFolder == "" ) {
        print( "Please specify backup folder on commandline with /backup:" );
        System.Environment.Exit(4);
}
(Having a more sensible help text is next on the agenda.) Next I create the filenames that will be used later in the Access Compact and Repair process. These also appear in the JScript.NET version for the usual reasons (that is, I don't know yet how to do a BuildPath equivalent in .NET.)
var sDatabaseFile = oFSO.BuildPath(sDataFolder, sDatabaseName);
var sBackupFile = oFSO.BuildPath(sBackupFolder, sDatabaseName);
var sTempFile = oFSO.BuildPath(sTempFolder, sDatabaseName);
Next, assorted deletes, moves and the setup and execution of the CompactRepair Access.Application's CompactRepair() method.
try {
 oFSO.DeleteFile( sTempFile );
} catch ( e ) {
 //~ WScript.Echo( e.message + ': ' + sTempFile );
}

WScript.Echo("CompactRepair",sDatabaseFile,"to",sTempFile);
var oACC = new ActiveXObject('Access.Application');
oACC.CompactRepair( sDatabaseFile, sTempFile, true );
oACC.Quit();

try {
 oFSO.DeleteFile( sBackupFile );
} catch( e ) {
 //~ WScript.Echo( e.message + ': ' + sBackupFile );
}
WScript.Echo("Moving",sDatabaseFile,"to",sBackupFile);
oFSO.MoveFile( sDatabaseFile, sBackupFile );

// copy temp to source, overwriting
try {
 oFSO.DeleteFile( sDatabaseFile );
} catch( e ) {
 //~ WScript.Echo( e.message + ': ' + sDatabaseFile );
}
WScript.Echo("Moving",sTempFile,"to",sDatabaseFile);
oFSO.MoveFile( sTempFile, sDatabaseFile );

WScript.Quit();
The JScript.NET version is almost exactly the same:
try {
 oFSO.DeleteFile( sTempFile );
} catch ( e ) {
 //~ print( e.message + ': ' + sTempFile );
}

print("CompactRepair ",sDatabaseFile," to ",sTempFile);
var oACC = new ActiveXObject("Access.Application");
oACC.CompactRepair( sDatabaseFile, sTempFile, true );
oACC.Quit();

// copy source to backup, overwriting
try {
 oFSO.DeleteFile( sBackupFile );
} catch( e ) {
 //~ print( e.message + ': ' + sBackupFile );
}
print("Moving ",sDatabaseFile," to ",sBackupFile);
oFSO.MoveFile( sDatabaseFile, sBackupFile );

// copy temp to source, overwriting
try {
 oFSO.DeleteFile( sDatabaseFile );
} catch( e ) {
 //~ print( e.message + ': ' + sDatabaseFile );
}
print("Moving ",sTempFile," to ",sDatabaseFile);
oFSO.MoveFile( sTempFile, sDatabaseFile );
System.Environment.Exit(4);
Notice the change from WScript.Quit() to System.Environment.Exit(). Notice also the change from WScript.Echo() to print(). One weird thing about the latter is that the arguments in a WScript.Echo() are output separated by a space, but are not separated at all in a print(), thus the extra spaces in the quoted strings. Sample invocation:
acarNET.exe /name:database.mdb /data:c:\acartest\data /temp:c:\temp /backup:c:\acartest\backup 
Compiled, the JScript.NET version runs very quickly in comparison to the original JScript version. It almost makes me wish JScript.NET had a future. As it stands, I'm going to have to redo this in something else. Sigh. © Copyright Bruce M. Axtens, 2012

Thursday, June 21, 2012

[JScript] The name of the caller


A few postings back I demonstrated how to pull the name of the current function out of arguments.callee. Now to finding out the name of the caller:

function foo() {
 try {
  var myCaller = foo.caller.toString().split(/ /)[1].split(/\(/)[0];
 } catch( e ) {
  myCaller = e.message;
 }
 WScript.Echo(myCaller );

}

function bar() {
 foo();
}

bar();
foo();
The output from all that is
bar
'foo.caller' is null or not an object
So if foo is called from bar then myCaller contains "bar" otherwise an error is raised as the global context doesn't qualify as a "caller". Notice, too, that unlike getting the callee, the caller requires the name of the current function, not arguments.© Copyright Bruce M. Axtens, 2012

Wednesday, June 20, 2012

[Go] Out with JScript, in with Go?

Today I ran a large JScript against a month's worth of hourly REST traffic logs. The logs were parsed and manipulated into a series of tables in an Access database. It took about 12† hours to run. 12 hours ... and on a decently-specced laptop -- a Toshiba Satellite Pro L670.

So I'm looking around for something as flexible as JScript/javascript but which produces native binaries ... and Go seems like a good possibility. Any other suggestions?




† I know, I did say 24 hours initially. Frightening the effect of 4 hours sleep on the middle-aged mind.

© Copyright Bruce M. Axtens, 2012

Monday, June 18, 2012

[JScript] Scatter redux

The previous version has a problem: when the recordset has zero records, it falls over. The updated version is below:

function Scatter( o ) {
 var result = {};
 var bEmpty = true;
 var vba = {};
 if ( o.RecordCount > 0 ) {
  bEmpty = false;
  vba = new VBArray( o.GetRows() );
 }
 var fldCount = o.Fields.Count;
 for (var i = 0; i < fldCount; i++ ) {
  result[o.Fields(i).Name] = [];
  if ( ! bEmpty ) {
   for ( var j = vba.lbound(2); j <= vba.ubound(2); j++ ) {
    result[o.Fields(i).Name].push( vba.getItem(i,j) );
   }
  }
 }
 return result;
}


© Copyright Bruce M. Axtens, 2012

Saturday, June 16, 2012

[JScript] Scatter (like the FoxPro function)

On a roll tonight!

Scatter and Gather are a pair of functions in FoxPro and related languages which would take a record and copy it into the memvar space, naming the memvar the same as the field name and storing the field's value. Gather did the opposite.

Now I've got that working in JScript. I hand it a recordset and it creates an object with the field names as property names and the values of each as a list attached to the property. This makes things like this possible:

var X = Scatter( oRS );
 for (var i = 0; i < X.AdvertiserParentFK.length; i++ ) {
  WScript.Echo( i, X.AdvertiserParentFK[i]);
 }
And so here's the function:
function Scatter( o ) {
  var result = {};
  var vba = new VBArray( o.GetRows() );
  var fldCount = o.Fields.Count;
  for (var i = 0; i < fldCount; i++ ) {
   result[o.Fields(i).Name] = [];
   for ( var j = vba.lbound(2); j <= vba.ubound(2); j++ ) {
    result[o.Fields(i).Name].push( vba.getItem(i,j) );
   }
  }
  return result;
 }

More to enjoy! 


© Copyright Bruce M. Axtens, 2012.

[JScript] ADODB GetRows to JScript

StackOverflow to the rescue again. Where would I be without them?

Anyway, I was looking up how to return a GetRows() call on an ADODB recordset to JScript and worked out the following from this posting about returning SafeArrays to JScript


function getRowsToMatrix( o ) {
  var vba = new VBArray( o );
  var dims = vba.dimensions();
  var result = [];
  for ( var i = vba.lbound(2); i <= vba.ubound(2); i++ ) {
   result[i] = [];
   for ( var j = vba.lbound(1); j <= vba.ubound(1); j++ ) {
    result[i].push(vba.getItem(j,i));
   }
  }
  return result;
 }

What I end up with is an array of arrays, which I can address as follows:


var X = getRowsToMatrix( oRS.GetRows() );
var recs = X.length;
var flds = X[0].length;
var lastFldLastRec = X[recs-1][flds-1]; // X is zero-based

Enjoy!



© Copyright Bruce M. Axtens, 2012

Monday, January 03, 2011

[VB6] Using VBScript's Escape and UnEscape (Take 2)

It's been pointed out to me recently that Escape() doesn't handle embedded quotes and embedded newlines. This is the fix.

I'm using JScript rather than VBScript, so that I can use the String object's fromCharCode() method. I parse the input string, convert the characters to a list of their numeric equivalents for passing to fromCharCode() and then store the result in a JScript variable which is then passed to escape().

Thanks to Anonymous and anjali kalkarni for pointing out the problem.


© Bruce M. Axtens, 2011