When sharing HTML data, a Share source app calls setHtmlFormat (in the DataPackage it gets in the eventArgs.request.data object) for the main markup and can then populate the package’s resourceMap with RandomAccessStreamReferences to local image files. This process is documented on How to share HTML.

What’s not documented at present (I’m filing a bug on this), are the allowable URI schemes when creating stream references with the RandomAccessStreamReference.createFromUri API can accept. Those are http, https, ms-appx, and ms-appdata. A small thing, but good to know!


(Continued from Part 2.This and the other posts in this series is material I’ve written for Programming Windows Store Apps in HTML, CSS, and JavaScript, Second Edition.)

A map (IMap<K, V>) and its read-only map view companion (IMapView<K, V>) are additional derivations of the basic iterator. A map is composed of key-value pairs, where the keys and values can both be arbitrary types. [Footenote: Each pair is described by the IKeyValuePair<K, V> interface, but you don’t encounter that construct explicitly in JavaScript. Also, the IObservableMap<K, V> interface is also meant for other languages and not used in JavaScript.] A closely related construct is the property set (IPropertySet), which relates to the map. The difference is that maps and map views are used (like vectors) to return collections from WinRT APIs and to handle certain properties of WinRT objects. Property sets, for their part, as used (like basic iterators) as input arguments to WinRT APIs.

It’s important to note right up front that maps and property sets are not projected as arrays in JavaScript. They do support value lookup through the [ ] operator, but otherwise do not have array methods. A map, instead, has methods (from IMap) called lookup (same as [ ]), insert, remove, clear, and hasKey, along with a size property and a getView method like the vector. A map view shares hasKey, lookup, and size, and adds a split method. You can also pass a map or map view to Object.keys to retrieve an array of keys.

A property set has a more extensive interface, but let me come back to that in a bit.

The generic term for maps and property sets alike is a dictionary. A dictionary does just what the word means in colloquial language: it lets you look up an item (e.g. a definition) in a collection (the dictionary) by a key (such as a word). This is very useful when the collection you’re working with doesn’t store items in a linear or indexed array, or doesn’t have a need to do so. For example, when working with the Windows.Storage.Pickers.FileSavePicker class, you give the user a choice of file types through its fileTypeChoices property. This property is very interesting because its type is IMap<String, IVector>, meaning that it’s a map between a string key and a value that is itself an array. This makes sense, because you want to use something like “JPEG” for a key while yet mapping that single key to a group of values like “.jpg” and “.jpeg”.

Maps are also used extensively when working with file properties, where you have access to a deeper hierarchy of metadata that’s composed of key-value pairs. This is the same metadata that you can explore if you right click on a file in Windows Explorer and click the details tab, as shown here for a picture I took on a trip to Egypt where the camera recorded exposure details and so forth:

image properties

The Windows.Storage.FileProperties API is how you get to all this metadata. Images provide an ImageProperties object, whose retrievePropertiesAsync produces a map containing the metadata. You can play with this in the Simple Imaging sample if you’d like, where once you’ve obtained a map you can access individual properties by name (retrievedProps is the map):

retrievedProps[“System.Photo.ExposureTime”]

On the flip side of this metadata scene is where we encounter property sets. Again, these are a form of dictionary like maps, but one that an app needs to create for input to methods like ImageProperties.savePropertiesAsync. This is why Windows.Foundation.Collections has a concrete PropertySet class and not just an interface, because then we can new up an instance like so:

var properties = new Windows.Foundation.Collections.PropertySet();

and create key-value pairs with the [ ] operator:

properties[“System.GPS.LatitudeNumerator”] = latNum;

or with the insert method:

properties.insert(“System.GPS.LatitudeNumerator”, latNum);

Be mindful that while the documentation for PropertySet lists quite a few methods and properties, only some of them are projected into JavaScript:

  • Properties: size
  • Lookup methods: [ ], lookup, hasKey, first (returns an iterator for the key-value pairs)
  • Manipulation methods: clear, insert, remove
  • Other: getView (retrieves a map view) and the mapChanged event

In summary, then, maps and property sets are distinct collection constructs that must be worked with through their own methods and properties. Vectors, on the other hand, are projected into JavaScript as an array and are thus suitable for data binding through WinJS.Binding.List. If you want to bind to a map or property set, on the other hand, you’ll need to maintain an array copy.


(Continued from Part 1.This and the other posts in this series is material I’ve written for Programming Windows Store Apps in HTML, CSS, and JavaScript, Second Edition.)

By itself, an iterator only has methods to go through the collection in one direction (IIterable.first returns an IIterator whose only methods are getMany and moveNext). A vector is a more capable variant (IVector derives from IIterable) that adds random-access methods (getAt and indexOf) and methods to modify the collection (append, clear, insertAt, removeAt, removeAtEnd, replaceAll, and setAt). A vector can also report its size. [Footnote: The IObservableVector interface in Windows.Foundations.Collections exists for other languages and is not ever seen in JavaScript.]

Because a vector is a type of iterator, you can also just treat it as a JavaScript array—a vector that you obtain from some WinRT API, that is, will have methods like forEach and splice as you’d expect. The one caveat here is that if you inspect a vector in Visual Studio’s debugger (as when you hover over a variable), you’ll only see its IVector members.

Vectors basically exist to help marshal changes to the collection between the JavaScript environment and WinRT. This is why IIterable is used as arguments to WinRT APIs (the input array is effectively read-only), whereas IVector is used as an output type, either for the return value of a synchronous API or for the results of an asynchronous API. For example, the readLinesAsync methods of the FileIO and PathIO methods in Windows.Storage provide results as a vector.

Within WinRT you’ll most often encounter vectors with a read-write collection property on some object. For example, the Windows.UI.Popups.MessageDialog object has a commands property of type IVector<IUICommand>, which translates into JavaScript simply as an array of UICommand objects. Because the collection can be modified by either the app or the WinRT API, a vector is used to marshal those changes across the boundary.

In quite a number of cases—properties and methods alike—the collection involved is read-only but still needs to support random-access characteristics. For this we have the vector view (IVectorView also derives from IIterable), which doesn’t have the vector’s modification methods. To give a few examples, a vector view of ConnectionProfile objects is what you get back from NetworkInformation.getConnectionProfiles. Similarly, StorageFolder.getFilesAsync provides a vector view of StorageFile objects. The user’s preferred languages in the Windows.System.UserProfile.GlobalizationPreferences object is a vector view of strings. And you can always get a read-only view for any given read-write vector through the latter’s getView method.

Now because a vector is just a more capable iterator, guess what? You can just treat a vector like an array. For example, the Folder enumeration sample uses StorageFolder.getFilesAsync and getItemsAsync to list the contents of in your various media libraries, using forEach to iterate the array that those APIs produce. Using that example, here’s what I meant earlier that Visual Studio only shows the IVector members—the items from getItemsAsync doesn’t show array methods but we can clearly call forEach (circled):

Vector methods


(This and the other posts in this series is material I’ve written for Programming Windows Store Apps in HTML, CSS, and JavaScript, Second Edition)

All of the WinRT collection types are found in the Windows.Foundation.Collections namespace. What you’ll notice immediately upon perusing the namespace is that it actually contains only one concrete class, PropertySet, and is otherwise its chock full of “interfaces” with curious names like IIterable<T>, IMapView<K, V>, and IVectorView<T>.

If you’ve at least fiddled with.NET languages like C# in your development career, you probably already know what the I and <T> business is all about because you get to type it our all the time. For the rest of you, it probably makes you appreciate the simplicity of JavaScript! In any case, let me explain a little more.

An interface, first of all, is an abstract definition of a group of related methods and properties. Interfaces in and of themselves have no implementation, so they’re sometimes referred to as abstract or virtual types. They simply describe a way to interact with some object that “implements” the interface, regardless of what else the object might do. Many objects, in fact, implement multiple interfaces. So anytime you see an I in front of some identifier, it’s just a shorthand for a group of members with some well-defined behavior.

[Footnote: There are actually all kinds of interfaces floating around the WinRT API. When working in JavaScript, however, you rarely bump into them because the language doesn’t have a formal construct for them. For example, a page control technically implements the WinJS.UI.Pages.IPageControlMembers interface, but you never see a direct reference to that name. Instead, you simply include its methods among the instance members of your page class. In contrast, when creating classes in other languages like C# you explicitly list an interface as an abstract base class to inherit its methods.]

With collections in particular, it’s convenient to talk about the collection’s behavior independently from the particular object type that the collection contains. That is, whether you have an array of strings, integers, floats, or other complex objects, you still use the same methods to manipulate the array and the same properties like length are always there. The <T> shorthand is thus a way of saying “of type T” or “of whatever type the collection contains.” It certainly saves the documentation writers from having to copy and paste the same text into dozens of separate pages and do a search-and-replace on the data type! Of course, you’ll never encounter an abstract collection interface directly—in every instance you’ll see a concrete type in place of <T>. IVector<String>, for instance, denotes a vector of strings: you navigate the collection through the methods of IVector, and the items in the collection are of type String.

In a few cases you’ll see <K> and <K, V> where K means key and V means value, both of which can also be of some arbitrary type. Again, it’s just a shorthand that enabled us to talk about the behavior of the collection without getting caught up in the details of whatever object type it contains.

So that’s the syntactical sugar—let’s now look at different WinRT collections.

Iterators

An iterator is the most basic form of a collection and one that maps directly to a simple array in JavaScript. The two iterator interfaces in WinRT are IIterable<T> and IIterator<T>, you’ll never work with these directly in JavaScript. For one thing, a JavaScript array (containing objects of any type) can be used wherever a WinRT API calls for an IIterable. Second, when a WinRT APIs produces an iterator as a result, you can pretty much treat it as an array. (There are, in fact, no WinRT APIs available from JavaScript that directly produce a plain iterator; they produce vectors and maps that derive from IIterable and thus have those methods.)

In short, iterators are transparent from the JavaScript point of view, so when you see IIterable in the documentation for an API, just thing “array.” For example, the first argument to BackgroundDownloader.requestUnconstrainedDownloadsAsync (see Chapter 4 of the second edition) is documented as an IIterable<DownloadOperation>. In JavaScript this just means an array of DownloadOperation objects; the JavaScript projection layer will make sure that the array is translated into an IIterable suitable for WinRT.

Similarly, a number of APIs in the Windows.Storage.FileIO and PathIO classes, such as appendLinesAsync and writeLinesAsync all take arguments of type IIterable<String>, which to us just means an array of strings.

Occasionally you’ll run into an API like ImageProperties.savePropertiesAsync (in Windows.Storage.FileProperties) that takes an argument of type IIterable<IKeyValuePair>, which forces us to pause and ask just what we’re supposed to do with an collection interface of another interface! (IKeyValuePair<K, V> is also in Windows.Foundation.Collections.) Fortunately, the JavaScript projection layer translates IIterable<IKeyValuePair> into the concrete Windows.Foundation.Collections.PropertySet class, which can be easily addressed as an array with named members, as we’ll in part 3.


Continuing from Part 1, to implement an binding initializer function directly looks like this, which is taken from scenario 1 of the Declarative binding sample (for 8.1):

var toCssColor = WinJS.Binding.initializer(
function toCssColor(source, sourceProperty, dest, destProperty) {
function setBackColor() {
dest.style.backgroundColor =
rgb(source.color.red, source.color.green, source.color.blue);
}

        return WinJS.Binding.bind(source, {
color: { red: setBackColor, green: setBackColor, blue: setBackColor, }
});
}
);

// A little helper function to convert from separate rgb values to a css color
function rgb(r, g, b) { return “rgb(” + [r, g, b].join(“,”) + “)”; }

WinJS.Namespace.define(“BasicBinding”, {
toCssColor: toCssColor
});

WinJS.Binding.initializer is just an alias for WinJS.Utilities.markSupportedForProcessing, which It makes sure you can reference this initializer from processAll and doesn’t add anything else where binding is concerned.

The arguments passed to your initializer clearly tell you which properties of source and target (dest) are involved in this particular relationship. The source argument is the same as the dataContext given to processAll, and dest is the element on which this particular initializer was declared (which can be anywhere below the rootElement given to processAll). The sourceProperty and destProperty arguments are both arrays that contain the “paths” to their respective properties, where each part of the identifier is an element in the array. That is, if you have an identifier like style.color in data-win-bind, the path array will be [style, color].

With all this information in hand, you can then set up whatever binding relationships you want by calling the source’s bind method with whatever properties and handlers you require. Note that although sourceProperty is what’s present in the data-win-bind attribute, you’re free to wire up to any other property you want to include in the relationship. The code above, for example, will be called with sourceProperty equal to [color], but it doesn’t actually bind to that directly. It instead uses a binding descriptor with WinJS.Binding.bind to hook up the setBackColor handler to three separate color subproperties. Although setBackColor is used for all three, you could just as easily have separate handlers for each one if, for example, each required a unique conversion.

Ultimately, what’s important is that the handler given to the source.bind method performs an appropriate update on the target object. In the code above, you can see that setBackColor sets dest.style.backgroundColor.

Hmmm. Do you see a problem there? In the Declarative binding sample, try changing the last data-win-bind attribute in html/1_BasicBinding.html to set the text color instead:

data-win-bind=”style.color : color BasicBinding.toCssColor”

Oops! It still changes the background color! This is because the initializer isn’t honoring destProperty, and that would be a difficult bug to track down when it didn’t work as expected. Indeed, because the initializer pays no attention to destProperty you use a non-existent identifier and it will still change the background color:

data-win-bind=”some.ridiculous.identifier : color BasicBinding.toCssColor”

Technically speaking, then, we could rewrite the code as follows:

dest.[destProperty[0]].[destProperty[1]] = rgb(source.color.red, source.color.green, source.color.blue);

Even this code makes the assumption that the target path has only two components—to be really proper about it, you need to iterate through the array and traverse each step of the path. Here’s a way to do that:

var target = “dest”;
for (var i = 0, len = destProperty.length – 1; i < len; i++) {
target += “.” + destProperty[i];
}

target = eval(target);
var lastProp = destProperty[i];

function setBackColor() {
target[lastProp] = rgb(source.color.red, source.color.green, source.color.blue);
}

Note that I’m building that reference outside of the setBackColor handler because there’s no need to rebuild it every time a source property changes.

Remember also that sourceProperty can also contain multiple parts, so you may need to evaluate that path as well. The sample gets away with ignoring sourceProperty because it knows it’s only using the toCssColor initializer with source.color to begin with. Still, if you’re going to write an initializer, best to make it as robust as you can!

 

[7/23/13: Corrected one statement above on the source and dest arguments to the initializer. It has incorrectly stated that dest was the same as the rootElement to processAll; it’s the element where the initializer is declared.]


I’ve been writing about this subject more thoroughly for the second edition of my book (view preview here), and thought to share the results here in two parts.

When WinJS.Binding.processAll encounters a data-win-bind attribute on an element, its main job is to take each <target property> : <source property> [] string and turn it into a real binding relationship. Assuming that the data source is observable, this basically means calling the source’s bind method with the source property name and some handler that will update the target property accordingly.
The purpose of the initializer function in this process is to define exactly what happens in that handler, that is, what happens to the target property in response to a source property update. In essence, an initializer provides the body of the handler given to the source’s bind (that is, each binding source is an object that has a bind method, typically brought in from the WinJS.Binding.mixin or observableMixin, which is done when you call WinJS.Binding.as or WinJS.Binding.define for a data source).

In a simple binding relationship, that code might simply copy the source value to the target, or might involve a converter function. It could also consolidate multiple source properties—you can really do anything you want here. The key thing to remember is that the initializer itself will be called once and only once for each binding relationship, but the code it provides, such as a converter function, will be called every time the source property changes.

Now if you don’t specify a custom initializer within data-win-bind, WinJS will always use a default, namely WinJS.Binding.defaultBind.  It simply sets up a binding relationship that copies the source property’s value straight over to the target property, as you’d expect. In short, the following two binding declarations have identical behavior:

data-win-bind=”innerText: name”
data-win-bind=”innerText: name defaultBind”

WinJS.Binding provides a number of other built-in initializers that can come in handy:

  • oneTime Performs a one-time copy of the source property to the target property without setting up any other binding relationship. This is necessary when the source is a WinRT object, as the proxy used for marshalling doesn’t supporting observability for one-way or two-way binding.
  • setAttribute and setAttributeOneTime Similar to defaultBind and oneTime but injects a call to the target element’s setAttribute method instead of just copying the source value to a target property. This is how you bind to DOM element attributes rather than object properties.
  • addClassOneTime (WinJS 2.0 only) Like setAttributeOneTime except that it interprets the source property as a class name and thus calls the target element’s classList.add method to apply that class. This is useful when working with binding templates.

Beyond these, we enter into the realm of custom initializers. The most common and simplest case is when you need to inject a converter into the binding relationship. All this takes on your part is to pass your conversion function to WinJS.Binding.converter, which returns the appropriate initializer (that’s also marked for declarative processing). For example, in the example below the function userTypeToColor is a simple data-conversion function, so we can create an initializer within the MyInitializers namespace as follows:

WinJS.Namespace.define(“MyInitializers”, {
//…
typeColorInitializer: WinJS.Binding.converter(userTypeToColor)
});

which we use in the HTML like so:

<span id=”loginName3″
data-win-bind=”innerText: name; style.color: userType MyInitializers.typeColorInitializer”>
</span>

Doing anything more requires that you implement the initializer function directly. We’ll pick up this subject in Part 2.



There are new APIs for working with the user’s calendar and contacts, which are found in Windows.ApplicationModel.Appointments and Windows.ApplicationModel.Contacts. There are also some smaller improvements in the file pickers and Share contract. For all this there are two //build talks: Building apps that work together (2-010) and Building Apps That Integrate with People and Events (3-007).


Fulfilling a common request for new APIs, Windows 8.1 adds a PDF rendering API that’s found in the Windows.Data.Pdf namespace and demonstrated in the PDF viewer sample and the more extensive PDF viewer showcase sample. The API itself can open and load PDFs, then you request that individual pages be rendered to a stream. That stream can then be turned into a graphic for whatever UI framework you’re using. The //build talk is Rendering PDF Content in Windows Store Apps (3-175).

Windows 8.1 also adds a text-to-speech API, which you’ll find in Windows.Media.SpeechSynthesis and demonstrated in the Speech synthesis sample. The //build talk on this is Making Your Windows Store Apps Talk (2-171).

Speaking of text, also look at the Windows.Data.Text namespace, where there’s a bunch of new stuff for text segmentation and Unicode. There are some related samples, but I haven’t worked through those enough yet to comment further.


On one hand I’m not entirely sure that the changes in Windows 8.1 for the Search contract and app sizing count as a “new API”–but they are certainly things you need to pay attention to!

Variable app sizing is certainly a new feature for Windows users, and thus something that apps want to handle well. This is one case where some APIs (like tryUnsnap) are actually deprecated! For apps written in HTML/CSS/JS, this means that the view state media features of (fullscreen-landscape, snapped, filled, and fullscreen-portrait) are obsoleted, replaced by the CSS3 standards for responsive web design, namely the orientation feature (portrait or landscape) and using max-width and min-width. I demonstrate some of this in Chapter 2 of my second edition preview. I’ll have more in my Layout chapter in the next preview, but you can also see more in the //build talk Beautiful Apps at Any Size on Any Screen (2-150).

Search also changes in that the Search charm now reaches out to web content, not just in-app content. As a result, in-app search is a feature that an app should show in its own UI (on-canvas or app bar). See Design and Build a Great Search Experience in Your App (3-144) for the details.