reference - 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

Parsing WinMD with .NET reflection APIs

2016 Nov 2, 6:13

Parsing WinMD files, the containers of WinRT API metadata, is relatively simple using the appropriate .NET reflection APIs. However, figuring out which reflection APIs to use is not obvious. I've got a completed C sharp class parsing WinMD files that you can check out for reference.

Use System.Reflection.Assembly.ReflectionOnlyLoad to load the WinMD file. Don't use the normal load methods because the WinMD files contain only metadata. This will load up info about APIs defined in that WinMD, but any references to types outside of that WinMD including types found in the normal OS system WinMD files must be resolved by the app code via the System.Reflection.InteropServices.WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve event.

In this event handler you must resolve the unknown namespace reference by adding an assembly to the NamespaceResolveEventArgs's ResolvedAssemblies property. If you're only interested in OS system WinMD files you can use System.Reflection.InteropServices.WindowsRuntimeMetadata.ResolveNamespace to turn a namespace into the expected OS system WinMD path and turn that path into an assembly with ReflectionOnlyLoad.

PermalinkComments.net code programming winmd winrt

JavaScript Types and WinRT Types

2016 Jan 21, 5:35

MSDN covers the topic of JavaScript and WinRT type conversions provided by Chakra (JavaScript Representation of Windows Runtime Types and Considerations when Using the Windows Runtime API), but for the questions I get about it I’ll try to lay out some specifics of that discussion more plainly. I’ve made a TL;DR JavaScript types and WinRT types summary table.

WinRT Conversion JavaScript
Struct ↔️ JavaScript object with matching property names
Class or interface instance JavaScript object with matching property names
Windows.Foundation.Collections.IPropertySet JavaScript object with arbitrary property names
Any DOM object

Chakra, the JavaScript engine powering the Edge browser and JavaScript Windows Store apps, does the work to project WinRT into JavaScript. It is responsible for, among other things, converting back and forth between JavaScript types and WinRT types. Some basics are intuitive, like a JavaScript string is converted back and forth with WinRT’s string representation. For other basic types check out the MSDN links at the top of the page. For structs, interface instances, class instances, and objects things are more complicated.

A struct, class instance, or interface instance in WinRT is projected into JavaScript as a JavaScript object with corresponding property names and values. This JavaScript object representation of a WinRT type can be passed into other WinRT APIs that take the same underlying type as a parameter. This JavaScript object is special in that Chakra keeps a reference to the underlying WinRT object and so it can be reused with other WinRT APIs.

However, if you start with plain JavaScript objects and want to interact with WinRT APIs that take non-basic WinRT types, your options are less plentiful. You can use a plain JavaScript object as a WinRT struct, so long as the property names on the JavaScript object match the WinRT struct’s. Chakra will implicitly create an instance of the WinRT struct for you when you call a WinRT method that takes that WinRT struct as a parameter and fill in the WinRT struct’s values with the values from the corresponding properties on your JavaScript object.

// C# WinRT component
public struct ExampleStruct
{
public string String;
public int Int;
}

public sealed class ExampleStructContainer
{
ExampleStruct value;
public void Set(ExampleStruct value)
{
this.value = value;
}

public ExampleStruct Get()
{
return this.value;
}
}

// JS code
var structContainer = new ExampleWinRTComponent.ExampleNamespace.ExampleStructContainer();
structContainer.set({ string: "abc", int: 123 });
console.log("structContainer.get(): " + JSON.stringify(structContainer.get()));
// structContainer.get(): {"string":"abc","int":123}

You cannot have a plain JavaScript object and use it as a WinRT class instance or WinRT interface instance. Chakra does not provide such a conversion even with ES6 classes.

You cannot take a JavaScript object with arbitrary property names that are unknown at compile time and don’t correspond to a specific WinRT struct and pass that into a WinRT method. If you need to do this, you have to write additional JavaScript code to explicitly convert your arbitrary JavaScript object into an array of property name and value pairs or something else that could be represented in WinRT.

However, the other direction you can do. An instance of a Windows.Foundation.Collections.IPropertySet implementation in WinRT is projected into JavaScript as a JavaScript object with property names and values corresponding to the key and value pairs in the IPropertySet. In this way you can project a WinRT object as a JavaScript object with arbitrary property names and types. But again, the reverse is not possible. Chakra will not convert an arbitrary JavaScript object into an IPropertySet.

// C# WinRT component
public sealed class PropertySetContainer
{
private Windows.Foundation.Collections.IPropertySet otherValue = null;

public Windows.Foundation.Collections.IPropertySet other
{
get
{
return otherValue;
}
set
{
otherValue = value;
}
}
}

public sealed class PropertySet : Windows.Foundation.Collections.IPropertySet
{
private IDictionary map = new Dictionary();

public PropertySet()
{
map.Add("abc", "def");
map.Add("ghi", "jkl");
map.Add("mno", "pqr");
}
// ... rest of PropertySet implementation is simple wrapper around the map member.


// JS code
var propertySet = new ExampleWinRTComponent.ExampleNamespace.PropertySet();
console.log("propertySet: " + JSON.stringify(propertySet));
// propertySet: {"abc":"def","ghi":"jkl","mno":"pqr"}

var propertySetContainer = new ExampleWinRTComponent.ExampleNamespace.PropertySetContainer();
propertySetContainer.other = propertySet;
console.log("propertySetContainer.other: " + JSON.stringify(propertySetContainer.other));
// propertySetContainer.other: {"abc":"def","ghi":"jkl","mno":"pqr"}

try {
propertySetContainer.other = { "123": "456", "789": "012" };
}
catch (e) {
console.error("Error setting propertySetContainer.other: " + e);
// Error setting propertySetContainer.other: TypeError: Type mismatch
}

There’s also no way to implicitly convert a DOM object into a WinRT type. If you want to write third party WinRT code that interacts with the DOM, you must do so indirectly and explicitly in JavaScript code that is interacting with your third party WinRT. You’ll have to extract the information you want from your DOM objects to pass into WinRT methods and similarly have to pass messages out from WinRT that say what actions the JavaScript should perform on the DOM.

PermalinkCommentschakra development javascript winrt

Debugging anecdote - the color transparent black breaks accessibility

2014 May 22, 10:36

Some time back while I was working on getting the Javascript Windows Store app platform running on Windows Phone (now available on the last Windows Phone release!) I had an interesting bug that in retrospect is amusing.

I had just finished a work item to get accessibility working for JS WinPhone apps when I got a new bug: With some set of JS apps, accessibility appeared to be totally broken. At that time in development the only mechanism we had to test accessibility was a test tool that runs on the PC, connects to the phone, and dumps out the accessibility tree of whatever app is running on the phone. In this bug, the tool would spin for a while and then timeout with an error and no accessibility information.

My first thought was this was an issue in my new accessibility code. However, debugging with breakpoints on my code I could see none of my code was run nor the code that should call it. The code that called that code was a more generic messaging system that hit my breakpoints constantly.

Rather than trying to work backward from the failure point, I decided to try and narrow down the repro and work forwards from there. One thing all the apps with the bug had in common was their usage of WinJS, but not all WinJS apps demonstrated the issue. Using a binary search approach on one such app I removed unrelated app code until all that was left was the app's usage of the WinJS AppBar and the bug still occurred. I replaced the WinJS AppBar usage with direct usage of the underlying AppBar WinRT APIs and continued.

Only some calls to the AppBar WinRT object produced the issue:

        var appBar = Windows.UI.WebUI.Core.WebUICommandBar.getForCurrentView(); 
// appBar.opacity = 1;
// appBar.closeDisplayMode = Windows.UI.WebUI.Core.WebUICommandBarClosedDisplayMode.default;
appBar.backgroundColor = Windows.UI.Colors.white; // Bug!
Just setting the background color appeared to cause the issue and I didn't even have to display the AppBar. Through additional trial and error I was blown away to discover that some colors I would set caused the issue and other colors did not. Black wouldn't cause the issue but transparent black would. So would aqua but not white.

I eventually realized that predefined WinRT color values like Windows.UI.Colors.aqua would cause the issue while JS literal based colors didn't cause the issue (Windows.UI.Color is a WinRT struct which projects in JS as a JS literal object with the struct members as JS object properties so its easy to write something like {r: 0, g: 0, b: 0, a: 0} to make a color) and I had been mixing both in my tests without realizing there would be a difference. I debugged into the backgroundColor property setter that consumed the WinRT color struct to see what was different between Windows.UI.Colors.black and {a: 1, r: 0, g: 0, b: 0} and found the two structs to be byte wise exactly the same.

On a hunch I tried my test app with only a reference to the color and otherwise no interaction with the AppBar and not doing anything with the actual reference to the color: Windows.UI.Colors.black;. This too caused the issue. I knew that the implementation for these WinRT const values live in a DLL and guessed that something in the code to create these predefined colors was causing the issue. I debugged in and no luck. Now I also have experienced crusty code that would do exciting things in its DllMain, the function that's called when a DLL is loaded into the process so I tried modifying my C++ code to simply LoadLibrary the DLL containing the WinRT color definition, windows.ui.xaml.dll and found the bug still occurred! A short lived moment of relief as the world seemed to make sense again.

Debugging into DllMain nothing interesting happened. There were interesting calls in there to be sure, but all of them behind conditions that were false. I was again stumped. On another hunch I tried renaming the DLL and only LoadLibrary'ing it and the bug went away. I took a different DLL renamed it windows.ui.xaml.dll and tried LoadLibrary'ing that and the bug came back. Just the name of the DLL was causing the issue.

I searched for the DLL name in our source code index and found hits in the accessibility tool. Grinning I opened the source to find that the accessibility tool's phone side service was trying to determine if a process belonged to a XAML app or not because XAML apps had a different accessibility contract. It did this by checking to see if windows.ui.xaml.dll was loaded in the target process.

At this point I got to fix my main issue and open several new bugs for the variety of problems I had just run into. This is a how to on writing software that is difficult to debug.

PermalinkCommentsbug debug javascript JS technical windows winrt

The Fiddler Book: "Debugging with Fiddler: The official reference from the developer of Fiddler"

2012 Jun 23, 9:19

THE Fiddler Book straight from the source, EricLaw - the developer of Fiddler!

Fiddler is a wonderful tool with never ending extensibility. With this book I shall master it!

PermalinkCommentstechnical programming book ericlaw fiddler http

HTTP Compression Documentation Reference

2012 Jun 13, 3:08
There's a lot of name reuse in HTTP compression so I've made the following to help myself keep it straight.
HTTP Content Coding Token gzip deflate compress
An encoding format produced by the file compression program "gzip" (GNU zip) The "zlib" format as described in RFC 1950. The encoding format produced by the common UNIX file compression program "compress".
Data Format GZIP file format ZLIB Compressed Data Format The compress program's file format
Compression Method Deflate compression method LZW
Deflate consists of LZ77 and Huffman coding

Compress doesn't seem to be supported by popular current browsers, possibly due to its past with patents.

Deflate isn't done correctly all the time. Some servers would send the deflate data format instead of the zlib data format and at least some versions of Internet Explorer expect deflate data format instead of zlib data format.

PermalinkCommentscompress compression deflate gzip http http-header technical zlib

Stuxnet Explained - Obama Order Sped Up Wave of Cyberattacks Against Iran

2012 Jun 1, 4:57

From his first months in office, President Obamasecretly ordered increasingly sophisticated attacks on the computer systems that run Iran’s main nuclear enrichment facilities, significantly expanding America’s first sustained use of cyberweapons, according to participants in the program.

PermalinkCommentssecurity politics iran nuclear virus

Vim anti-patterns (geek.nz)

2012 Feb 7, 11:58

Things you do in VIM but faster with more obscure and specific commands.

PermalinkCommentstechnica vi vim reference howto

JavaScript Array methods in the latest browsers

2011 Dec 3, 6:46

Cool and (relatively) new methods on the JavaScript Array object are here in the most recent versions of your favorite browser! More about them on ECMAScript5, MSDN, the IE blog, or Mozilla's documentation. Here's the list that's got me excited:

some & every
Does your callback function return true for any (some) or all (every) of the array's elements?
filter
Filters out elements for which your callback function returns false (in a new copy of the Array).
map
Each element is replaced with the result of it run through your callback function (in a new copy of the Array).
reduce & reduceRight
Your callback is called on each element in the array in sequence (from start to finish in reduce and from finish to start in reduceRight) with the result of the previous callback call passed to the next. Reduce your array to a single value aggregated in any manner you like via your callback function.
forEach
Simply calls your callback passing in each element of your array in turn. I have vague performance concerns as compared to using a normal for loop.
indexOf & lastIndexOf
Finds the first or last (respectively) element in the array that matches the provided value via strict equality operator and returns the index of that element or -1 if there is no such element. Surprisingly, no custom comparison callback method mechanism is provided.
PermalinkCommentsjavascript array technical programming

"JSON Reference" - Paul Bryan, Kris Zyp

2011 Nov 14, 8:24PermalinkCommentstechnical json ietf

Obscuring Location

2011 Jul 1, 10:17"A method for obscuring location information is described. Both static and changing location information can be obscured. A single distance measure is input to the process; this parameter controls the precision of location information that can be extracted by a recipient."PermalinkCommentsgeoloc geolocation technical rfc standard reference

draft-ietf-websec-origin-01 - The Web Origin Concept

2011 Jun 21, 1:22"This document defines the concept of an "origin", which is often used
as the scope of authority or privilege by user agents. Typically,
user agents isolate content retrieved from different origins to
prevent malicious web site operators from interfering with the
operation of benign web sites. In addition to outlining the
principles that underly the origin concept, this document defines how
to determine the origin of a URI, how to serialize an origin into a
string, and an HTTP header, named "Origin", that indicates which
origins are associated with an HTTP request."PermalinkCommentsietf reference technical web browser user-agent webbrowser origin

Lifetimes of cryptographic hash functions

2011 Jun 20, 11:25A cautionary tale in chart form: lesson is make sure you can always upgrade your hashing algorithm or don't have security dependencies on hashing algorithms.PermalinkCommentsreference hash encryption security table technical humor

_opt Mnemonic

2011 May 24, 11:00

​I always have trouble remembering where the opt goes in SAL in the __deref_out case. The mnemonic is pretty simple: the _opt at the start of the SAL is for the pointer value at the start of the function. And the _opt at the end of the SAL is for the dereferenced pointer value at the end of the function.






SAL foo == nullptr allowed at function start? *foo == nullptr allowed at function end?
__deref_out void **foo No No
__deref_opt_out void **foo Yes No
__deref_out_opt void **foo No Yes
__deref_opt_out_opt void **foo Yes Yes
.
PermalinkCommentssal technical programming

The ftp URI Scheme

2011 May 22, 10:38One step closer to completely deprecating the original URI spec by pulling out the ftp URI scheme specification into its own new updated spec!PermalinkCommentsuri url ftp uri-scheme ietf rfc reference technical

CSS Fonts Module Level 3

2011 May 10, 10:49Interesting standards disagreements showing up in specs: "Some implementers feel a same-origin restriction should be the default for all new resource types while others feel strongly that an opt-in strategy usuable for all resource types would be a better mechanism and that the default should always be to allow cross-origin linking for consistency with existing resource types (e.g. script, images). As such, this section should be considered at risk for removal if the consensus is to use an alternative mechanism."PermalinkCommentsreference web development font specification w3c css3

HTTP framework for time-based access to resource states -- Memento

2011 Apr 30, 4:33"The HTTP-based Memento framework bridges the present and past Web by interlinking current resources with resources that encapsulate their past. It facilitates obtaining representations of prior states of a resource, available from archival resources in Web archives or version resources in content management systems, by leveraging the resource's URI and a preferred datetime. To this end, the framework introduces datetime negotiation (a variation on content negotiation), and new Relation Types for the HTTP Link header aimed at interlinking resources with their archival/version resources. It also introduces various discovery mechanisms that further support briding the present and past Web."PermalinkCommentstechnical rfc reference http header time memento archive

Experiences from an IPv6-Only Network

2011 Apr 30, 4:05"This document discusses our experiences from moving a small number of users to an IPv6-only network, with access to the IPv4-only parts of the Internet via a NAT64 device. The document covers practical experiences as well as road blocks and opportunities for this type of a network setup. The document also makes some recommendations about where such networks are applicable and what should be taken into account in the network design. The document also discusses further work that is needed to make IPv6-only networking applicable in all environments."PermalinkCommentsinternet ip ipv6 ipv4 nat technical reference

URI Fragment Identifiers for the text/csv Media Type

2011 Apr 29, 3:55This memo defines URI fragment identifiers for text/csv MIME entities. These fragment identifiers make it possible to refer to parts of a text/csv MIME entity, identified by cell, row, column, or slice.PermalinkCommentscsv uri technical mime reference

draft-abarth-url-01 - Parsing URLs for Fun and Profit

2011 Apr 27, 3:12Prescriptive spec on URI parsing. "This document contains a precise specification of how browsers process URLs. The behavior specified in this document might or might not match any particular browser, but browsers might be well-served by adopting the behavior defined herein."PermalinkCommentstechnical rfc reference uri
Older Entries Creative Commons License Some rights reserved.