0x800a1391 - JavaScript runtime error: 'Application' is undefined - javascript

I was following the "HelloWorldWithPages" tutorial from
0x800a1391 - JavaScript runtime error: 'Application' is undefined
It occurs right here: return nav.navigate(Application.navigator.home);
Here is the full file:
default.js
// For an introduction to the Navigation template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232506
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var nav = WinJS.Navigation;
app.addEventListener("activated", function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
// Save the previous execution state.
WinJS.Application.sessionState.previousExecutionState =
args.detail.previousExecutionState;
if (app.sessionState.history) {
nav.history = app.sessionState.history;
}
args.setPromise(WinJS.UI.processAll().then(function () {
if (nav.location) {
nav.history.current.initialPlaceholder = true;
return nav.navigate(nav.location, nav.state);
} else {
return nav.navigate(Application.navigator.home);
}
}));
}
});
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. If you need to
// complete an asynchronous operation before your application is
// suspended, call args.setPromise().
app.sessionState.history = nav.history;
};
app.start();
})();
Please let me know if I need to show the code from any other file too. I am unable to understand why this problem keeps coming.

Related

Nightwatch.js function not 'closing'

I'm trying to perform a function at the beginning of my test, then the rest of the test should be executed.
This is my custom-command (named internalAdviceLinksHtml):
var solr = require('solr-client')
exports.command = function() {
this
var client = solr.createClient('solr.dev.bauerhosting.com', 8080, 'cms', '/www.parkers.co.uk');
var globalSettingsQuery = client.createQuery()
.q({TypeName:'Bauer.Parkers.GlobalSettings'})
.start(0)
.rows(10);
client.search(globalSettingsQuery,function(err,obj) {
if (err) {
console.log(err);
} else {
var myresult = (obj.response.docs[0].s_InternalAdviceLinksHtml);
console.log(myresult.length);
if (myresult.length === 0) {
console.log('content block not configured');
} else {
console.log('content block configured');
}
}
});
return this;
};
Test-file (script):
module.exports = {
'set up the solr query': function (browser) {
browser
.solr_query.global_settings.internalAdviceLinksHtml();
},
'links above footer on advice landing page displayed': function (browser) {
browser
.url(browser.launch_url + browser.globals.carAdvice)
.assert.elementPresent('section.seo-internal-links')
},
'closing the browser': function (browser) {
browser
.browserEnd();
},
};
The function works correctly (i.e. if myresult length is 0 then "content block is not configured" is displayed, etc), but the following test ("links above footer on advice landing page displayed") is never invoked.
It seems like the execution stops after the custom-command. I'm sure this will be something quite obvious to someone, but I just can't seem to see what it is.
Any help would be greatly appreciated.
Regarding your internalAdviceLinksHtml custom-command, everything looks good from my point of view (I presume that lonely this was a typo).
Your hunch is correct, it seems that the Nightwatch test-runner fails to go to the next test, which is probably due to some promise not being resolved upstream (client.search function from internalAdviceLinksHtml).
I would recommend doing a return this immediately after outputting to console (content block not configured, or content block configured) and see if that fixes the problem:
client.search(globalSettingsQuery,function(err,obj) {
if (err) {
console.log(err);
} else {
var myresult = (obj.response.docs[0].s_InternalAdviceLinksHtml);
console.log(myresult.length);
if (myresult.length === 0) {
console.log('content block not configured');
} else {
console.log('content block configured');
}
}
return this
});
Also, a few extra pointers:
make use of the Nightwatch test-hooks to make your tests easier to read/maintain & create a separation of concern (setup => before/beforeEach hooks | teardown (e.g: browser.end()) => after/afterEach hooks);
you need not do an explicit browser.end() at the end of your test case. Check this answer for more information on the matter.
Your test-file would become:
module.exports = {
// > do your setup here <
before(browser) {
browser
.solr_query.global_settings.internalAdviceLinksHtml();
},
'links above footer on advice landing page displayed': function (browser) {
browser
.url(browser.launch_url + browser.globals.carAdvice)
.assert.elementPresent('section.seo-internal-links');
},
// > do your cleanup here <
after(browser) {
browser
.browserEnd();
},
};

How can I close the client-side JavaScript 'Hub' connection in SignalR?

I have followed this tutorial.
But there is no hint how to close the Websocket connection via the HubConnection class in signalr.js-file. The file is V1.0.4.
This solution does not resolve my problem because I am using the microsofts javascript-library.
Here ist the code:
var lHubConnection = null;
var Init = function () {
// create instance
lHubConnection = new signalR.lHubConnectionBuilder().withUrl("/chatHub").build();
// receive message
lHubConnection.on("ReceiveMessage", function (pMessage) {
// show message
console.log(JSON.parse(pMessage));
});
// [...]
};
// close websocket connection
var CloseConnection = function(){
if (lHubConnection !== null && lHubConnection.connection.connectionState === 1) {
// lHubConnection.invoke("?"); ???
}
};
Here is an console output of the lHubConnection instance:
According to Microsoft the JavaScript client contains a stop function.
https://learn.microsoft.com/en-us/javascript/api/%40aspnet/signalr/hubconnection?view=signalr-js-latest#stop
In addition, you can find the .stop()-Method in the prototype of the framework:

What should I do with the redundant state of a ServiceWorker?

I gotta a companion script for a serviceworker and I'm trialling right now.
The script works like so:
((n, d) => {
if (!(n.serviceWorker && (typeof Cache !== 'undefined' && Cache.prototype.addAll))) return;
n.serviceWorker.register('/serviceworker.js', { scope: './book/' })
.then(function(reg) {
if (!n.serviceWorker.controller) return;
reg.onupdatefound = () => {
let installingWorker = reg.installing;
installingWorker.onstatechange = () => {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
updateReady(reg.waiting);
} else {
// This is the initial serviceworker…
console.log('May be skipwaiting here?');
}
break;
case 'waiting':
updateReady(reg.waiting);
break;
case 'redundant':
// Something went wrong?
console.log('[Companion] new SW could not install…')
break;
}
};
};
}).catch((err) => {
//console.log('[Companion] Something went wrong…', err);
});
function updateReady(worker) {
d.getElementById('swNotifier').classList.remove('hidden');
λ('refreshServiceWorkerButton').on('click', function(event) {
event.preventDefault();
worker.postMessage({ 'refreshServiceWorker': true } );
});
λ('cancelRefresh').on('click', function(event) {
event.preventDefault();
d.getElementById('swNotifier').classList.add('hidden');
});
}
function λ(selector) {
let self = {};
self.selector = selector;
self.element = d.getElementById(self.selector);
self.on = function(type, callback) {
self.element['on' + type] = callback;
};
return self;
}
let refreshing;
n.serviceWorker.addEventListener('controllerchange', function() {
if (refreshing) return;
window.location.reload();
refreshing = true;
});
})(navigator, document);
I'm a bit overwhelmed right now by the enormity of the service workers api and unable to "see" what one would do with reg.installing returning a redundant state?
Apologies if this seems like a dumb question but I'm new to serviceworkers.
It's kinda difficult to work out what your intent is here so I'll try and answer the question generally.
A service worker will become redundant if it fails to install or if it's superseded by a newer service worker.
What you do when this happens is up to you. What do you want to do in these cases?
Based on the definition here https://www.w3.org/TR/service-workers/#service-worker-state-attribute I am guessing just print a log in case it comes up in debugging otherwise do nothing.
You should remove any UI prompts you created that ask the user to do something in order to activate the latest service worker. And be patient a little longer.
You have 3 service workers, as you can see on the registration:
active: the one that is running
waiting: the one that was downloaded, and is ready to become active
installing: the one that we just found, being downloaded, after which it becomes waiting
When a service worker reaches #2, you may display a prompt to the user about the new version of the app being just a click away. Let's say they don't act on it.
Then you publish a new version. Your app detects the new version, and starts to download it. At this point, you have 3 service workers. The one at #2 changes to redundant. The one at #3 is not ready yet. You should remove that prompt.
Once #3 is downloaded, it takes the place of #2, and you can show that prompt again.
Write catch function to see the error. It could be SSL issue.
/* In main.js */
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js')
.then(function(registration) {
console.log("Service Worker Registered", registration);
})
.catch(function(err) {
console.log("Service Worker Failed to Register", err);
})
}

Extended execution does not seem to work in Windows 10 Universal JavaScript apps

I have a Windows 10 Universal app that's written in JavaScript. The app is a location tracker and needs to run in the background, and I am attempting to use the ExtendedExecution APIs to make that happen. I'm finding, though, that this works as advertised in a C#/XAML app, but does not work in a JavaScript app.
As an experiment, in Visual Studio 2015 I created a new C# project via File -> New -> Project -> Visual C# -> Blank App (Universal Windows) and kitted it out as follows:
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private Geolocator locator;
private ObservableCollection<string> coordinates = new ObservableCollection<string>();
private ExtendedExecutionSession session;
public MainPage()
{
this.InitializeComponent();
// Start geo locating
locator = new Geolocator();
locator.DesiredAccuracy = PositionAccuracy.High;
locator.DesiredAccuracyInMeters = 0;
locator.MovementThreshold = 0;
locator.PositionChanged += positionChanged;
coords.ItemsSource = coordinates;
// Request extended execution
RequestExtendedExecution();
}
private async void RequestExtendedExecution()
{
// Request extended execution via the ExtendedExecution API
session = new ExtendedExecutionSession();
session.Description = "Location Tracker";
session.Reason = ExtendedExecutionReason.LocationTracking;
session.Revoked += ExtendedExecutionSession_Revoked;
var result = await session.RequestExtensionAsync();
if (result == ExtendedExecutionResult.Allowed)
coordinates.Insert(0, "Extended execution SUCCESS");
else if (result == ExtendedExecutionResult.Denied)
coordinates.Insert(0, "Extended execution DENIED");
else
coordinates.Insert(0, "Extended execution unexpected return code");
}
private async void EndExtendedExecution()
{
if (session != null)
{
session.Dispose();
session = null;
}
}
private void ExtendedExecutionSession_Revoked(object sender, ExtendedExecutionRevokedEventArgs args)
{
var _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
coordinates.Insert(0, "Extended execution REVOKED: " + ((args.Reason == ExtendedExecutionRevokedReason.Resumed) ? "Resumed" : (args.Reason == ExtendedExecutionRevokedReason.SystemPolicy) ? "Resources" : "Unknown reason"));
});
EndExtendedExecution();
}
private void positionChanged(Geolocator sender, PositionChangedEventArgs args)
{
var coord = args.Position;
string position = string.Format("{0},{1}",
args.Position.Coordinate.Point.Position.Latitude,
args.Position.Coordinate.Point.Position.Longitude);
var _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
coordinates.Insert(0, position);
});
}
}
The markup is simply:
<ListView x:Name="coords" />
This absolutely works as expected. When I request the extended session, I get "Extended execution SUCCESS", when minimized the app continues to add coords to the ListView, and when returned to the foreground I get "Extended execution REVOKED: Resumed". Super duper. Back to Visual Studio 2015, I then created a new JavaScript project via File -> New -> Project -> JavaScript -> Blank App (Universal Windows) and implemented the same features as follows:
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var extendedExecution = Windows.ApplicationModel.ExtendedExecution;
var session = null;
var geolocator = null;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize your application here.
// Start geo tracking
Windows.Devices.Geolocation.Geolocator.requestAccessAsync().done(
function (accessStatus) {
switch (accessStatus) {
case Windows.Devices.Geolocation.GeolocationAccessStatus.allowed:
geolocator = new Windows.Devices.Geolocation.Geolocator();
geolocator.ReportInterval = 1000;
// Subscribe to PositionChanged event to get updated tracking positions
geolocator.addEventListener("positionchanged", function (e) {
var coord = e.position.coordinate;
log("app.onactivated: coord = " + coord.point.position.latitude + ", " + coord.point.position.longitude, false, true, false);
});
break;
case Windows.Devices.Geolocation.GeolocationAccessStatus.denied:
log("Geolocator.requestAccessAsync: Access to location is denied.", false, true, false);
break;
case Windows.Devices.Geolocation.GeolocationAccessStatus.unspecified:
log("Geolocator.requestAccessAsync: Unspecified error.", false, true, false);
break;
}
},
function (err) {
log("Geolocator.requestAccessAsync: error " + err, false, true, false);
}
);
// Request extended execution
requestExtendedExecution();
} else {
// TODO: This application was suspended and then terminated.
// To create a smooth user experience, restore application state here so that it looks like the app never stopped running.
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state that needs to persist across suspensions here.
// You might use the WinJS.Application.sessionState object, which is automatically saved and restored across suspension.
// If you need to complete an asynchronous operation before your application is suspended, call args.setPromise().
log("app.oncheckpoint: application is about to be suspended");
};
function requestExtendedExecution() {
// If we already have an extended session, close it before requesting a new one.
if (session != null) {
session.close();
session = null;
}
// Request extended execution via the ExtendedExecution API
session = new extendedExecution.ExtendedExecutionSession();
session.description = "Background location tracking";
session.reason = extendedExecution.ExtendedExecutionReason.locationTracking;
session.onrevoked = function (args) {
log("requestExtendedExecution: Background mode revoked: " + args.reason);
requestExtendedExecution();
};
session.requestExtensionAsync().done(
function success() {
log("requestExtendedExecution: Successfully enabled background mode");
},
function error(error) {
log("requestExtendedExecution: Could not enable background mode: " + error);
}
);
}
function log (text) {
var now = new Date();
var timestamp = now.toLocaleDateString() + " " + now.toLocaleTimeString();
var outputDiv = document.getElementById("divOutput");
outputDiv.innerHTML = timestamp + " " + text + "<br/>" + outputDiv.innerHTML;
}
app.start();
})();
And the markup is:
<div id="divOutput"></div>
When I request the extended session, I still get "Extended execution SUCCESS", yay, but when I minimize the app, app.oncheckpoint gets called, the app gets suspended and there is no further activity until it returns to the foreground. I have also tried requesting the extended session from within app.oncheckpoint, but that has no effect either.
Anyone have some insight into this? Thanks in advance.
It works. The actual problem is your code doesn't listen on revoke event. It should be onrevoked. :)
And there are some small problems in your code.
Try the following:
function requestExtendedExecution() {
// Request extended execution via the ExtendedExecution API
session = new extendedExecution.ExtendedExecutionSession();
session.description = "Background location tracking";
session.reason = extendedExecution.ExtendedExecutionReason.locationTracking;
session.onrevoked = function (args) {
log("requestExtendedExecution: Background mode revoked: " + args.reason);
};
session.requestExtensionAsync().done(
function success() {
log("requestExtendedExecution: Successfully enabled background mode");
},
function error(error) {
log("requestExtendedExecution: Could not enable background mode: " + error);
}
);
}

How to save an image in Windows Phone 8.1 using WinJS

I am looking to migrate my Windows 8 app to Windows Phone 8.1 using WinJS. I had used picker.pickSaveFileAsync in Windows 8 which is not supported for WP 8.1.
I had then referred the official samples from http://code.msdn.microsoft.com/windowsapps/Simple-Imaging-Sample-a2dec2b0
The Javascript version in the sample does not save on Windows Phone 8.1 when the Save As button is clicked and it returns the below error when `getFileAsync is called:
0x80004005 - JavaScript runtime error: Unspecified error
When clicked on Save, it returns a Read Only error. I had tested the sample in Lumia 520 also. I get the same error in the phone.
In Windows Phone you cannot get write access to files returned from a FileOpenPicker. You have to use a FileSavePicker to do this. With the help of a coworker I was able to get a sample working that can open and then re-save a file under a new name starting from the "Blank" Windows Phone App template
Inside of your default.html create two buttons:
<button id="choose">Choose a Photo</button>
<button id="save">Save a Photo</button>
Replace default.js with the following:
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var origFile = null;
function pickPhoto() {
var picker = new Windows.Storage.Pickers.FileOpenPicker();
var enumerator = Windows.Graphics.Imaging.BitmapDecoder.getDecoderInformationEnumerator();
enumerator.forEach(function (decoderInfo) {
decoderInfo.fileExtensions.forEach(function (fileExtension) {
picker.fileTypeFilter.append(fileExtension);
});
});
picker.pickSingleFileAndContinue();
}
function loadPhoto(file) {
origFile = file;
}
function savePhotoPicker(file) {
var picker = new Windows.Storage.Pickers.FileSavePicker();
picker.fileTypeChoices.insert("JPEG file", [".jpg"]);
picker.pickSaveFileAndContinue();
}
function savePhoto(src, dest) {
src.copyAndReplaceAsync(dest).done(function () {
console.log("success");
})
}
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
document.getElementById("choose").addEventListener("click", pickPhoto);
document.getElementById("save").addEventListener("click", savePhotoPicker);
}
if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.pickFileContinuation) {
loadPhoto(args.detail.files[0]);
}
if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) {
savePhoto(origFile, args.detail.file);
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
};
app.start();
})();
If you are creating the file yourself, make sure to set the ImageProperties for it before saving.
Sorry about the broken sample, I'll get that reported to the sample owner.

Categories

Resources