I am trying to write a WSH logon script. Administrators throughout the company need to be able to customize the execution of the script, and execute additional scripts, for specific locations and users. In order to make their jobs easier, I would like to provide an API that the administrators can access in their scripts. If I write my API using JScript, would it be possible to initialize the objects I define through VBScript? For example, consider the following code:
<!-- The WSF logon script file -->
<package>
<job>
<script language="JScript">
// A demonstration function
function OverNineThousand() {
return 9001;
}
// A demonstration "class"
function WorkstationClass() {
var os = "Windows XP";
this.getOperatingSystem = function() {
return os;
}
}
</script>
<script language="VBScript">
Dim bigNumber, workstation
'// This assignment works properly.
bigNumber = OverNineThousand()
'// This assignment causes an error. Am I doing it wrong?
Set workstation = New WorkstationClass()
'// Execution never gets this far
WScript.Echo workstation.getOperatingSystem()
</script>
</job>
</package>
Is there any way to accomplish what I'm trying to do?
VBScript and JScript seem to disagree on how to initialize an object. However, once the object has been initialized it is recognized by both languages. To get around this I had to create the object in JScript and then return it to the VBScript caller, as demonstrated below.
<package>
<job>
<script language="JScript">
// A demonstration "class"
function WorkstationClass() {
var os = "Windows XP";
this.getOperatingSystem = function() {
return os;
}
}
function CreateWorkstation() {
return new WorkstationClass();
}
</script>
<script language="VBScript">
Dim workstation
'// This assignment causes an error.
'// Set workstation = New WorkstationClass()
'// This works!
Set workstation = CreateWorkstation()
'// Prints "Windows XP"
WScript.Echo workstation.getOperatingSystem()
</script>
</job>
</package>
Related
Hello i am facing following problem.
I am have an report with a prompt page that contains three dates prompts. For each of these prompts I have added a JavaScript-Element so that a specific value is always selected. For this i have used following code:
<script type="text/javascript">
var fW = (typeof getFormWarpRequest == "function" ? getFormWarpRequest(): document.forms["formWarpRequest"]);
if(fW)
{
if(fW._oLstChoices1.length >= 1)
{
fW._oLstChoices1.selectedIndex = 18;
}
}
</script>
At the end i have a seperate list-prompt filled with static values, that runs the report automatically:
<script>
var form = getFormWarpRequest();
var list = form._oLstChoicesdummy;
list.selectedIndex = 0;
canSubmitPrompt();
setTimeout('oCVRS.promptAction(\'finish\')', 0);
</script>
When I open the report in Report Studio and click on "RUN", the report is executed automatically. But if I run the report outside of Report Studio, the prompt mask appears again and I have to click on "Finish/Run".
Has anyone faced silimiar problems and knows how to solve it?
Thanks in advance
If anyone else should face the same problem you can use the following code that will autosubmit the prompt page:
<script type="text/javascript">
//get the form request
var fW = (typeof getFormWarpRequest == "function" ? getFormWarpRequest() : document.forms["formWarpRequest"]);
if (fW)
{
// if the report is running from reportStudio or the Portal objects are different
if (fW.elements["cv.id"].value == "RS")
{
setTimeout('oCVRS.promptAction(\'next\')', 1000);
}else{
setTimeout('oCV_NS_.promptAction(\'next\')', 1000);
}
}
</script>
I work on a simple add-in for outlook 365, but it looks like I'm missing some simple point since office.context variable is always empty for me, for example even base code sample:
// The initialize function is required for all apps.
Office.initialize = function () {
// Checks for the DOM to load using the jQuery ready function.
$(document).ready(function () {
// After the DOM is loaded, app-specific code can run.
var item = Office.context.mailbox.item;
var subject = item.subject;
// Continue with processing the subject of the current item,
// which can be a message or appointment.
});
}
What can I miss? Adds-in permission is highest -- ReadWriteMailbox
Try to take some work example , for example: https://github.com/OfficeDev/Outlook-Add-in-Commands-Translator
You need parts of home.html and home.js.
I think this part of code need to work in your case:
(function () {
'use strict';
// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
** now try to get the item **
});
}; })();
I try it and it's work for me..
Good luck.
Setting an ACE editor instance to JSON or XML language mode works great.
But my statement
LiquidMode = ace.require("ace/mode/liquid").Mode,
// fails, ace.require("ace/mode/liquid") returns undefined
Yet the ace/mode/liquid file is defined on the cdn and is returned by it.
Thank you for any ideas or alternatives.
The cdn call and more:
<script src="https://cdn.jsdelivr.net/g/ace#1.2.6(noconflict/ace.js+noconflict/mode-hjson.js+noconflict/mode-liquid.js+noconflict/mode-xml.js+noconflict/theme-chrome.js)">
</script>
// Javascript file
var XMLMode = ace.require("ace/mode/xml").Mode,
JSONMode = ace.require("ace/mode/json").Mode,
LiquidMode = ace.require("ace/mode/liquid").Mode; // fails,
// ace.require("ace/mode/liquid") returns undefined
...
ace_session.setMode(new JSONMode()); // works great
...
ace_session.setMode(new LiquidMode());
When you load ace.js with multiple file syntax, dynamic loading doesn't work, because ace can't determine the url from which it was loaded.
As a workaround you can use
var url = "https://cdn.jsdelivr.net/ace/1.2.6/noconflict/"
ace.config.set("basePath", url)
see https://github.com/ajaxorg/ace/blob/v1.2.6/lib/ace/config.js#L185
Note that you don't need to pass mode object, setMode("ace/mode/liquid") works too.
<script src="https://cdn.jsdelivr.net/g/ace#1.2.6(noconflict/ace.js+noconflict/mode-json.js+noconflict/mode-liquid.js+noconflict/mode-xml.js+noconflict/theme-chrome.js)">
</script>
<script >
// Javascript file
var XMLMode = ace.require("ace/mode/xml").Mode,
JSONMode = ace.require("ace/mode/json").Mode,
LiquidMode = ace.require("ace/mode/liquid").Mode;
debugger
var editor = ace.edit()
var url = "https://cdn.jsdelivr.net/ace/1.2.6/noconflict/";
ace.config.set("basePath", url)
editor.setValue("use core::rand::RngUtil;\n\nfn main() {\n \n}", -1)
editor.setOptions({
autoScrollEditorIntoView: true,
maxLines: 15,
});
document.body.appendChild(editor.container)
editor.session.setMode("ace/mode/rust");
</script>
I'm finding it incredibly slow to fix issues that are specific to the iOS portion of my app. I'd like the know the recommended way to debug Worklight apps when the browser debugger isn't available.
In particular, I'm working on issues with WL.JSONStore which only works on iOS and Android. I can't use the browser debugger to see what's going on. When I do WL.Logger.debug() statements, nothing is showing up in the Xcode console, and the iPad simulator console (Cordova) only displays a few lines. There have also been periods this week that no output is printed anywhere.
I have downloaded and installed Weinre too, but none of the print statements appear to show up in its console and in general I just don't see information about the areas I need.
Thanks in advance for your suggestions.
General Worklight 5.0.6 Debugging
Look at the training module titled Debugging your applications. (Direct PDF link)
Debug Tips for JSONStore on Worklight 5.0.6
Try console.log('message') or WL.Logger.debug('message') inside jsonstore.js and your code ([app-name].js, etc.). The output should show up in Xcode's console and Android's LogCat.
Reset the Simulator or Emulator and/or call WL.JSONStore.destroy().
Make sure you're running on a supported environment:
Android >=2.2 ARM/x86 Emulator or Devices
iOS >=5.0 Simulator or Device
Try turning encryption off (ie. do not pass a password to WL.JSONStore.init or WL.JSONStore.initCollection).
Look at the SQLite Database file generated by JSONStore. This only works if encryption is off.
Android:
$ adb shell
$ cd /data/data/com.[app-name]/databases/wljsonstore
$ sqlite3 jsonstore.sqlite
iOS
$ cd ~/Library/Application Support/iPhone Simulator/6.1/Applications/[id]/Documents/wljsonstore
$ sqlite3 jsonstore.sqlite
Try looking at the searchFields with .schema and selecting data with SELECT * FROM [collection-name];. To exit sqlite3 type .exit. Take a look at this StackOverflow question for an example.
(Android Only) Enable verbose JSONStore.
adb shell setprop log.tag.jsonstore-core VERBOSE
adb shell getprop log.tag.jsonstore-core
(iOS >=6.0 and Safari >=6.0 Only) Try to use the JavaScript debugger. Set break points inside jsonstore.js. Helpful lines:
Bridge to Native code:
cdv.exec(options.onSuccess, options.onFailure, pluginName, nativeFunction, args);
Success Callbacks returning from Native code:
deferred.resolve(data, more);
Failure Callbacks returning from Native code:
deferred.reject(new ErrorObject(errorObject));
Write Proper Tests (Unit, Functional, Integration -- get test coverage). Here's a template that uses QUnit and Sinon.js to create a Sandbox environment where you can test how JSONStore handles different types of data/calls:
<!DOCTYPE HTML>
<html>
<head>
<title>JSONStore Test App</title>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.11.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.11.0.js"></script>
<script src="http://sinonjs.org/releases/sinon-1.6.0.js"></script>
<script>
//QUnit configuration flags, no need to change it.
QUnit.config.requireExpects = true;
</script>
</head>
<body id="content" style="display: none;">
<!-- Test results will be appended to the div below, no need to make changes here. -->
<div id="qunit"></div>
<script>
//Start Worklight
WL.Client.init({connectOnStartup : false});
//Hook into the deviceready event
document.addEventListener("deviceready", onDeviceReady, false);
//onDeviceReady will be called when JSONStore/Cordova is ready
function onDeviceReady () {
//Auto executing function that holds the test
(function (jQuery) { //The variable jQuery is usable inside.
//Mock WL.Client.invokeProcedure using a Stub.
//This is only useful if you need to link a Worklight Adapter
//to a JSONStore collection to reproduce your issue or bug.
//API Doc: http://sinonjs.org/docs/#stubs
var fakeAdapter = sinon.stub(WL.Client, "invokeProcedure", function (invocationData, options) {
//DO NOT Create a real adapter, just mock the reponse here if it's relevant to the bug.
var ADAPTER_RESPONSE = {invocationResult: {fakeKey: [{fn: 'carlos'}, {fn: 'mike'}]}};
options.onSuccess(ADAPTER_RESPONSE);
});
//[**Explain your test here**]
var EXPECTED_ASSERTIONS = 2; //every assertion is a deepEqual below.
asyncTest('[**Meaningful title here**]', EXPECTED_ASSERTIONS, function () {
//Destroy first to make sure we don't depend on state
WL.JSONStore.destroy()
.then(function () {
//[**Start writting your test here**]
//The test below is an example, it does the following:
// - Initializes a collection linked to a fake adapter (see stub above).
// - Checks if initialization worked by checking the collection name.
// - Loads data from the fake adapter (see stub above).
// - Checks if load worked by checking the number of documents loaded.
var collections = {
col1 : {
searchFields : {fn: 'string'},
adapter : {name: 'fakeAdapter',
load: {
procedure: 'fakeProcedure',
params: [],
key: 'fakeKey'
}
}
}
};
return WL.JSONStore.init(collections);
})
.then(function (response) {
//Prep for your assertion
var ACTUAL_VALUE = response.col1.name;
var EXPECTED_VALUE = 'col1';
var COMMENT = 'Checking for the right collection name';
//Do your assertion using deepEqual
//API Doc: http://api.qunitjs.com/deepEqual/
deepEqual(ACTUAL_VALUE, EXPECTED_VALUE, COMMENT);
return WL.JSONStore.get('col1').load();
})
.then(function (response) {
//Prep for your assertion
var ACTUAL_VALUE = response; //load returns number of documents loaded
var EXPECTED_VALUE = 2; //two documents are returned by the fake adapter (stub)
var COMMENT = 'Checking if load worked';
//Do the assertion using deepEqual
deepEqual(ACTUAL_VALUE, EXPECTED_VALUE, COMMENT);
start();//call start() after you finish your test succesfully
})
.fail(function (error) {
deepEqual(false, true, 'Failure callback should not be called' + error.toString());
start();//call start() after you finish your test with a failure
});
});
}(WLJQ)); //end auto executing function that holds the test
} //end wlCommonInit
</script>
</body>
</html>
Expected output of the code above:
Side-note: Here's a general article about the PhoneGap/Cordova workflow for a specific developer. There's a part of debugging, just browser-based though. Some of it applies to IBM Worklight development too.
cnandreu provides great tips here. Still, visibility is pretty poor and these approaches didn't really solve my problem. I would like to also suggest what I've found to be most useful in my project (aside from WL.Logger.debug() everywhere):
JSConsole has been indispensable (http://jsconsole.com/). In reality, I don't actually use it that much like it's intended. However, I've found that it's startup warning message does something with WL.Logger.debug() (and console.log()) that enables the statements to actually print to the console so I can see what I'm doing.
In iOS 6 Safari on the Mac lets you inspect the DOM of an attached device. It's moderately useful, especially for hybrid UI issues that only are misbehaving when running natively on iOS. I don't find it super helpful otherwise. See more at https://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/DebuggingSafarioniPhoneContent/DebuggingSafarioniPhoneContent.html
The single most useful technique I've been using has been to write status messages to the UI. Yes, it's an ugly prehistoric way to do things, but everything else - including 80s error print statements to the console - have failed miserably. Here's what I do (using Dojo & JavaScript):
var v = dom.byId('audio_status');
if (v) { v.innerHTML += "recording file ["+filename+"]"; }
Where audio_status is the ID of a DIV that displays the debug content.
This stuff is ugly, but at least we can see something.
I've been asked to 'sniff' users' windows username via a vbscript snippet and am having trouble getting this to work in the tapestry (5.1.0.5) application.
It seems tapestry is trying to interpret the vbscript as javascript and therefore failing.
The vbscript snippet (below) is embedded within a component which is in turn loaded conditionally inside a zone as part of a multizoneupdate.
pseudo tml:
<page>
<t:zone>
<t:if>
<t:mycomponent>
<vbscript />
vbscript:
<script type="text/vbscript" language="vbscript">
Dim shell
set shell = createobject("wscript.shell")
set env = shell.environment("process")
set field = document.getElementById("windowsLoginField")
if field is nothing then
alert("no field")
else
field.value = env("username")
end if
</script>
I am aware that this should only work for IE, however other browsers should fail gracefully (not run the script).
When the zone is re-loaded in a state where the vbscript should be rendered, I get the following error in firebug:
missing ; before statement
Dim shell
This is because the script is being evaluated by prototypejs:
evalScripts: function() {
return this.extractScripts().map(function(script) { return eval(script) });
},
Does anyone know of a way to avoid prototype evaluating this script so that it can make it through and be executed as vbscript?
I notice there is no #IncludeVbScriptLibrary annotation ...
thanks, p.
Tapestry inherits this problem from prototype. One solution is to patch the prototype extractScripts and evalScripts so that they do what you want when they see vbscript.
This code works (tested in IE7 and Chrome), but it could be made more flexible (keys off of type and not language for instance)
<script type="text/javascript">
String.prototype.extractScripts = function() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
var matchVBScript = new RegExp('<script.*type=(["\'])text\/vbscript\\1');
return (this.match(matchAll) || []).map(function(scriptTag) {
return [matchVBScript.match(scriptTag), (scriptTag.match(matchOne) || ['', ''])[1]];
});
}
String.prototype.evalScripts = function() {
return this.extractScripts().map(function(script) {
// if it's vbscript and we're in IE then exec it.
if ( script[0] && Prototype.Browser.IE ) return execScript(script[1], "VBScript");
// if it's not vbscript then eval it
if ( !script[0] ) return eval(script[1]);
});
}
</script>