console - Dave's Blog

Search
My timeline on Mastodon

MSApp.getHtmlPrintDocumentSourceAsync - JavaScript UWP app printing

2017 Oct 11, 5:49

The documentation for printing in JavaScript UWP apps is out of date as it all references MSApp.getHtmlPrintDocumentSource but that method has been replaced by MSApp.getHtmlPrintDocumentSourceAsync since WinPhone 8.1.

Background

Previous to WinPhone 8.1 the WebView's HTML content ran on the UI thread of the app. This is troublesome for rendering arbitrary web content since in the extreme case the JavaScript of some arbitrary web page might just sit in a loop and never return control to your app's UI. With WinPhone 8.1 we added off thread WebView in which the WebView runs HTML content on a separate UI thread.

Off thread WebView required changing our MSApp.getHtmlPrintDocumentSource API which could no longer synchronously produce an HtmlPrintDocumentSource. With WebViews running on their own threads it may take some time for them to generate their print content for the HtmlPrintDocumentSource and we don't want to hang the app's UI thread in the interim. So the MSApp.getHtmlPrintDocumentSource API was replaced with MSApp.getHtmlPrintDocumentSourceAsync which returns a promise the resolved value of which is the eventual HtmlPrintDocumentSource.

Sample

However, the usage of the API is otherwise unchanged. So in sample code you see referencing MSApp.getHtmlPrintDocumentSource the sample code is still reasonable but you need to call MSApp.getHtmlPrintDocumentSourceAsync instead and wait for the promise to complete. For example the PrintManager docs has an example implementing a PrintTaskRequested event handler in a JavaScript UWP app.

    function onPrintTaskRequested(printEvent) {    
var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
args.setSource(MSApp.getHtmlPrintDocumentSource(document));
});

Instead we need to obtain a deferral in the event handler so we can asynchronously wait for getHtmlPrintDocumentSourceAsync to complete:

    function onPrintTaskRequested(printEvent) {    
var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
const deferral = args.getDeferral();
MSApp.getHtmlPrintDocumentSourceAsync(document).then(htmlPrintDocumentSource => {
args.setSource(htmlPrintDocumentSource);
deferral.complete();
}, error => {
console.error("Error: " + error.message + " " + error.stack);
deferral.complete();
});
});
PermalinkCommentsjavascript MSApp printing programming uwp webview win10 windows

Win10 UWP WebView AddWebAllowedObject details

2017 Sep 4, 3:09

The x-ms-webview HTML element has the void addWebAllowedObject(string name, any value) method and the webview XAML element has the void AddWebAllowedObject(String name, Object value) method. The object parameter is projected into the webview’s top-level HTML document’s script engine as a new property on the global object with property name set to the name parameter. It is not injected into the current document but rather it is projected during initialization of the next top-level HTML document to which the webview navigates.

Lifetime

If AddWebAllowedObject is called during a NavigationStarting event handler the object will be injected into the document resulting from the navigation corresponding to that event.

If AddWebAllowedObject is called outside of the NavigationStarting event handler it will apply to the navigation corresponding to the next explicit navigate method called on the webview or the navigation corresponding to the next NavigationStarting event handler that fires, whichever comes first.

To avoid this potential race, you should use AddWebAllowedObject in one of two ways: 1. During a NavigationStarting event handler, 2. Before calling a Navigate method and without returning to the main loop.

If called both before calling a navigate method and in the NavigationStarting event handler then the result is the aggregate of all those calls.

If called multiple times for the same document with the same name the last call wins and the previous are silently ignored.

If AddWebAllowedObject is called for a navigation and that navigation fails or redirects to a different URI, the AddWebAllowedObject call is silently ignored.

After successfully adding an object to a document, the object will no longer be projected once a navigation to a new document occurs.

WinRT access

If AddWebAllowedObject is called for a document with All WinRT access then projection will succeed and the object will be added.

If AddWebAllowedObject is called for a document which has a URI which has no declared WinRT access via ApplicationContentUriRules then Allow for web only WinRT access is given to that document.

If the document has Allow for web only WinRT access then projection will succeed only if the object’s runtimeclass has the Windows.Foundation.Metadata.AllowForWeb metadata attribute.

Object requirements

The object must implement the IAgileObject interface. Because the XAML and HTML webview elements run on ASTA view threads and the webview’s content’s JavaScript thread runs on another ASTA thread a developer should not create their non-agile runtimeclass on the view thread. To encourage end developers to do this correctly we require the object implements IAgileObject.

Property name

The name parameter must be a valid JavaScript property name, otherwise the call will fail silently. If the name is already a property name on the global object, that property is overwritten if the property is configurable. Non-configurable properties on the global object are not overwritten and the AddWebAllowedObject call fails silently. On success, the projected property is writable, configurable, and enumerable.

Errors

Some errors as described above fail silently. Other issues, such as lack of IAgileObject or lack of the AllowForWeb attribute result in an error in the JavaScript developer console.

PermalinkComments

JavaScript Types and WinRT Types

2016 Jan 21, 5:35PermalinkCommentschakra development javascript winrt

Retweet of kuvos

2015 Mar 17, 4:36
TIL: `for (i in '--') console.log(i);` nice http://www.michalpaszkiewicz.co.uk/about-js1k2015.html … :D
PermalinkComments

URI functions in Windows Store Applications

2013 Jul 25, 1:00PermalinkCommentsc# c++ javascript technical uri windows windows-runtime windows-store

Client Side Cross Domain Data YQL Hack

2012 Feb 27, 2:28

One of the more limiting issues of writing client side script in the browser is the same origin limitations of XMLHttpRequest. The latest version of all browsers support a subset of CORS to allow servers to opt-in particular resources for cross-domain access. Since IE8 there's XDomainRequest and in all other browsers (including IE10) there's XHR L2's cross-origin request features. But the vast majority of resources out on the web do not opt-in using CORS headers and so client side only web apps like a podcast player or a feed reader aren't doable.

One hack-y way around this I've found is to use YQL as a CORS proxy. YQL applies the CORS header to all its responses and among its features it allows a caller to request an arbitrary XML, HTML, or JSON resource. So my network helper script first attempts to access a URI directly using XDomainRequest if that exists and XMLHttpRequest otherwise. If that fails it then tries to use XDR or XHR to access the URI via YQL. I wrap my URIs in the following manner, where type is either "html", "xml", or "json":

        yqlRequest = function(uri, method, type, onComplete, onError) {
var yqlUri = "http://query.yahooapis.com/v1/public/yql?q=" +
encodeURIComponent("SELECT * FROM " + type + ' where url="' + encodeURIComponent(uri) + '"');

if (type == "html") {
yqlUri += encodeURIComponent(" and xpath='/*'");
}
else if (type == "json") {
yqlUri += "&callback=&format=json";
}
...

This also means I can get JSON data itself without having to go through JSONP.
PermalinkCommentsxhr javascript yql client-side technical yahoo xdr cors

CSI: Xbox - how cops perform Xbox Live stakeouts and console searches

2012 Jan 10, 2:33

Fascinating anecdotes on criminal investigations involving game consoles.

PermalinkCommentstechnical crime law video-game xbox

PowerShell Script Batch File Wrapper

2011 May 22, 7:20

I'm trying to learn and use PowerShell more, but plenty of other folks I know don't use PowerShell. To allow them to use my scripts I use the following cmd.exe batch file to make it easy to call PowerShell scripts. To use, just name the batch file name the same as the corresponding PowerShell script filename and put it in the same directory.

@echo off
if "%1"=="/?" goto help
if "%1"=="/h" goto help
if "%1"=="-?" goto help
if "%1"=="-h" goto help

%systemroot%\system32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -Command . %~dpn0.ps1 %*
goto end

:help
%systemroot%\system32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -Command help %~dpn0.ps1 -full
goto end

:end

Additionally for PowerShell scripts that modify the current working directory I use the following batch file:

@echo off
if "%1"=="/?" goto help
if "%1"=="/h" goto help
if "%1"=="-?" goto help
if "%1"=="-h" goto help

%systemroot%\system32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -Command . %~dpn0.ps1 %*;(pwd).Path 1> %temp%\%~n0.tmp 2> nul
set /p newdir=
PermalinkCommentspowershell technical programming batch file console

Console Build Window Jump Lists Tool

2010 Dec 13, 11:14

I've made two simple command line tools related to the console window and Win7 jump lists. The source is available for both but neither is much more than the sort of samples you'd find on MSDN =).

SetAppUserModelId lets you change the Application User Model ID for the current console window. The AppUserModelId is the value Win7 uses to group together icons on the task bar and is what the task bar's jump lists are associated with. The tool lets you change that as well as the icon and name that appear in the task bar for the window, and the command to launch if the user attempts to re-launch the application from its task bar icon.

SetJumpList lets you set the jump list associated with a particular AppUserModelId. You pass the AppUserModelId as the only parameter and then in its standard input you give it lines specifying items that should appear in the jump list and what to execute when those items are picked.

I put these together to make my build environment easier to deal with at work. I have to deal with multiple enlistments in many different branches and so I wrote a simple script around these two tools to group my build windows by branch name in the task bar, and to add the history of commands I've used to launch the build environment console windows to the jump list of each.

PermalinkCommentswin7 jumplist technical console

pinvoke.net: ConsoleFunctions (kernel32)

2010 Aug 14, 5:34pInvoke.net is a wiki for the C# interop declarations for various Win32 functions.PermalinkCommentspinvoke c# csharp consle api windows reference wiki technical

Hard Drive weight increasing?

2009 Jun 30, 5:50"Thank you for posting on Microsoft Answers Forum. If we understand your question correctly, there is no possible way that copying files or installing programs is increasing the weight of your laptop. Also, the same with your Xbox, downloading games from the Arcade will not increase the weight of your Game Console. Just to explain a little bit more..." lolz ensuePermalinkCommentshumor microsoft msdn harddrive technical

Nintendo GDC keynote: Wii Storage, new Zelda, world domination - Ars Technica

2009 Mar 25, 1:03Finally more storage for all those virtual console games I download: "What is going to interest gamers, however, is the expanded support for storage on the Nintendo Wii. The new update for the Wii Menu allows you to download and launch content straight from an SD card, and there is now support for SDHC cards, meaning you can cheaply add as much storage to your system as you'd like. A game was shown launching from a memory stick, with only a short loading time."PermalinkCommentsnintendo wii videogame storage

Finished First Three Zelda Games

2008 Jul 17, 4:45
Screen shot from Legend of ZeldaScreen shot from Zelda II: The Adventures of LinkScreen shot from Legend of Zelda: A Link to the Past

I want to once again profess my love for the Wii's Virtual Console. Sarah and I recently finished playing through the first three Zelda games. Although I'd played a bit of the first two I never had a Nintendo as a kid and so unlike Sarah this was my first time completely playing through Zelda I & II. What people say about Zelda II is true... its all so true. And on the flip side I have fond memories of beating the third Zelda game which Sarah hadn't played.

In hilarious Zelda related news, a friend from work's husband posted the following blog post concerning their son named Link.

PermalinkCommentszelda link video-games nontechnical wii

Finished Paper Mario Games

2008 May 12, 4:05
Super Paper MarioPaper Mario: The Thousand-Year DoorPaper Mario Title Screen

Sarah and I have finished playing through the games "Paper Mario", "Paper Mario: The Thousand-Year Door", and "Super Paper Mario" last week (including the various Pits of 100 Trials). We played them all on the Wii, because even though Super Paper Mario was the only one released explicitly for that platform, Wii maintains compatibility with Game Cube games such as Thousand-Year Door and Paper Mario although originally released for the Nintendo 64 is now available as a pay for download game on the Wii's Virtual Console. So, yay for Nintendo!

I think my favorite of the three is Thousand-Year Door mostly because of the RPG attack system. In Thousand-Year Door and Paper Mario when you come into contact with an enemy you go into an RPG style attack system where you take turns selecting actions. In Super Paper Mario you still have hit points and such, but you don't go into a turn based RPG style attack system, rather you do the regular Mario jumping on bad guys thing (or hitting them with a mallet etc...). Thousand-Year Door and Paper Mario are very similar in terms of game play but Thousand-Year Door looks very pretty and has made improvements to how your party-mates are handled in battle (they have HP and can fall as you would expect) and there's an audience that cheers you on during your battles.

Even if the gameplay sucked the humor throughout the series might be tempting enough. Mario's clothing and mustache are mocked throughout and standard RPG expectations are subverted. I hate to describe any of these moments for fear of ruining anything but, for instance, an optional and very difficult enemy who may only be killed after hours of work only results in one experience point, or a very intimidating enemy who you imagine you'll have to fight actually challenges you to a quiz.

Despite how I personally rank them, all the games are great and I'd recommend any of them.

PermalinkCommentsmario videogame paper mario nontechnical

XSL Transforms in JavaScript

2007 Oct 7, 4:12In a previous post I mentioned an xsltproc like js file I made. As noted in that post, on Windows you can write console script files in JavaScript, name them foo.js, and execute them from the command prompt. I later found that MSDN has an XSLT javascript sample which looks similar to mine, but I like mine better for the XSLT parameter support and having a non-ridiculous way of interpreting filenames. The code for my xsltproc.js follows. The script is very simple and demonstrates the ease with which you can manipulate these system objects and all it takes is opening up notepad.
var createNewXMLObj = function() {
   var result = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
   result.validateOnParse = false;
   result.async = false;
   return result;
}

var args = WScript.arguments;
var ofs = WScript.CreateObject("Scripting.FileSystemObject");

var xslParams = [];
var xmlStyle = null;
var xmlInput = null;
var inputFile = null;
var outputFile = null;
var error = false;

for (var idx = 0; idx < args.length && !error; ++idx)
   if (args.item(idx) == "-o") {
      if (idx + 1 < args.length) {
         outputFile = ofs.GetAbsolutePathName(args.item(idx + 1));
         ++idx;
      }
      else
         error = true;
   }
   else if (args.item(idx) == "--param" || args.item(idx) == "-param") {
      if (idx + 2 < args.length) {
         xslParams[args.item(idx + 1)] = args.item(idx + 2);
         idx += 2;
      }
      else
         error = true;
   }
   else if (xmlStyle == null) {
      xmlStyle = createNewXMLObj();
      xmlStyle.load(ofs.GetAbsolutePathName(args.item(idx)));
   }
   else if (xmlInput == null) {
      inputFile = ofs.GetAbsolutePathName(args.item(idx));
      xmlInput = createNewXMLObj();
      xmlInput.load(inputFile);
   }

if (xmlStyle == null || xmlInput == null || error) {
   WScript.Echo('Usage:\n\t"xsltproc" xsl-stylesheet input-file\n\t\t["-o" output-file] *["--param" name value]');
}
else {
   var xslt = new ActiveXObject("MSXML2.XSLTemplate.3.0");
   xslt.stylesheet = xmlStyle;
   var xslProc = xslt.createProcessor();
   xslProc.input = xmlInput;

   for (var keyVar in xslParams)
      xslProc.addParameter(keyVar, xslParams[keyVar]);

   xslProc.transform();

   if (outputFile == null)
      WScript.Echo(xslProc.output);
   else {
      var xmlOutput = createNewXMLObj();
      xmlOutput.loadXML(xslProc.output);
      xmlOutput.save(outputFile);
   }
}
PermalinkCommentsjs xml jscript windows xslt technical xsltproc wscript xsl javascript

Roommate Wedding

2007 May 5, 10:05Carissa, Elijah, and KristenCarissa and Elijah are married! Sarah and I flew to Oakland the Friday of two weeks previous (April 27th) into the Oakland Airport. We were on the same flight as Jon which was fun but we weren't seated with him. Instead I was seated between Sarah and a middle aged lady who enjoyed talking to herself. It seemed a bonus if others such as myself listened but not a prerequisite for her speaking.

Church Front Sarah and I rented a car and we drove Jon first to Hayward where he was staying then we drove to our hotel in Dublin. The car we got turned out to be a PT Cruiser which was a surprise of course but actually wasn't that bad. The power windows are controlled by the center console rather than by a switch near the windows themselves which led to several embarrassing seconds when we later tried to pay the toll for the Bay Bridge.

Carissa & Elijah's Reception HallThe next day we went to Carissa's wedding which was lovely. In a small church with white roses Carissa's mom married Carissa and Elijah. Afterward we went to the reception at the Senior Center. "Senior Center" may conjure up images of rolley charis that smell like old people but it wasn't like that at all. It appears to be a community center funded by the Senior Condos next door so it was very nice.

Carissa is the first of the college roommates to get married! I guess I'm just having trouble imagining any of us getting married...PermalinkCommentswedding friend personal california nontechnical

Trivia

2007 Apr 21, 11:38This previous Wednesday, I went to trivia at the Wilde Rover. Our team consisted of Sarah, myself, Jane, Eric, Rachel, and Ansen. Before the last round we were 16th (out of ~32) but after the final round we were 6th! The previous time Sarah played there the exact same thing happened. Of course you must be in the top five to win money (or last place who gets their money back). You could say, of those who didn't get any money we did the best! I didn't contribute too much except for spotting a street from Paris in the picture round and knowing which generation the Wii is of Nintendo home consoles. Mostly I focused on increasing our bill =)PermalinkCommentsbar game personal trivia nontechnical

RSF暫定トップ

2005 Apr 23, 3:25Sega Fantasy VI - The gaming console RPGPermalinkCommentshumor game
Older Entries Creative Commons License Some rights reserved.