Chromecast Launch, what's with the DIAL parameters? Aren't I runing MY application, not some registered standard? - google-chrome

The following code displays a proper list of available chromecast devices on my network. But when I click on the links, the application never launches. There are a couple of things that I'm quite confused about that may or may not be related to this question:
If I'm making my own custom application, what's with the DIAL parameters and why do I have to pass them? I don't want to write an app for the DIAL standard... this is MY app.
Again related to the DIAL parameters, if I search for devices with any other query other than "YouTube" (a DIAL parameter), the list always comes up blank. I suppose I shouldn't care, as long as the device is listed... but again... the app won't launch.
It should be noted that my sender app is a chrome webpage.
I'm a bit confused as to where my "appid" goes int he launch parameters,'
<html data-cast-api-enabled="true">
<body>
hi!<BR/>
<script>
var cast_api, cv_activity;
if (window.cast && window.cast.isAvailable) {
// Cast is known to be available
initializeApi();
} else {
// Wait for API to post a message to us
window.addEventListener("message", function(event) {
if (event.source == window && event.data &&
event.data.source == "CastApi" &&
event.data.event == "Hello")
{
//document.write("Initialize via message.<br/>");
initializeApi();
//document.write("Api initialized via message.");
};
});
};
initializeApi = function() {
cast_api = new cast.Api();
cast_api.addReceiverListener("YouTube", onReceiverList);
};
var g_list;
onReceiverList = function(list) {
g_list = list;
// If the list is non-empty, show a widget with
// the friendly names of receivers.
// When a receiver is picked, invoke doLaunch with the receiver.
document.write("Receivers: "+list.length+"<br/>");
var t;
for(t=0;t<list.length;t++)
document.write('found:'+list[t].name+' ' +list[t].id+'<br/>');
};
onLaunch = function(activity) {
if (activity.status == "running") {
cv_activity = activity;
// update UI to reflect that the receiver has received the
// launch command and should start video playback.
} else if (activity.status == "error") {
cv_activity = null;
}
};
function launchy(idx)
{
doLaunch(g_list[idx]);
}
doLaunch = function(receiver) {
var request = new window.cast.LaunchRequest(">>>>>what REALLY goes here?<<<<<<< ", receiver);
request.parameters = "v=abcdefg";
request.description = new window.cast.LaunchDescription();
request.description.text = "My Cat Video";
request.description.url = "http://my.website.get.your.own/chomecast/test.php";
cast_api.launch(request, onLaunch);
};
stopPlayback = function() {
if (cv_activity) {
cast_api.stopActivity(cv_activity.activityId);
}
};
</script>
</body>
</html>
The part marked "what really goes here?" is the part that I THINK is wrong... I couldn't be completely wrong. My device is white listed, I have an appid (which I thought might go in that slot)... The documentation merely says ActivityType DIAL Parmeters are valid, mandatory.

The first argument to the LaunchRequest is your App ID, the one that you have received in an email as part of whitelisting process. Also, the "YouTube" in the initialize method should also be replaced with the same App ID.
I strongly suggest you look at the sample that is on GitHub for chrome sender to see how you can send a request to load a media on a cast device.

Related

How do you use getHtmlPrintDocumentSourceAsync to print in HTML/JavaScript Windows Store apps?

I am very simply trying to print some content in a Windows 10 app (Universal) using HTML and JavaScript/WinJS.
ALL of the documentation says that there is a function on MSApp called getHtmlPrintDocumentSource.
I do not have this, nor can I seem to find any relevant source to see if it may have been moved. I instead have getHtmlPrintDocumentSourceAsync. This seems to be a replacement for the former, but I cannot get it to work and there is zero documentation on it as far as I can tell.
When I run the below code (which is based on the documentation but updated to be async):
function onPrintTaskRequested(printEvent) {
var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
MSApp.getHtmlPrintDocumentSourceAsync(document)
.then(function(result) {
args.setSource(result);
});
printTask.oncompleted = onPrintTaskCompleted;
});
}
result is populated with some of the print settings as I would expect, but the content property is set to 0, which I am guessing is the problem. I can't really be sure as there is no documentation for this function. I can't even run any of the dozens of pieces of example code in the documentation using `getHtmlPrintDocumentSource' because it seemingly doesn't exist anymore.
In addition to just sending document to the Async method, I have tried a couple of different variations of creating document fragments. Same results.
Probably not terribly helpful, but the message in the Windows Print Dialog that opens when executing the above code is: "Nothing was sent to print. Open a document and print again."
Any ideas?
getHtmlPrintDocumentSource is a synchronous deprecated API in Windows 10 apps. We'll work on some of the docs left behind for Windows 8 and 8.1 to clarify that.
Check out https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/Printing/js for an example of how to use getHtmlPrintDocumentSourceAsync in JavaScript.
Here is the code:
// Needs to be invoked before calling the print API
function registerForPrintContract() {
var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
printManager.onprinttaskrequested = onPrintTaskRequested;
console.log("Print Contract registered. Use the Print button to print.", "sample", "status");
}
// Variable to hold the document source to print
var gHtmlPrintDocumentSource = null;
// Print event handler for printing via the PrintManager API.
function onPrintTaskRequested(printEvent) {
var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
args.setSource(gHtmlPrintDocumentSource);
// Register the handler for print task completion event
printTask.oncompleted = onPrintTaskCompleted;
});
}
// Print Task event handler is invoked when the print job is completed.
function onPrintTaskCompleted(printTaskCompletionEvent) {
// Notify the user about the failure
if (printTaskCompletionEvent.completion === Windows.Graphics.Printing.PrintTaskCompletion.failed) {
console.log("Failed to print.", "sample", "error");
}
}
// Executed just before printing.
var beforePrint = function () {
// Replace with code to be executed just before printing the current document:
};
// Executed immediately after printing.
var afterPrint = function () {
// Replace with code to be executed immediately after printing the current document:
};
function printButtonHandler() {
// Optionally, functions to be executed immediately before and after printing can be configured as following:
window.document.body.onbeforeprint = beforePrint;
window.document.body.onafterprint = afterPrint;
// Get document source to print
MSApp.getHtmlPrintDocumentSourceAsync(document).then(function (htmlPrintDocumentSource) {
gHtmlPrintDocumentSource = htmlPrintDocumentSource;
// If the print contract is registered, the print experience is invoked.
Windows.Graphics.Printing.PrintManager.showPrintUIAsync();
});
}

subscribeTag is not working in windowsphone8

i am implementing TAG based push notification in windowsphone8 but my app is not able to register the TAG when i execute following code.
i have tried putting subscribeTag outside onReadyToSubscribe too but i am not getting anything no success , no failure , no nothing.
if (WL.Client.Push) {
WL.Client.Push.onReadyToSubscribe = function() {
WL.Client.Push.subscribeTag("RRNEWS", {
onSuccess: function () {
alert("Tag registered");
},
onFailure: function (e) {
alert("Tag registered failed" + JSON.stringify(e));
}
});
};
}else{
alert("not supported");
}
i have register tag in application-descriptor.xml as follows
<tags>
<tag>
<name>RRNEWS</name>
<description>News</description>
</tag>
</tags>
here is the windowsphone8 entry
<windowsPhone8 version="1.0">
<uuid>6e043ba2-d382-4894-965f-47e08c24bd1e</uuid>
<pushSender/>
</windowsPhone8>
I run a tag based notification sample from Tag Notification github and deployed it on my mobile first server 6.3
when i generated the windowspone8 build and run it into a device , it shows following results
1) isPushSupported -> True
2) isSubscribed -> sample-tag1: false , sample-tag2: false
rest of the buttons are disabled
1) Subscribe to sample-tag2
2) Unsubscribe from sample-tag1
3) Unsubscribe from sample-tag2
then i tried removing disabled properties from html tag and try pressing
subscribe to sample-tag2 but nothing is happening.
Change is adapter code
function sendTagNotificationToWindows(applicationId, notificationText,notificationTags){
var notificationOptions = {};
var tags = notificationTags.split(",");
var notificationOptions = {};
var notification = WL.Server.createDefaultNotification(notificationText, 10);
notification.MPNS.raw = {};
notification.MPNS.raw.payload = {"custom":"data"} ;
notificationOptions.message = {};
notificationOptions.target = {};
notificationOptions.message.alert = JSON.stringify(notification);
notificationOptions.target.tagNames = tags;
// i have tried it with a notificationOptions too
WL.Server.sendMessage(applicationId, notification);
return {
result : "Notification sent to users subscribed to the tag(s): '" + JSON.stringify(notification) + "'."
};
}
Error
when i pass only notification param it throws following error
"Push Works Bad Request: FPWSE0005E: Invalid value was provided. Check the 'message' parameter value."
The Tag notifications sample project does not take into account the Windows Phone 8 environment. Here's what you need to add to the sample:
application-descriptor.xml
After adding the Windows Phone 8 environment, add an empty pushSender tag:
<windowsPhone8 version="1.0">
<uuid>AUTOGENERATED-GUID-NUMBER-HERE</uuid>
<pushSender/>
</windowsPhone8>
PushAdater-impl.js
Add the following to the function used for sending the notification.
For example, something like this:
function sendTagNotification(applicationId, notificationText, notificationTags) {
var tags = notificationTags.split(",");
var notificationOptions = {};
notificationOptions.message = {};
notificationOptions.message.alert = notificationText;
notificationOptions.target = {};
notificationOptions.target.tagNames = tags;
notificationOptions.settings = {};
notificationOptions.settings.mpns = {};
notificationOptions.settings.mpns.toast = {};
notificationOptions.settings.mpns.toast.text1 = "New notification";
notificationOptions.settings.mpns.toast.text2 = "You have a new notification";
notificationOptions.settings.mpns.toast.param = "/MainPage.xaml?value1=54321";
WL.Server.sendMessage(applicationId, notificationOptions);
return {
result : "Notification sent to users subscribed to the tag(s): '" + notificationTags + "'."
};
}
notificationOptions.settings.mpns.toast is needed so that when the application is closed (quit) or in the background, "toast" notification type will appear in the device.
Tapping on a toast notification launches the application. optional "param" field is used to pass on values that will be displayed once the application launches. The values set in the "param" of the toast can be retrieved natively and displayed within the application.
Additional clarifications:
When the app is open the raw notification type and the props and payload values can be seen on screen if used.
When the app is in the background and tapping the notification there are two notification types that can be receive: toast or tile. Both open the application.
When the app is in the background and tapping the app icon:
This means clicking the application tile. Application launches
When the app is closed and tapping the notification: Tapping on the toast launches the application. Tapping on the application tile launches the application.
When the app is closed and tapping the app icon: This means clicking the application tile. Application launches
I recommend to read the following MS documentation to understand what are the available notification types (Toast, Tile and Raw) and when to use them: https://msdn.microsoft.com/en-us/library/hh221549.aspx
Then search for "MPNS", "toast", "tile" or "raw" in the following user documentation topic (for onMessage) to see an example of how to set them up in your application: http://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.apiref.doc/html/refjavascript-server/html/WL.Server.html?cp=SSHS8R_7.1.0%2F10-1-0-1-6&lang=en

How to keep event handlers alive in Actionscript 3

I have a Flex app that connects to a JBoss/MS-SQL back-end. Some of our customers have a proxy server in front of their JBoss with a timeout of 90 seconds. In our application there are searches that can take up to 2-3 minutes for complex criteria. Since the proxy isn't smart enough to recognize AMF's keep alive pings for what they are the proxy sends a 503 to the client, which in Flex land becomes a "Channel Call Failed" event. In searching SO and other places, this seems to be a common problem. We can't do anything about the proxy or lengthen the timeout, the application needs to handle it.
Of course the back-end continues to process and eventually ships the results to the client. But the user gets an ugly error message and assumes the app is broke.
The solution I have settled on is to consume the CCF error and have the client continue to wait. I have managed the first part, but I can't figure out how to keep the client's handlers active to receive the data (and/or consume another timeout if necessary).
Current error handler:
private function handleSearchError(event : FaultEvent) : void {
if (event.fault.faultCode == "Channel.Call.Failed") {
event.stopImmediatePropagation(); // doesn't seem to help
return;
}
if (searchProgress != null) {
PopUpManager.removePopUp(searchProgress);
searchProgress = null;
}
etc...
}
This is the setup:
<mx:Button id="btnSearch" label="
{resourceManager.getString('recon_perspective',
'ReconPerspective.ReconView.search')}" icon="{iconSearch}"
click="handleSearch()" includeIn="search, default"/>
And:
<mx:method name="search" result="event.token.resultHandler(event);"
fault="handleSearchError(event);"/>
Kicking off the call:
var token : AsyncToken = null;
token = sMSrv.search(searchType.toString(), getSearchMode(), criteria,
smartMatchParent.isArchiveMode);
searchProgress = LoadProgress(PopUpManager.createPopUp
(FlexGlobals.topLevelApplication as DisplayObject, LoadProgress, true));
searchProgress.title = resourceManager.getString('matching', 'smartmatch.loading.trans');
searchProgress.token = token;
searchProgress.showCancelButton = true;
PopUpManager.centerPopUp(searchProgress);
token.resultHandler = handleSearchResults;
token.cancelSearch = false;
So my question is how do I keep handleSearch and handleSearchError alive to consume the events from the server?
I verified that the data comes back from the server using WebDeveloper in the browser to watch the network traffic and if you cause the app to refresh that screen, the data gets displayed.
I'm very in experienced but would this help?
private function handleSearchError(event : FaultEvent) : void {
if (event.fault.faultCode == "Channel.Call.Failed") {
event.stopImmediatePropagation(); // doesn't seem to help
if(event.isImmediatePropagationStopped(true)) {
//After stopped do something here?
}
return;
}
if (searchProgress != null) {
PopUpManager.removePopUp(searchProgress);
searchProgress = null;
}
etc...
}

Check if browser has allowed geolocation services in the past?

Currently I can determine if a user has Allowed or Denied browser location services. But how do I detect if a user's browser has previously allowed the permission? I don't want to show the "setting message" to the user again.
$("#updateLocation").click(function(e){
e.preventdefault;
navigator.geolocation.getCurrentPosition(allowLocation,deniedLocation);
return false;
});
function allowLocation(position){
// codes
}
function deniedLocation(){
// codes
}
I also facing the same problem. And, after I search and experiment I finally found the answer
You can add this JS code :
navigator.permissions.query({name:'geolocation'}).then(function(result) {
// Will return ['granted', 'prompt', 'denied']
console.log(result.state);
});
Then you can use your custom code as needed.
source : https://developer.mozilla.org/en-US/docs/Web/API/Navigator/permissions
You can do this simply by making use of HTML5 localstorage which allows you to create key-value pairs:
$("#updateLocation").click(function(e){
e.preventdefault;
if(localStorage.location == undefined){
var ip-located-geo-location = navigator.geolocation.getCurrentPosition();
// code to get ip-located geolocation
var user_defined_location = prompt("Please enter your location", ip-located-geo-location);
localStorage.location = user_defined_location;
}
else{
// use localStorage.location
}
return false;
});
If the location is not previously saved then it asks for user_defined_location, also displaying the ip-located-position, and thereby updates the localStorage, so that the next time the user doesn't have to reset the location according to his preference.

HTML5/websockets/javascript based real-time logfile viewer?

Im looking for the equivalent of "tail -f" that runs in a browser using html5 or javascript.
A solution would need a client side code written in HTML5/websockets/javascript and a back-end server side application. Im looking for one in c# but i'm willing to rewrite it from php or python.
This is the only thing that i've seen that comes close is
http://commavee.com/2007/04/13/ajax-logfile-tailer-viewer/
However, modern browsers have WebSockets which makes the problem much simpler.
http://www.websocket.org/echo.html
Ideally, I would like to have some of the capabilities of BareTail
http://www.baremetalsoft.com/baretail/
Such as Color Coding of lines, sorting and multi-file tabbing.
I have located a similar posting where someone is looking for windows based log file programs
https://stackoverflow.com/questions/113121/best-tail-log-file-visualization-freeware-tool
Anyone have any suggestions?
It is not exactly like tail but the live logs feature of https://log4sure.com does allow you to monitor your client side logs realtime. You would have to setup and do the logs appropriately as you would do for tailing, but you can see all the logs with extra information about your client, example browser, os, country etc. You can also create your own custom logs to log stuff. Checkout the demo on the site to get a better idea.
The setup code is really easy, and the best part is, its free.
// set up
var _logServer;
(function() {
var ls = document.createElement('script');
ls.type = 'text/javascript';
ls.async = true;
ls.src = 'https://log4sure.com/ScriptsExt/log4sure-0.1.min.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ls, s);
ls.onload = function() {
// use your token here.
_logServer = new LogServer("use-your-token-here");
};
})();
// example for logging text
_logServer.logText("your log message goes here.")
// example for logging error
divide = function(numerator, divisor) {
try {
if (parseFloat(value) && parseFloat(divisor)) {
throw new TypeError("Invalid input", "myfile.js", 12, {
value: value,
divisor: divisor
});
} else {
if (divisor == 0) {
throw new RangeError("Divide by 0", "myfile.js", 15, {
value: value,
divisor: divisor
});
}
}
} catch (e) {
_logServer.logError(e.name, e.message, e.stack);
}
}
// another use of logError in window.onerror
// must be careful with window.onerror as you might be overwriting some one else's window.onerror functionality
// also someone else can overwrite window.onerror.
window.onerror = function(msg, url, line, column, err) {
// may want to check if url belongs to your javascript file
var data = {
url: url,
line: line,
column: column,
}
_logServer.logError(err.name, err.message, err.stack, data);
};
//example for custom logs
var foo = "some variable value";
var bar = "another variable value";
var flag = "false";
var temp = "yet another variable value";
_logServer.log(foo, bar, flag, temp);
While I wish it had better JSON object prettification for live tailing and historical logs, the following JS client works and supports your server-side requirement also:
https://github.com/logentries/le_js/wiki/API
<html lang="en">
<head>
<title>Your page</title>
<script src="/js/le.min.js"></script>
<script>
// Set up le.js
LE.init('YOUR-LOG-TOKEN');
</script>
</head>
.....
<script>
// log something
LE.log("Hello, logger!");
</script>
Personally to get the above code to work however, I've had to add the following line of code just above LE.init('YOUR-LOG-TOKEN'):
window.LEENDPOINT = 'js.logentries.com/v1'
.. Alternatively, Loggly may be a fit as well: https://www.loggly.com/docs/javascript/