How to debug an MSI Custom Action that is implemented in Javascript? - wix

I'm having difficulty figuring out why my Javascript Custom action is failing.
I thought I saw a topic in the WIX.chm file on debugging; now I cannot find it.
Q1
is there doc on how to debug Javascript or VBScript custom actions?
Q2
Is there a way to emit something into the MSI log from a custom action?
Addendum:
Some people think script is the wrong tool for writing CAs.
I don't agree. I think Javascript is a very good tool for the job.

For the doc, look for Session.Message.
To emit messages into the MSI log from a Javascript Custom Action, follow this boilerplate code:
//
// CustomActions.js
//
// Template for WIX Custom Actions written in Javascript.
//
//
// Mon, 23 Nov 2009 10:54
//
// ===================================================================
// http://msdn.microsoft.com/en-us/library/sfw6660x(VS.85).aspx
var Buttons = {
OkOnly : 0,
OkCancel : 1,
AbortRetryIgnore : 2,
YesNoCancel : 3
};
var Icons = {
Critical : 16,
Question : 32,
Exclamation : 48,
Information : 64
};
var MsgKind = {
Error : 0x01000000,
Warning : 0x02000000,
User : 0x03000000,
Log : 0x04000000
};
// http://msdn.microsoft.com/en-us/library/aa371254(VS.85).aspx
var MsiActionStatus = {
None : 0,
Ok : 1, // success
Cancel : 2,
Abort : 3,
Retry : 4, // aka suspend?
Ignore : 5 // skip remaining actions; this is not an error.
};
function MyCustomActionInJavascript() {
try {
LogMessage("Hello from MyCustomActionInJavascript");
// ...do work here...
LogMessage("Goodbye from MyCustomActionInJavascript");
}
catch (exc1) {
Session.Property("CA_EXCEPTION") = exc1.message ;
LogException(exc1);
return MsiActionStatus.Abort;
}
return MsiActionStatus.Ok;
}
// Pop a message box. also spool a message into the MSI log, if it is enabled.
function LogException(exc) {
var record = Session.Installer.CreateRecord(0);
record.StringData(0) = "CustomAction: Exception: 0x" + decimalToHexString(exc.number) + " : " + exc.message;
Session.Message(MsgKind.Error + Icons.Critical + Buttons.btnOkOnly, record);
}
// spool an informational message into the MSI log, if it is enabled.
function LogMessage(msg) {
var record = Session.Installer.CreateRecord(0);
record.StringData(0) = "CustomAction:: " + msg;
Session.Message(MsgKind.Log, record);
}
// popup a msgbox
function AlertUser(msg) {
var record = Session.Installer.CreateRecord(0);
record.StringData(0) = msg;
Session.Message(MsgKind.User + Icons.Information + Buttons.btnOkOnly, record);
}
// Format a number as hex. Quantities over 7ffffff will be displayed properly.
function decimalToHexString(number) {
if (number < 0)
number = 0xFFFFFFFF + number + 1;
return number.toString(16).toUpperCase();
}

Related

JSON store hangs while retrieving data

We have observed that at certain times accessing the JSONStore API's hangs for long time, to make it work we have to call the function again or app has to be taken to background & bring to foreground again.
NOTE : when application faces this issue, behaviour is same until we reinstall the app or reboot the device.
There doesn't appear to be any proper scenarios for this, we have searched many articles but did not find any solution, any solutions are welcome.
We observed this issue on Android devices like S5 and S4.
Here is my code Snippet:
function getWidgets(w_id, getWidgetsSuccessCallback, getWidgetsFailureCallback) {
var query = { user_id : w_id };
var options = {};
WL.JSONStore.get(StorageCollections.widgets).find(query, options)
.then(function(arrayResults) {
var count = arrayResults.length;
Logger.debug("getWidgets: success, count: " + count);
...
getWidgetsSuccessCallback(widgets);
})
.fail(function(errorObject) {
Logger.error("getWidgets: failed, error: " + JSON.stringify(errorObject));
getWidgetsFailureCallback(errorObject);
});}
Logs when everything works fine http://pastebin.com/NVP8ycTG
Logs when accessing JSON store hangs, it will work only when app taken to background & bring back to foreground again http://pastebin.com/eYzx57qC
JSON store is initialised as below
var collections = {
// User
user: {
searchFields: {
user_id : 'string',
user_name : 'string',
first_name : 'string',
last_name : 'string',
}
}
}};
// Storage encryption
var options = {};
if (key) {
options.password = key;
options.localKeyGen = true;
}
// Open the collection
var promise = WL.JSONStore.init(collections, options)
.then(function() {
Logger.debug("initializeAppStorage: " + JSON.stringify(collections) + " completed");
initAppStorageSuccessCallback(true);
return true;
})
// Handle failure
.fail(function(errorObject) {
Logger.error("initializeAppStorage: failed, error: " + errorObject.toString());
initAppStorageFailureCallback(errorObject.toString());
return false;
});
return promise;
Thanks.
Try this one :
function getWidgets(w_id, getWidgetsSuccessCallback, getWidgetsFailureCallback) {
var query = { key : w_id };
var options = {};
WL.JSONStore.get(StorageCollections.widgets).find(query, options)
.then(function(arrayResults) {
var count = arrayResults.length;
Logger.debug("getWidgets: success, count: " + count);
...
getWidgetsSuccessCallback(widgets);
})
.fail(function(errorObject) {
Logger.error("getWidgets: failed, error: " + JSON.stringify(errorObject));
getWidgetsFailureCallback(errorObject);
});}

Win 8 Apps : saving and retrieving data in roamingfolder

I'm trying to store few user data into a roamingFolder method/property of Windows Storage in an app using JavaScript. I'm following a sample code from the Dev Center, but no success. My code snippet is as follows : (OR SkyDrive link for the full project : https://skydrive.live.com/redir?resid=F4CAEFCD620982EB!105&authkey=!AE-ziM-BLJuYj7A )
filesReadCounter: function() {
roamingFolder.getFileAsync(filename)
.then(function (filename) {
return Windows.Storage.FileIO.readTextAsync(filename);
}).done(function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// getFileAsync or readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
filesDisplayOutput: function () {
this.filesReadCounter();
}
I'm calling filesDisplayOutput function inside ready method of navigator template's item.js file, to retrieve last session's data. But it always shows blank. I want to save upto 5 data a user may need to save.
I had some trouble running your code as is, but that's tangential to the question. Bottom line, you're not actually reading the file. Note this code, there's no then or done to execute when the promise is fulfilled.
return Windows.Storage.FileIO.readTextAsync(filename);
I hacked this in your example solution and it's working... typical caveats of this is not production code :)
filesReadCounter: function () {
roamingFolder.getFileAsync(filename).then(
function (filename) {
Windows.Storage.FileIO.readTextAsync(filename).done(
function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
function () {
// getFileAsync failed
})
},

Custom data source with WinJS?

I am currently implementing a custom data source in a Windows8 application. However, I got some trouble with it: no data is displayed.
First, here is the code:
var dataArray = [
{ title: "Basic banana", text: "Low-fat frozen yogurt", picture: "images/60banana.png" },
// Other data taken from Windows8 ListView quick start
{ title: "Succulent strawberry", text: "Sorbet", picture: "images/60strawberry.png" }
];
var searchAdDataAdapter = WinJS.Class.define(
function () {}, // Constructor
{
itemsFromIndex: function (requestIndex, countBefore, countAfter) {
var that = this;
if (requestIndex >= that._maxCount) {
return WinJS.Promise.wrapError(new WinJS.ErrorFromName(UI.FetchError.doesNotExist));
}
var fetchSize, fetchIndex;
// See which side of the requestIndex is the overlap.
if (countBefore > countAfter) {
// Limit the overlap
countAfter = Math.min(countAfter, 10);
// Bound the request size based on the minimum and maximum sizes.
var fetchBefore = Math.max(
Math.min(countBefore, that._maxPageSize - (countAfter + 1)),
that._minPageSize - (countAfter + 1)
);
fetchSize = fetchBefore + countAfter + 1;
fetchIndex = requestIndex - fetchBefore;
} else {
countBefore = Math.min(countBefore, 10);
var fetchAfter = Math.max(Math.min(countAfter, that._maxPageSize - (countBefore + 1)), that._minPageSize - (countBefore + 1));
fetchSize = countBefore + fetchAfter + 1;
fetchIndex = requestIndex - countBefore;
}
// Create an array of IItem objects:
// results =[{ key: key1, data : { field1: value, field2: value, ... }}, { key: key2, data : {...}}, ...];
for (var i = 0, itemsLength = dataArray.length ; i < itemsLength ; i++) {
var dataItem = dataArray[i];
results.push({
key: (fetchIndex + i).toString(),
data: dataArray[i]
});
}
// Get the count.
count = dataArray.length;
return {
items: results, // The array of items.
offset: requestIndex - fetchIndex, // The index of the requested item in the items array.
totalCount: count
};
},
getCount: function () {
return dataArray.length;
}
}
);
var searchAdDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function () {
this._baseDataSourceConstructor(new searchAdDataAdapter());
});
// Create a namespace to make the data publicly
// accessible.
var publicMembers = {
itemList: new searchAdDataSource()
};
WinJS.Namespace.define("DataExample", publicMembers);
I know the code is a little bit long, but the major part of it is taken from official Microsoft custom data source quick start.
I tried to debug it, but it seems the code contained in itemFromIndex is never used (my breakpoint is never reached).
The HTML code is:
<div id="basicListView" data-win-control="WinJS.UI.ListView"
data-win-options="{itemDataSource : DataExample.itemList.dataSource}">
</div>
I do not use any template for the moment, to simplify the code as more as I can. Data are normally displayed in text this way (but nothing appears).
Have one of this great community any idea?
Furthermore, I do not understand the countBefore and countAfter parameters, even with the documentation. Can somebody explain it to me with other words?
Thanks a lot! :)
Try modifying your HTML code to the following:
<div id="basicListView" data-win-control="WinJS.UI.ListView"
data-win-options="{itemDataSource : DataExample.itemList}">
</div>
No need to call the .datasource member, as you are talking to the datasource directly.

Access sd card in android for uploading a file to my php server using phonegap

I want to go to select a file from sdcard and upload it to server. is it possible to access the sdcard in android via phonegap as how we are picking a image from gallery and uploading. I went through samples but all are specifying the file name also like eg: mnt/sdcard/read.txt. But i want to goto only sdcard so that user can select his own file is it possible to do.
U can easily do that its very easy
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccessUpload, fail);
function onFileSystemSuccessUpload(fileSystem) {
// get directory entry through root and access all the folders
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(successReader,fail);
}
function successReader(entries) {
var i;
for (i=0; i<entries.length; i++) {
//alert(entries[i].name);
if(entries[i].isDirectory==true)
{
var directoryReaderIn = entries[i].createReader();
directoryReaderIn.readEntries(successReader,fail);
}
if(entries[i].isFile==true)
{
entries[i].file(uploadFile, fail);
}
}
};
function uploadFile(file) {
var target=""; //the url to upload on server
var ft = new FileTransfer(),path = "file://"+ file.fullPath,name = file.name;
ft.upload(path, target, win, fail, { fileName: name });
// var ft = new FileTransfer();
//ft.upload(file.fullPath, target, win, fail, options);
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
}

how can i check whether WCF is already registered with IIS

i am making a installer and want to check whether the WCF is already registered with IIS
Check for the .svc extension in the IIS ScriptMaps. To do that, you can use WMI from a WIX Custom Action implemented in Javascript, VBScript, or C/C++. Here's an example in Javascript:
// IsWcf.js
// ------------------------------------------------------------------
//
// detect if WCF is installed; suitable for use within a WIX Custom Action.
//
// Copyright 2010, Cheeso.
//
// Licensed under the MS Public License
// http://opensource.org/licenses/ms-pl.html
//
// To use this as a Custom Action in a WIX project, register it this way:
//
// <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
// <Fragment>
// <Binary Id="B.JavaScript" SourceFile="CustomActions.js" />
// <CustomAction Id="CA.DetectWcf"
// BinaryKey="B.JavaScript"
// JScriptCall="DetectWcf_CA"
// Execute="immediate"
// Return="check" />
// </Fragment>
// </Wix>
//
// And invoke it this way:
//
// <InstallUISequence>
// <Custom Action="CA.DetectWcf" After="CostFinalize" Overridable="yes">NOT Installed</Custom>
// </InstallUISequence>
//
//
// =======================================================
// http://msdn.microsoft.com/en-us/library/aa371254(VS.85).aspx
var MsiActionStatus = {
None : 0,
Ok : 1, // success
Cancel : 2,
Abort : 3,
Retry : 4, // aka suspend?
Ignore : 5 // skip remaining actions; this is not an error.
};
var MsgKind = {
Error : 0x01000000,
Warning : 0x02000000,
User : 0x03000000,
Log : 0x04000000
};
// Format a number as hex. Quantities over 7ffffff will be displayed properly.
function decimalToHexString(number) {
if (number < 0)
number = 0xFFFFFFFF + number + 1;
return number.toString(16).toUpperCase();
}
function LogMessage(s) {
LogMessage2(s,MsgKind.Log);
}
function LogMessage2(s,kind){
if (typeof Session !== "undefined") {
var record = Session.Installer.CreateRecord(0);
record.StringData(0) = "CustomActions: " + msg;
Session.Message(kind, record);
}
else {
WScript.echo(s);
}
}
function LogException(loc, exc) {
var s = "Exception {" + loc + "}: 0x" + decimalToHexString(exc.number) + " : " + exc.message;
if (typeof Session !== "undefined") {
var record = Session.Installer.CreateRecord(0);
record.StringData(0) = s;
Session.Message(MsgKind.Error + Icons.Critical + Buttons.btnOkOnly, record);
}
else {
LogMessage(s);
}
}
function stringEndsWith(subject, end) {
return (subject.match(end+"$") == end);
}
function DetectWcf_CA(website) {
try {
LogMessage("DetectWcf_CA() ENTER");
if (website == null) {
website = "W3SVC"; // default value
}
LogMessage("website name(" + website + ")");
var query = ( website == "W3SVC" )
? "SELECT * FROM IIsWebServiceSetting"
: "SELECT * FROM IIsWebServerSetting WHERE Name = '" + website + "'";
var iis = GetObject("winmgmts://localhost/root/MicrosoftIISv2");
var settings = iis.ExecQuery(query);
LogMessage("WMI Query results : " + typeof settings);
if ( settings == null ) {
LogMessage("Cannot query IIS.");
return MsiActionStatus.Abort;
}
var item;
if ( settings.Count != 0 ) {
for(var e = new Enumerator(settings); !e.atEnd(); e.moveNext()) {
item = e.item();
}
}
var scriptMaps = item.ScriptMaps.toArray();
var isSvcMapPresent = false;
var svcMapIndex = -1;
for (var i=0; i<scriptMaps.length; i++) {
var map = scriptMaps[i];
for(var e = new Enumerator(map.Properties_); !e.atEnd(); e.moveNext()) {
item = e.item();
if (item.Name == "Extensions" && item.Value == ".svc" && svcMapIndex == -1 ) {
svcMapIndex = i;
}
else if (i == svcMapIndex && item.Name == "ScriptProcessor" && stringEndsWith(item.Value,"aspnet_isapi.dll")) {
isSvcMapPresent = true;
}
}
}
LogMessage("DetectWcf_CA(): Is WCF Present?: " + isSvcMapPresent);
// works in WIX Custom Action only:
if (typeof Session !== "undefined") {
Session.Property("ISWCF") = (isSvcMapPresent) ? "1" : "0";
}
LogMessage("DetectWcf_CA() EXIT (Ok)");
}
catch (exc1) {
LogException("DetectWcf_CA", exc1);
return MsiActionStatus.Abort;
}
return MsiActionStatus.Ok;
}
// actually run it, only if being invoked outside of WIX
if (typeof Session == "undefined") {
DetectWcf_CA("W3SVC") ;
}
servicemodelreg.exe -lv
http://msdn.microsoft.com/en-us/library/ms732012.aspx