within the app container. For example, trying to create a jQuery datepicker widget ($("myCalendar").datepicker()) will hurl out this kind of error. You can get around this on the app level by wrapping the code above with MSApp.execUnsafeLocalFunction, but that doesn’t solve injections coming from deeper inside the library. In the jQuery example given here, the control can be created but clicking a date in that control generates another error. In short, you’re free to use third-party libraries so long as you’re aware that they were generally written with assumptions that don’t always apply within the app container. Over time, of course, fully Windows 8–compatible versions of such libraries will emerge. Here My Am! with ms-appdata OK! Having endured seven pages of esoterica, let’s play with some real code and return to the Here My Am! app we wrote in Chapter 2. Here My Am! used the convenient URL.createObjectURL method to display a picture taken through the camera capture UI in an img element: captureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo) .done(function (capturedFile) { if (capturedFile) { that.src = URL.createObjectURL(capturedFile); } }); This is all well and good: we just take it on faith that the picture is stored somewhere so long as we get a URI. Truth is, pictures (and video) from the camera capture API are just stored in a temp file; if you set a breakpoint in the debugger and look at capturedFile, you’ll see that it has an ugly file path like C:\Users\kraigb\AppData\Local\Packages\ ProgrammingWin8-JS-CH3- HereMyAm3a_5xchamk3agtd6\TempState\picture001.png. Egads. Not the friendliest of locations, and definitely not one that we’d want a typical consumer to ever see! With an app like this, let’s copy that temp file to a more manageable location, to allow the user, for example, to select from previously captured pictures (as we’ll do in Chapter 8, “State, Settings, Files, and Documents”). We’ll make a copy in the app’s local appdata folder and use ms-appdata to set the img src to that location. Let’s start with the call to captureUI.captureFileAsync as before: //For use across chained promises var capturedFile = null; captureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo) .then(function (capturedFileTemp) { //Be sure to check validity of the item returned; could be null if the user canceled. if (!capturedFileTemp) { throw ("no file captured"); } Notice that instead of calling done to get the results of the promise, we’re using then instead. This is because we need to chain a number of async operations together and then allows errors to propagate through the chain, as we’ll see in the next section. In any case, once we get a result in capturedFileTemp (which is in a gnarly-looking folder), we then open or create a “HereMyAm” folder within our local 92
appdata. This happens via Windows.Storage.ApplicationData.current.localFolder, which gives us a Windows.Storage.StorageFolder object that provides a createFolderAsync method: //As a demonstration of ms-appdata usage, copy the StorageFile to a folder called HereMyAm //in the appdata/local folder, and use ms-appdata to point to that. var local = Windows.Storage.ApplicationData.current.localFolder; capturedFile = capturedFileTemp; return local.createFolderAsync("HereMyAm", Windows.Storage.CreationCollisionOption.openIfExists); }) .then(function (myFolder) { //Again, check validity of the result operations if (!myFolder) { throw ("could not create local appdata folder"); } Assuming the folder is created successfully, myFolder will contain another StorageFolder object. We then use this as a target parameter for the temp file’s copyAsync method, which also takes a new filename as its second parameter. For that name we’ll just use the original name with the date/time appended (replacing colons with hypens to make a valid filename): //Append file creation time (should avoid collisions, but need to convert colons) var newName = capturedFile.displayName + " - " + capturedFile.dateCreated.toString().replace(/:/g, "-") + capturedFile.fileType; return capturedFile.copyAsync(myFolder, newName); }) .done(function (newFile) { if (!newFile) { throw ("could not copy file"); } Because this was the last async operating in the chain, we use the promise’s done method for reasons we’ll again see in a moment. In any case, if the copy succeeded, newFile contains a StorageFile object for the copy, and we can point to that using an ms-appdata URI: lastCapture = newFile; //Save for Share that.src = "ms-appdata:///local/HereMyAm/" + newFile.name; }, function (error) { console.log(error.message); }); The completed code is in the HereMyAm3a example. Of course, we could still use URL.createObjectURL with newFile as before (making sure to provide the { oneTimeOnly=true } parameter to avoid memory leaks). While that would defeat the purpose of this exercise, it works perfectly (and the memory overhead is essentially the same since the picture has to be loaded either way). In fact, we’d need to use it if we copy images to the user’s pictures library instead. To do this, just replace Windows.Storage.ApplicationData.current.localFolder with Windows.Storage.KnownFolders.picturesLibrary and declare the Pictures Library capability in the manifest. Both APIs give us a StorageFolder, so the rest of the code is the same except that we’d use URL.createObjectURL because we can neither use ms-appdata:// nor file:// to refer to the pictures library. The HereMyAm3a example contains this code in comments. 93
1 99
Table of Contents Introduction ....
WinJS Tools for Pages and Page Navi
Chapter 6: Layout .................
Design Guidelines for Settings ....
Manipulating Audio and Video ......
Managing Secondary Tiles ..........
The User Profile (and the Lock Scre
The Windows Store APIs ............
Introduction Welcome, my friends, t
I'm also assuming that your interes
Acknowledgements In many ways, this
Support for developers, however, ca
technologies, including DirectX, XA
The upload process will walk you th
FIGURE 1-2 A typical app page in th
do this, I’m sure!). In a hotel,
The app host is more or less Intern
Sidebar: Mixed Language Apps Window
When snapped, on the other hand, ap
defined as part of the WinJS.UI nam
Clearly, then, the bulk of the work
var element = document.getElementBy
This example is taken directly from
FIGURE 4-7 Expanding a WinJS contro
Flexbox -ms-[inline-]flexbox (value
Note Though not shown here, you can
For the ToggleSwitch, win-* classes
• If a WinJS.UI.Tooltip is gettin
Custom Control Examples To see thes
Between calendar.js and calendar.cs
]]> Whe
This would be appropriate if you cr
Two-way: essentially one-way bindin
The code for this can be found in T
Sidebar: Data-Binding Properties of
Implementing Two-Way Binding To imp
• oneTime A function that just lo
• Windows 8 apps have rich stylin
Collection Control Basics To seek t
indingList: bindingList, array: arr
Now while the ListView control in S
The header template in html/scenari
In the modified sample I changed na
} return groupCompareGlobalized(lef
a function instead of a declarative
var list = new WinJS.Binding.List()
data-win-options="{ itemDataSource:
e used anywhere it’s appropriate,
If you were to provide your own nav
sample code in this chapter’s com
Because of data binding, changes to
What is does have, however, is this
What you then do inside the element
• The groups themselves are all s
and the current viewable area. Thou
Styling Following the precedent of
Technically speaking, the layout pr
or you can set layout.groupInfo fro
Using the first item’s dimension
You can set a breakpoint in this fu
Incremental Loading Apart from pote
The yellow bars indicate execution
If it’s not provided (as when the
During initialization (outside the
Chapter 6 Layout Compared to other
that appear when needed through app
Within the body of content, then, W
} -ms-grid-columns: 120px 2fr 80px
-ms-scroll-snap-x Shorthand to comb
WinRT: filled -ms-view-state: fille
Handling View States As I just ment
var mql = window.matchMedia("(-ms-v
individual items in snapped view. B
FIGURE 6-5 Options for display size
If your developer sensibilities obj
Content goes here This is really
Such a layout is most easily achiev
Because the specs themselves are st
/* In CSS */ #divMain { width: 100%
CSS styles that are supported for W
Within the activated handler docume
Multicolumn Elements and Regions Tr
FIGURE 6-9 CSS region chains to flo
Chapter 7 Commanding UI For consume
• Commands that can’t be placed
which provide many specifics on pla
Tip To prevent the app bar from app
This example doesn’t provide any
var appbar = document.getElementByI
• afterhide occurs immediately af
This button’s click handler uses
In the extraClass properties we’v
To provide graphics of your own, do
It should come as no surprise by
Flyouts and Menus Going back to our
are optional with show. (Note also
function confirmOrder() { bought =
The point of this last example is t
Also, go into css/header-menu.c
In the contextmenu handler menu.sho
Scenario 3 is identical to Scenario
The app bar now appears as follows,
This message will appear if the use
Chapter 8 State, Settings, Files, a
while our permanent home was being
• Account and profile configurati
By the way, you might have some rea
var localSettings = Windows.Storage
It is also possible to migrate app
Tip There are some file extensions
Sidebar: Closing Streams vs. Closin
Using App Data APIs for State Manag
efore setting up new defaults. As m
Roaming State The automatic roaming
good idea to not be too aggressive
Each app-supplied command can do on
There are two ways to implement thi
function helpCommandInvoked(e) { va
Programmatically Invoking Settings
Sidebar: Changes to Permissions A c
Think about this for a moment (as I
eturns an appropriate StorageFile o
function pickSinglePhoto() { // Ver
When picking multiple files, the re
indicate a new filename in which to
scenario oriented on the music libr
A QueryOptions is generally created
The setPropertyPrefetch method goes
What We’ve Just Learned • State
Chapter 9 Input and Sensors Touch i
• Second, when you need to handle
One or more fingers touch the scree
You might notice a conspicuous abse
Note that this method has no effect
• TouchCapabilities Properties ar
Tip Pointer events won’t fire if
Properties Description currentPoint
The first step to receiving gesture
• MSGestureHold occurs when MSPoi
FIGURE 9-3 A conceptual representat
FIGURE 9-4 The Input Instantiable G
obviously a specific deceleration m
• Process keydown, keyup, and key
For passwords you get a key to hide
keyboard sample. 50 Adding listener
Standard Keystrokes The last piece
FIGURE 9-9 The Input Ink sample wit
(string), and timestamp (Date) prop
Like all other WinRT APIs, however,
Here’s an example of such code fr
Chapter 10 Media To say that media
movie.controls = true; document.get
declared inline, created dynamicall
} document.getElementById("r").styl
function onImageError(source) { sou
• By copying pixel data from a vi
It’s also helpful to understand t
Video Element Extension APIs Beyond
vid.msInsertVideoEffect("GrayscaleT
elements with the same source. The
in the background. As a developer,
function soundLevelChanged() { //Ca
Playing Sequential Audio An app tha
need to bypass the audio element an
To guarantee the ordering we use Pr
Thumbnails First, StorageFile.getTh
or combination of System.GPS.Longit
} return degrees + "°" + minutes +
Most of the displayImageUI function
provides a specific BitmapEncoder i
method can be called only once and
Transcoding and Custom Image Format
Transcoding happens either from one
In Scenario 2, the sample always us
Media Capture There are times when
ecordLimitationExceeded Fired when
} captureInitSettings.videoDeviceId
} // Add the devices to deviceList
Streaming from a Server and Digital
Here’s how such apps generally wo
Next you’ll want to wire up handl
• WinRT provides a rich API for m
necessary. In this way, excessive a
The Control Panel setting can be ob
screen; the Panel animations are fo
want to chain or synchronize animat
Create addToList animation. var add
CSS Animations and Transitions As n
Animations work in an opposite mann
Keyframes, while typically defined
FIGURE 11-2 Output of Scenario 3 of
What’s more, requestAnimationFram
Still, 20% is a lot of CPU power to
Chapter 12 Contracts Recently I dis
File activation (file type associat
more specific. For instance, when a
var dataPackageTitle = document.get
The other interesting part of Scena
When sharing an image, don't forget
FIGURE 12-3 The Share content targe
• Acknowledge user actions when y
The key here is the args.detail.sha
target app. If you’re using image
FIGURE 12-7 Controls to create a qu
The question is how to wire up comm
The Search contract that makes this
FIGURE 12-11 The Search declaration
} } })); In the search activation p
} }); Windows.ApplicationModel.Sear
The request object also has a getDe
Type to Search The final feature of
egistered for that type, rather tha
At the very bottom of this UI you c
ecord a new sound. In such cases, h
Activation of a File Picker Provide
Windows.ApplicationModel.Activation
A final note is that a file picker
}; // Create a file to provide back
The next step for the provider is t
FIGURE 12-18 The provider sample’
FIGURE 12-21 The provider sample’
• If the UI status is visible, sw
Just as the file picker contract al
Using the Contact Picker Contacts a
} } }); Contact Picker Providers On
As you can see, the homeEmail field
Chapter 13 Tiles, Notifications, th
FIGURE 13-1 The typical default Sta
Selecting an item on the Start scre
In many ways, live tiles might redu
toss up lots of superfluous toast,
Yet Windows doesn’t want to force
The third way an app can issue upda
Providing both square and wide stat
• arguments A string that’s pas
function activated(eventObject) { i
16 or fewer characters that is used
Third, if you supply an image that
arrive on a Windows 8 machine will
The Notifications Extensions Librar
The other bits of the manifest that
In such cases it would be better to
Windows.UI.Notifications.BadgeUpdat
you’d use start time), or the pha
Tip The tile and badge updaters are
eturned from page requests, as we
through the Web platform installer.
Toast Notifications So far in this
FIGURE 13-16 Issuing text toasts th
supports addImageQuery for scale, l
A scheduled toast is created using
To update a tile, set a badge, or i
Your app should go through this sho
matter of sending an XmlHttpRequest
In the running app, the pushnotific
Background Tasks and Lock Screen Ap
FIGURE 13-18 The manifest editor fo
In this code, the BackgroundTaskBui
var internetCondition = new backgro
The Background task sample provides
Note Working with the lock screen i
Debugging Background Tasks By this
• Periodic updates for tiles and
Network Information and Connectivit
networkstatuschanged event that we
Note Windows Store apps written in
Programmatically, as noted before,
Although this option will not set u
hundred kilobytes—if you know fro
Finally, avoid using XHR for large
Starting a download transfer happen
There is also a variation of create
operations—it is possible to crea
); "form-data", "------------------
Basically, you would change the pol
Authentication, Credentials, and th
The result from pickAsync, as given
To clarify the relationship between
There is one subtle difference betw
Within the web authentication broke
https://www.facebook.com/dialog/oau
Single Sign On with Live Connect Be
setAccountPicturesAsync (for provid
And lastly it’s worth at least li
} var scenario1Link = document.getE
} return currentFeed.items[currentI
When data arrives, the handler rece
} // This is a helper function echo
On the client side, StreamSocket ag
And closing the socket in Scenario
In the sample, we first create a Me
} try { var size = dataWriter.measu
What We’ve Just Learned • Netwo
• Connecting with devices in the
The XInput and JavaScript controlle
function renderLoop() { var state =
FIGURE 15-3 Sample device enumerati
The Removable Storage sample, in Sc
• Communications are supported on
Advertising a Connection Making you
Tap to Connect and Tap to Activate
On a simpler note, publishing a URI
FIGURE 15-5 Scenario 2 of the Print
Print Document Sources No matter wh
If you don’t add a handler for th
The final bit to mention in the cod
Indeed, when we speak of mixed lang
Again, components can also make use
Sidebar: WinRT Components vs. Class
Once you add the name of a class an
With the basic mechanics worked out
As we did with C#, let’s start by
Comparing the Results The Image Man
} return sum; Running a count with
Component Implementation • When c
When this worker is started, the on
FIGURE 16-4 A promise manages and i
Note that Task.Run does not support
As with C#, there are additional st
public IAsyncOperation ConvertPixel
method called ConvertGrayscalFileAs
Event names, on the other hand, are
One challenge, as we saw in the qui
The Building your own Windows Runti
• Check against an encrypted lice
Chapter 17 Apps for Everyone: Acces
Your App, Your Business If you chec
FIGURE 17-1 Creating an app package
desktop applications and distribute
means is that if you want to promot
You should also strongly consider m
• In-app purchases through the Wi
That said, WinRT provides for the f
When your app accesses CurrentAppSi
} }); currentApp.licenseInformation
You won’t hit your breakpoint imm
If you’re using a custom commerce
You might have noticed that a Produ
Id=\"e2a62d42-dbca-43d2-b779-66eb91
The latter two we’ve already cove
• aria-label Directly provides te
Apart from the small bits of code i
control sample, and switch between
Scenario 2 shows similar effects wi
Canvas a better choice? To this poi
one resource. For a few examples of
addition of new string and image re
FIGURE 17-9 Control panel dialogs f
Formatting Culture-Specific Data an
Sorting and Grouping Just as a worl
With images, you can reverse them w
Note CSS files can contain string l
Manifest: Let’s turn now to the m
Other affected files in this app in
Sidebar: String Resources in Settin
the folder name itself doesn’t us
If you like, you can just send your
FIGURE 17-11 The Multilingual App T
Second, the Toolkit will detect if
Localization Wrap-Up Well, we’re
Let me say that again: all of this
Onboarding and Working through Reje
Connecting Your Website If you have
What We’ve Just Learned • An ap
What do you think of this book? We