Javascript - Windows Store - Forcing Mandatory Update - javascript

Javascript:
I want my Windows Store app to check for updates, especially mandatory ones, and then prompt the user to update.
I have found out this involves Windows.Services.Store, but I cannot find any javascript examples of how this is done, only the usual c#/vb ones.
Does anyone know of a code template?

I have found out this involves Windows.Services.Store, but I cannot find any javascript examples of how this is done, only the usual c#/vb ones.
I'd suppose the examples you've found are Code examples in Download and install package updates for your app. Although, these examples are written with C#, but we can convert them to JavaScript easily as most of them are Windows Runtime APIs.
Using Download and install all package updates for example, the JavaScript version would like the following:
var context = Windows.Services.Store.StoreContext.getDefault();
context.getAppAndOptionalStorePackageUpdatesAsync().then(function (updates) {
if (updates.size > 0) {
var dialog = new Windows.UI.Popups.MessageDialog("Download and install updates now? This may cause the application to exit.", "Download and Install?");
dialog.commands.append(new Windows.UI.Popups.UICommand("Yes"));
dialog.commands.append(new Windows.UI.Popups.UICommand("No"));
dialog.showAsync().then(function (command) {
if (command.label === "Yes") {
context.requestDownloadAndInstallStorePackageUpdatesAsync(updates).then(function (result) {
// TODO
}, function (error) {
//TODO
}, function (progress) {
var downloadProgressBar = document.getElementById("downloadProgressBar");
downloadProgressBar.value = progress.packageDownloadProgress;
});
}
});
}
});
Two major differences between C# and JavaScript version here are casing conventions and asynchronous methods. For more info, please see Using the Windows Runtime in JavaScript.

Related

Should I keep console statements in JavaScript application?

I am using console.log() and console.dir() statements in 3 places in my 780 lines of code JS script. But all of them are useful for debugging and discovering problems that might appear when using the application.
I have a function that prints internal application's state i.e current value of variables:
printData: function () {
var props = {
operation: this.operation,
operand: this.operand,
operandStr: this.operandStr,
memory: this.memory,
result: this.result,
digitsField: this.digitsField,
dgField: this.dgField,
operationField: this.operationField,
opField: this.opField
};
console.dir(props);
}
I also have a list of immutable "contants" which are hidden with closure but I can print them with accessor method called list(); in console.
Something like this:
list: function () {
var index = 0,
newStr = "",
constant = '';
for (constant in constants) {
if (constants.hasOwnProperty(constant)) {
index = constant.indexOf('_');
newStr = constant.substr(index + 1);
console.log(newStr + ": " + constants[constant]);
}
}
}
The third place where I use console in debugging purposes is in my init(); function, where I print exception error if it happens.
init: function (config) {
try {
this.memoryLabelField = global.getElementById(MEMORY_LABEL);
this.digitsField = global.getElementById(DIGITS_FIELD);
this.digitsField.value = '0';
this.operationField = global.getElementById(OPERATION_FIELD);
this.operationField.value = '';
return this;
} catch (error) {
console.log(error.message);
return error.message;
}
}
As my question states, should I keep these console statements in production code?
But they come very useful for later maintenance of the code.
Let me know your thoughts.
Since these are not persistent logs you won't get much benefit out of them. Also it runs on every individuals machine since everyone has their own copy of the program. If you really need it, it would be better to have a variable that can toggle this feature. Espcially if you are targetting to debug a whole lot of pre-determined stuffs.
Client Side issues needs to be debugged slightly different from Server Side. Everyone has their own copy of the program. Browser-JS is run on client side you open the browser and all code that you wrote is with you in a full blown repl and debugging is easy compared to Server side where most likely you wouldn't have access to that system. It is so flexible that you could just override it when you are checking something in production right from your own browser without affecting anyone. Just override it with those console statements and debug the issue.
Its a good idea to have logs in Server side programming. It gives a lot of useful information and is persistent.
As said above, debugging code should not be present on a production environment.
However, if you plan to keep it anyway, keep in mind that all browsers do not support it.
So you may check its availability and provide a fallback:
if (typeof window.console === 'undefined')
{
window.console = {};
}
if (typeof window.console.log === 'undefined')
{
window.console.log = function() { };
}
According to mozilla developer network
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
Leaving console.log() on production sites can cause issues since it is not supported by older browsers. It is most likely to throw exceptions in that case.
It's historically considered a bad-practice by Javascript programmers. At the start of the eons, some browsers didn't have support for it (IE8 or less for example). Other thing to take in mind is that you are making your code larger to download.

Ace Editor and meteor for collaborative code editing: Observe hangs app

I am trying to make a basic collaborative code editor in Meteor using the Ace editor.
The javascript is as follows:
var file
Meteor.startup(function(){
Session.set("file", "fileID");
var query = Files.find({_id : Session.get("fileId")});
var handle = query.observe({
changed : function(newDoc, oldDoc) {
if(editor !== undefined){
console.log("doc was changed from ", oldDoc.contents, "to ", newDoc.contents);
editor.setValue(newDoc.contents);
}
handle.stop();
}
});
editor.getSession().on('change', function(e) {
// update the File collection
if(Session.get('file')) {
Files.update({_id: Session.get("file")},
{ $set :
{
contents : editor.getValue()
}
});
}
});
});
The editor is able to update the database without much ado, however, the query that handles observing changes and setting the document to a new value basically just hangs and doesn't do anything.
What's the issue? Or in general what's a better way to solve this problem (of making the ace editor collaborative using meteor...assuming I want to code it myself..and not use meteorite or something)
Thanks!
Using the ace editor directly with Meteor will result in laggy operations and clunky interactions between users unless you write and debug a whole lot of code.
Another approach is to attach the ShareJS stack to Meteor, because it integrates really well with ace. In fact, I ended up doing this after looking at other ways to do collaborative editing in Meteor:
https://github.com/mizzao/meteor-sharejs
There is an (out-of-date) demo here: http://documents.meteor.com

Preloading of Javascript Files

Working on a small engine to run my HTML5 test games, using it as a great way to get deeper into Javascript and have fun at the same time. Succeeding, btw.
However, I just found this cool little script called PreloadJS ( http://www.createjs.com/#!/PreloadJS ). Also using John Resig's classical inheritence class JS. Very cool, enjoying it. I am attempting to use PreloadJS to pull in all of my engine files...but I seem to be having an issue. Here's the code I'm using (keeping it simple on purpose):
var ScriptLoader = Class.extend({ // Want to add functionality to this to allow PHP or inline loading...perhaps later
init: function() {
this.fileList = [
'Empty.js',
'./engine/Scene.js'
];
this.preload;
},
loadProjectSource: function(directory) {
if (this.preload != null) { this.preload.close(); }
this.preload = new createjs.LoadQueue();
this.preload.addEventListener("fileload", this.fileLoaded);
this.preload.addEventListener("error", this.fileError);
this.preload.setMaxConnections(5);
this.loadAnother();
},
loadAnother: function() {
var item = this.fileList.shift();
if(this.fileList.length != 0) {
this.preload.loadFile(item);
}
},
fileLoaded: function(e) {
debug('Loaded ' + e.item.src);
this.loadAnother();
},
fileError: function(e) {
debug('Error ' + e.item.src);
}
}
From my engine instantiation, I'm calling ScriptLoader.loadProjectSource. It's doing nothing but throwing errors, and the documentation on error handling (and loading JS files in general...) is very sparse on the PreloadJS site. It focuses on preloading images (which, admittedly, looks great). Anyway, so yea, it's throwing errors. And it can't be the files, as I tried loading a completely blank JS file (as you can see). Still throwing an error on the Empty.js file.
Annoyed :) Thanks in advance.
The PreloadJS script uses XHR where available with browser support. In order for this to function correctly with locally-hosted scripts, a local webserver must be running. Upon activating my local webserver and attempting the same operation, full success.

Javascript Build Tools To Toggle Urls/Variables Between Production/Deployment

I am beginning my first big javascript project! I had a question about deployment. I am using ajax calls to a webservice. To set this up I have a static JS file with code like:
var API_URL_ROOT = 'http://api.example.com/';
var IN_DEVELOPMENT = True;
if (IN_DEVELOPMENT) {
API_URL_ROOT = 'http://localhost.com/api';
}
$.get(API_URL_ROOT)
I am using python/fabric to deploy. I was wondering if there were any prebuilt tools for handling the static analysis/manipulation of the javascript files., Right now it leaves toggling up to the commiters
I was planning on a deployment process like:
issue deploy command
"build" JS, by setting all values to production values (ie. IN_DEVELOPMENT = False)
Minify JS
Deploy code to production servers
I was thinking of just using sed or something to do the IN_DEVELPMENT = False replacement. I have looked at some of the popular minification tools and none seem to offer this sort of functionality.
I would assume that this is a pretty common problem for applications. How is it usually handled? Any help would be appreciated. Thank you
I recently read an article on hackernews from mozilla:
In the Mozilla Persona code base, we frequently expose difficult to
test private functions to the public interface, clearly marking the
extra functions as part of a test API. While other developers are
still able to call these private functions, the author’s intentions
are clear.
...
publicFunction: function() {
return "publicFunction can be invoked externally but "
+ privateFunction();
}
// BEGIN TESTING API
,
privateFunction: privateFunction
// END TESTING API
};
// privateFunction is now accessible via the TESTING API
function privateFunction() {
...
Code between the // BEGIN TESTING API and //END TESTING API
pseudo-markers can be removed for production during the build process.
So other companies are definitely doing this. Are there premade tools to facilitate the JS build proccess that can remove this code? I glanced at a number of their projects on github and didn't see any. Thank you
We are using dojo
And in dojo you can use conditional exclusions for the build version of your js in order to exclude parts of your code that you would not want in your build js. Hope this helps.
eg:
var API_URL_ROOT = 'http://api.example.com/';
//>>excludeStart("dev",!pragmas.dev);
var IN_DEVELOPMENT = True;
//>>excludeEnd("dev");
if (IN_DEVELOPMENT) {
API_URL_ROOT = 'http://localhost.com/api';
}
$.get(API_URL_ROOT)

which control flow library works with google closure library?

there are several js libraries available for flow control.
though when working with the closure compiler the ones i looked at yet do not work well with the compiler in advanced mode.
is there any closure compatible flow control library?
I am mostly interested in waiting on multiple results without complicating the code more than necessary.
What i want to archive is to reduce loading time on user actions.
For one action of the user multiple requests have to be done to the backend. To keep the code maintainable, at the moment, i do one request at a time and handle potential errors after each step.
What i want to archive is that i can just fire nondepended requests together without complicating the error handling more than necessary.
I like the syntax of flow js:
var auth = flow.define(
function(username, password) {
sys.puts("trying " + username + ", " + password);
this.password = password;
keystore.get('userId:' + username, this);
},function(err, userId) {
keystore.get('user:' + userId + ':password', this);
},function(err, passwordInDb) {
if (passwordInDb == this.password) {
sys.puts("Authenticated!");
}
else {
sys.puts("Failed Authentication!");
}
}
)
It also allows to spawn multiple async operations and collect them.
Though if you need any state between callbacks the state is stored like "this.password" above.
as the containing scope is not typed the closure compiler will not be able to rename it consistently (from my understanding) when in ADVANCED mode.
So i need an alternative which has a typed container object that is pushed as a parameter (or this) through each function.
Can you use goog.async.Deferred from Closure Library? It manage async and sync workflow.
Generally, you can use any library with Closure Compiler's advanced mode by creating an extern file for the library and loading the code separately (or concatenating the library after compilation of your code).
Ok i've found a solution.
When i create a typed container object and pass it to each of the functions with goog.bind it works.
A very tiny flow control lib for Closure Library i've written is ready.js.
As per the description:
Watches over multiple async operations and triggers listeners when all or some are complete.
It's worth a look

Categories

Resources