<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Windows 8 app developer blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/windowsappdev/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/windowsappdev/feed.xml</link>
    <description>Insights on building Windows Store apps by the Windows 8 engineering team</description>
    <lastBuildDate>Sun, 05 Apr 2015 06:03:35 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Introducing the Windows App Builder blog!</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/introducing-the-windows-app-builder-blog</link>
      <pubDate>Wed, 19 Jun 2013 09:30:00 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/06/19/introducing-the-windows-app-builder-blog/</guid>
      <description><![CDATA[Hey everyone, I wanted to let you know that we’re bringing the Windows 8 app developer and Windows...]]></description>
      <content:encoded><![CDATA[<p>Hey everyone, I wanted to let you know that we’re bringing the <a href="http://blogs.msdn.com/b/windowsappdev/" target="_blank">Windows 8 app developer</a> and <a href="http://blogs.msdn.com/windowsstore/" target="_blank">Windows Store</a> blogs together into the new <a href="http://blogs.windows.com/windows/b/appbuilder/" target="_blank">Windows App Builder blog</a>. With the upcoming release of Windows 8.1 Preview we have a lot to tell you about what’s new for Windows app builders, and we’re excited to do so in the new blog. With the new blog, you’ll be able to get what you need to build, design, and market your apps. </p>  <p>For those of you currently subscribed to our RSS feed, don’t worry. We’ll automatically redirect posts from the old blog to the new blog so you don’t miss a beat. And we’ll continue to host all our existing blog posts right here, so you can always come back to check out the info we’ve written on developing apps for Windows 8.</p>  <p>I hope you’ve enjoyed the content on the blog so far and look forward to seeing you on the <a href="http://blogs.windows.com/windows/b/appbuilder/" target="_blank">Windows App Builder blog</a>.</p>  <p>-Ian LeGrow, Group Program Manager, Windows</p>]]></content:encoded>
    </item>
    <item>
      <title>Optimizing ListView item rendering</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/optimizing-listview-item-rendering</link>
      <pubDate>Mon, 17 Jun 2013 10:00:00 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/06/17/optimizing-listview-item-rendering/</guid>
      <description><![CDATA[For many Windows Store apps written in JavaScript that work with collections, cooperating well with...]]></description>
      <content:encoded><![CDATA[<p>For many <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211385.aspx" target="_blank">Windows Store apps written in JavaScript</a> that work with collections, cooperating well with the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211837.aspx" target="_blank">WinJS ListView control</a> is essential for great app performance. This isn’t surprising: when you’re dealing with management and display of potentially thousands of items, every bit of optimization you make with those items really counts. Most important is how each of the items gets rendered, which is to say, how—and when—each item in the ListView control gets built up in the DOM and becomes a visible part of the app. Indeed, the <i>when </i>part of this equation becomes a critical factor when a user rapidly pans around within a list and expects that list to keep pace.</p>  <p>Item rendering in a ListView happens through either a declarative template defined in HTML or through a custom JavaScript <i>rendering function</i> that’s called for every item in the list. Although using a declarative template is the simplest, it doesn’t provide much latitude for specific control over the process. A rendering function, on the other hand, lets you customize rendering on a per-item basis and enables a number of optimizations that are demonstrated in the <a href="http://code.msdn.microsoft.com/windowsapps/ListView-performance-39fb71f0" target="_blank">HTML ListView optimizing performance sample</a>. Those optimizations are:</p>  <ul>   <li>Allowing for asynchronous delivery of item data and a rendered element, as supported by basic rendering functions.</li>    <li>Separating the creation of an item’s shape, which is necessary for the ListView’s overall layout, from its internal elements. This is supported through a placeholder renderer.</li>    <li>Reusing a previously-created item element (and its children) by replacing its data, avoiding most of the element-creation steps, provided for through a recycling placeholder renderer.</li>    <li>Deferring expensive visual operations like image loading and animations until an item is visible and the ListView isn’t being rapidly panned, which is accomplished through a multistage renderer.</li>    <li>Batching together those same visual operations to minimize re-rendering of the DOM with a multistage batching renderer.</li> </ul>  <p>In this post we’ll go through all these stages and learn how they cooperate with the ListView’s item rendering process. As you can imagine, optimizations around the <i>when</i> of item rendering involves lots of asynchronous operations and therefore lots of promises. So in the process, we’ll also gain a deeper understanding of promises themselves, building upon the earlier <a href="http://blogs.msdn.com/b/windowsappdev/archive/2013/06/10/all-about-promises-for-windows-store-apps-written-in-javascript.aspx" target="_blank">All about promises</a> on this blog.</p>  <p>As a general note that applies to all renderers, it’s always important to keep your core item rendering time (not counting deferred operations) to a minimum. Because the ListView’s final performance greatly depends on how well its updates are aligned to screen refresh intervals, a few extra milliseconds spent in an item renderer can bump the ListView’s overall rendering time over the next refresh interval, resulting in dropped frames and visual choppiness. In other words, item renderers are one place where it really does count to optimize your JavaScript code.</p>  <h2>Basic renderers</h2>  <p>Let’s start with a quick review of what an item rendering function—which I’ll simply call a <i>renderer</i>—looks like. A renderer is a function that you assign to the ListView’s <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700705.aspx" target="_blank">itemTemplate</a> property instead of a template name, and that function will be called, as necessary, for items that the ListView wants to include in the DOM. (Basic documentation for renderers, by the way, is found on the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700705.aspx" target="_blank">itemTemplate</a> page, but it’s the sample that really shows the optimizations.)</p>  <p>You might expect that an item rendering function would just be given an item from the ListView’s data source. It would then create the HTML elements needed for that particular item and return the root element that the ListView can add to the DOM. This is essentially what happens, but there are two added considerations. First, the item data itself might be loaded asynchronously, so it makes sense to tie element creation to the availability of that data. Furthermore, the process of rendering the item itself might involve other asynchronous work, such as loading images from remote URIs or reading data in other files identified in the item data. The different levels of optimization that we’ll see, in fact, allow for an arbitrary amount of async work between the request of the item’s elements and actual delivery of those elements.</p>  <p>So, again, you can expect that promises are involved! For one, the ListView doesn’t just give the renderer the item data directly, it supplies a promise for that data. And instead of the function directly returning the item’s root element, it returns a promise for that element. This allows the ListView to join many item rendering promises together and wait (asynchronously) until a whole page worth of items has been rendered. It does this, in fact, to intelligently manage how it builds up different pages, first building the page of visible items, then two offscreen pages forward and back where users are most likely to pan to next. In addition, having all these promises in place means that the ListView can easily cancel the rendering of unfinished items if the user pans away, thereby avoiding unnecessary element creation.</p>  <p>We can see how these promises are used in the <b>simpleRenderer</b> function of the sample:</p>  <p>&#160;</p>  <blockquote>   <div id="codeSnippetWrapper">     <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">function</span> simpleRenderer(itemPromise) {<br />    <span style="color: rgb(0, 0, 255);">return</span> itemPromise.then(<span style="color: rgb(0, 0, 255);">function</span> (item) {<br />        <span style="color: rgb(0, 0, 255);">var</span> element = document.createElement(<span style="color: rgb(0, 96, 128);">&quot;div&quot;</span>);<br />        element.className = <span style="color: rgb(0, 96, 128);">&quot;itemTempl&quot;</span>;<br />        element.innerHTML = <span style="color: rgb(0, 96, 128);">&quot;&lt;img src='&quot;</span> + item.data.thumbnail +<br />            <span style="color: rgb(0, 96, 128);">&quot;' alt='Databound image' /&gt;&lt;div class='content'&gt;&quot;</span> + item.data.title + <span style="color: rgb(0, 96, 128);">&quot;&lt;/div&gt;&quot;</span>;<br />        <span style="color: rgb(0, 0, 255);">return</span> element;<br />    });<br />}<br /></pre>
  </div>
</blockquote>

<p>This code first attaches a completed handler to the <b>itemPromise</b>. The handler is invoked when the item data is available and effectively creates the elements in response. But notice again that we’re not actually returning the element directly—we’re returning a promise that’s fulfilled with that element. That is, the return value from <b>itemPromise.then()</b> is a promise that’s fulfilled with <i>element </i>if and when the ListView needs it.</p>

<p>Returning a promise allows us to do other asynchronous work if necessary. In this case the renderer can just chain those intermediate promises together, returning the promise from the last <b>then</b> in the chain. For example:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">function</span> someRenderer(itemPromise) {<br />    <span style="color: rgb(0, 0, 255);">return</span> itemPromise.then(<span style="color: rgb(0, 0, 255);">function</span> (item) {<br />        <span style="color: rgb(0, 0, 255);">return</span> doSomeWorkAsync(item.data);<br />    }).then(<span style="color: rgb(0, 0, 255);">function</span> (results) {<br />        <span style="color: rgb(0, 0, 255);">return</span> doMoreWorkAsync(results1);<br />    }).then(<span style="color: rgb(0, 0, 255);">function</span> (results2) {<br />        <span style="color: rgb(0, 0, 255);">var</span> element = document.createElement(<span style="color: rgb(0, 96, 128);">&quot;div&quot;</span>);<br />        <span style="color: rgb(0, 128, 0);">// use results2 to configure the element</span><br />        <span style="color: rgb(0, 0, 255);">return</span> element;<br />    });<br />}<br /></pre>
  </div>
</blockquote>

<p>Note that his is a case where we do <i>not</i> use <b>done</b> at the end of the chain because we’re returning the promise from the last <b>then</b> call. The ListView takes responsibility for handling any errors that might arise.</p>

<h2>Placeholder renderers</h2>

<p>The next stage of ListView optimization uses a <i>placeholder renderer</i> that separates building up the element into two stages. This allows the ListView to ask for just those parts of an element that are necessary to define the list’s overall layout, without having to build up all the elements inside each item. As a result, the ListView can complete its layout pass quickly and continue to be highly responsive to further input. It can then ask for the remainder of the element at a later time.</p>

<p>A placeholder renderer returns an object with two properties instead of just a promise:</p>

<ul>
  <li><i>element</i> The top-level element in the item’s structure that’s enough to define its size and shape and is not dependent on the item data.</li>

  <li><i>renderComplete</i> A promise that’s fulfilled when the remainder of the element’s contents are constructed, that is, returns the promise from whatever chain you have starting with <b>itemPromise.then</b> as before.</li>
</ul>

<p>The ListView is smart enough to check whether your renderer returns a promise (the basic case as before) or an object with <i>element</i> and <i>renderComplete</i> properties (more advanced cases). So the equivalent placeholder renderer (in the sample) for the previous <b>simpleRenderer</b> is as follows:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">function</span> placeholderRenderer(itemPromise) {<br />    <span style="color: rgb(0, 128, 0);">// create a basic template for the item that doesn't depend on the data</span><br />    <span style="color: rgb(0, 0, 255);">var</span> element = document.createElement(<span style="color: rgb(0, 96, 128);">&quot;div&quot;</span>);<br />    element.className = <span style="color: rgb(0, 96, 128);">&quot;itemTempl&quot;</span>;<br />    element.innerHTML = <span style="color: rgb(0, 96, 128);">&quot;&lt;div class='content'&gt;...&lt;/div&gt;&quot;</span>;<br /><br />    <span style="color: rgb(0, 128, 0);">// return the element as the placeholder, and a callback to update it when data is available</span><br />    <span style="color: rgb(0, 0, 255);">return</span> {<br />        element: element,<br /><br />        <span style="color: rgb(0, 128, 0);">// specifies a promise that will be completed when rendering is complete</span><br />        <span style="color: rgb(0, 128, 0);">// itemPromise will complete when the data is available</span><br />        renderComplete: itemPromise.then(<span style="color: rgb(0, 0, 255);">function</span> (item) {<br />            <span style="color: rgb(0, 128, 0);">// mutate the element to include the data</span><br />            element.querySelector(<span style="color: rgb(0, 96, 128);">&quot;.content&quot;</span>).innerText = item.data.title;<br />            element.insertAdjacentHTML(<span style="color: rgb(0, 96, 128);">&quot;afterBegin&quot;</span>, <span style="color: rgb(0, 96, 128);">&quot;&lt;img src='&quot;</span> +<br />                item.data.thumbnail + <span style="color: rgb(0, 96, 128);">&quot;' alt='Databound image' /&gt;&quot;</span>);<br />        })<br />    };<br />}<br /></pre>
  </div>
</blockquote>

<p>Note that the <i>element.innerHTML</i> assignment could be moved inside <b>renderComplete</b> because the <i>itemTempl</i> class in the sample’s css/scenario1.css file specifies the width and height of the item directly. The reason why it’s included in the <i>element</i> property is because it provides the default “…” text in the placeholder. You could just as easily use an <i>img</i> element that refers to a small in-package resource that’s shared across all the items (and thus renders quickly).</p>

<h2>Recycling placeholder renderers</h2>

<p><strong>Note:</strong> This option is only available on Windows 8 and the WinJS 1.0 ListView. On Windows 8.1 Preview and later the WinJS 2.0 ListView doesn’t recycle items because of changes in loading behaviors.</p>

<p>The next optimization, the <i>recycling placeholder</i> renderer, doesn’t add anything new where promises are concerned. It rather adds awareness of a second parameter to the renderer called <i>recycled</i>, which is the root element of an item that was previously rendered but is no longer visible. That is, the recycled element already has is child elements in place, so you can simply replace the data and perhaps tweak a few of those elements. This avoids most of the otherwise costly element-creation calls needed for a wholly new item, saving quite a bit of time in the rendering process.</p>

<p>The ListView may provide a recycled element when its <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211835.aspx" target="_blank">loadingBehavior</a><b></b> is set to &quot;randomaccess&quot;. If <i>recycled</i> is given, you can just clean data out of the element (and its children), return it as the placeholder, and then fill in data and create any additional children (if necessary) within <i>renderComplete</i>. If a recycled element is not provided (as when the ListView is first created or when <b>loadingBehavior</b> is &quot;incremental&quot;), you’ll create the element anew. Here’s the code from the sample for that variation:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">function</span> recyclingPlaceholderRenderer(itemPromise, recycled) {<br />    <span style="color: rgb(0, 0, 255);">var</span> element, img, label;<br />    <span style="color: rgb(0, 0, 255);">if</span> (!recycled) {<br />        <span style="color: rgb(0, 128, 0);">// create a basic template for the item that doesn't depend on the data</span><br />        element = document.createElement(<span style="color: rgb(0, 96, 128);">&quot;div&quot;</span>);<br />        element.className = <span style="color: rgb(0, 96, 128);">&quot;itemTempl&quot;</span>;<br />        element.innerHTML = <span style="color: rgb(0, 96, 128);">&quot;&lt;img alt='Databound image' style='visibility:hidden;'/&gt;&quot;</span> +<br />            <span style="color: rgb(0, 96, 128);">&quot;&lt;div class='content'&gt;...&lt;/div&gt;&quot;</span>;<br />    }<br />    <span style="color: rgb(0, 0, 255);">else</span> {<br />        <span style="color: rgb(0, 128, 0);">// clean up the recycled element so that we can reuse it </span><br />        element = recycled;<br />        label = element.querySelector(<span style="color: rgb(0, 96, 128);">&quot;.content&quot;</span>);<br />        label.innerHTML = <span style="color: rgb(0, 96, 128);">&quot;...&quot;</span>;<br />        img = element.querySelector(<span style="color: rgb(0, 96, 128);">&quot;img&quot;</span>);<br />        img.style.visibility = <span style="color: rgb(0, 96, 128);">&quot;hidden&quot;</span>;<br />    }<br />    <span style="color: rgb(0, 0, 255);">return</span> {<br />        element: element,<br />        renderComplete: itemPromise.then(<span style="color: rgb(0, 0, 255);">function</span> (item) {<br />            <span style="color: rgb(0, 128, 0);">// mutate the element to include the data</span><br />            <span style="color: rgb(0, 0, 255);">if</span> (!label) {<br />                label = element.querySelector(<span style="color: rgb(0, 96, 128);">&quot;.content&quot;</span>);<br />                img = element.querySelector(<span style="color: rgb(0, 96, 128);">&quot;img&quot;</span>);<br />            }<br />            label.innerText = item.data.title;<br />            img.src = item.data.thumbnail;<br />            img.style.visibility = <span style="color: rgb(0, 96, 128);">&quot;visible&quot;</span>;<br />        })<br />    };<br />}<br /></pre>
  </div>
</blockquote>

<p>In <i>renderComplete</i>, be sure to check for the existence of elements that you don’t create for a new placeholder, such as <i>label</i>, and create them here if needed.</p>

<p>If you’d like to clean out recycled items more generally, note that you can provide a function to the ListView’s <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211846.aspx" target="_blank">resetItem</a><b></b> property. This function would contain similar code to that shown above. The same is true for the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700726.aspx" target="_blank">resetGroupHeader</a><b></b> property, because you can use template functions for group headers as well as items. We haven’t spoken of these as much because group headers are far fewer and don’t typically have the same performance implications. Nevertheless, the capability is there.</p>

<h2>Multistage renderers</h2>

<p>This brings us to the penultimate optimization, the <i>multistage renderer</i>. This extends the recycling placeholder renderer to delay-load images and other media until the rest of the item is wholly present in the DOM. It also delays effects like animations until the item is actually on screen. This recognizes that users often pan around within a ListView quite rapidly, so it makes sense to asynchronously defer the more expensive operations until the ListView has come to a stable position.</p>

<p>The ListView provides the necessary hooks as members on the <b>item</b> result from <b>itemPromise</b>: a property called <b>ready</b> (a promise) and two methods, <b>loadImage</b> and <b>isOnScreen</b>, both of which return (more!) promises. That is:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">renderComplete: itemPromise.then(<span style="color: rgb(0, 0, 255);">function</span> (item) {<br />    <span style="color: rgb(0, 128, 0);">// item.ready, item.loadImage, and item.isOnScreen available</span><br />})<br /></pre>
  </div>
</blockquote>

<p>Here’s how you use them:</p>

<ul>
  <li><b>ready</b> Return this promise from the first completed handler in your chain. This promise is fulfilled when the full structure of the element has been rendered and is visible. This means you can chain another <b>then</b> with a completed handler in which you do other post-visibility work like loading images.</li>

  <li><b>loadImage</b> Downloads an image from a URI and displays it in the given <i>img</i> element, returning a promise that’s fulfilled with that same element. You attach a completed handler to this promise, which itself returns the promise from <b>isOnScreen</b>. Note that <b>loadImage</b> will create an <i>img</i> element if one isn’t provided and deliver it to your completed handler.</li>

  <li><b>isOnScreen</b> Returns a promise whose fulfillment value is a Boolean indicating whether the item is visible or not. In present implementations, this is a known value so the promise is fulfilled synchronously. By wrapping it in a promise, though, it can be used in a longer chain.</li>
</ul>

<p>We see all this in the sample’s <b>multistageRenderer</b> function, where completion of the image load is used to start a fade-in animation. Here I’m just showing what’s returned from the <i>renderComplete</i> promise:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">renderComplete: itemPromise.then(<span style="color: rgb(0, 0, 255);">function</span> (item) {<br />    <span style="color: rgb(0, 128, 0);">// mutate the element to update only the title</span><br />    <span style="color: rgb(0, 0, 255);">if</span> (!label) { label = element.querySelector(<span style="color: rgb(0, 96, 128);">&quot;.content&quot;</span>); }<br />    label.innerText = item.data.title;<br /><br />    <span style="color: rgb(0, 128, 0);">// use the item.ready promise to delay the more expensive work</span><br />    <span style="color: rgb(0, 0, 255);">return</span> item.ready;<br />    <span style="color: rgb(0, 128, 0);">// use the ability to chain promises, to enable work to be cancelled</span><br />}).then(<span style="color: rgb(0, 0, 255);">function</span> (item) {<br />    <span style="color: rgb(0, 128, 0);">// use the image loader to queue the loading of the image</span><br />    <span style="color: rgb(0, 0, 255);">if</span> (!img) { img = element.querySelector(<span style="color: rgb(0, 96, 128);">&quot;img&quot;</span>); }<br />    <span style="color: rgb(0, 0, 255);">return</span> item.loadImage(item.data.thumbnail, img).then(<span style="color: rgb(0, 0, 255);">function</span> () {<br />        <span style="color: rgb(0, 128, 0);">// once loaded check if the item is visible</span><br />        <span style="color: rgb(0, 0, 255);">return</span> item.isOnScreen();<br />    });<br />}).then(<span style="color: rgb(0, 0, 255);">function</span> (onscreen) {<br />    <span style="color: rgb(0, 0, 255);">if</span> (!onscreen) {<br />        <span style="color: rgb(0, 128, 0);">// if the item is not visible, don't animate its opacity</span><br />        img.style.opacity = 1;<br />    } <span style="color: rgb(0, 0, 255);">else</span> {<br />        <span style="color: rgb(0, 128, 0);">// if the item is visible, animate the opacity of the image</span><br />        WinJS.UI.Animation.fadeIn(img);<br />    }<br />})<br /></pre>
  </div>
</blockquote>

<p>Even though there’s a lot going on, we still just have a basic promise chain here. The first async operation in the renderer updates simple parts of the item element structure, such as text. It then returns the promise in <b>item.ready</b>. When that promise is fulfilled—or, more accurately, if that promise is fulfilled—we use the item’s async <b>loadImage</b> method to kick off an image download, returning the <b>item.isOnScreen</b> promise from that completed handler. This means that the <i>onscreen</i> visibility flag gets passed to the final completed handler in the chain. When and if that <b>isOnScreen</b> promise is fulfilled—meaning the item is actually visible—we can perform relevant operations like animations.</p>

<p>I emphasize the if part because it’s again likely that the user will be panning around within the ListView while all this is happening. Having all these promises chained together again makes it possible for the ListView to cancel the async operations whenever these items are panned out of view and/or off any buffered pages. Suffice it to say that the ListView control has gone through a <i>lot</i> of performance testing!</p>

<p>It’s also important to remind ourselves again that we’re using <b>then</b> throughout all these chains because we’re still returning a promise from the rendering function within the <i>renderComplete</i> property. We’re never the end of the chain in these renderers, so we’ll never use <b>done</b> at the end.</p>

<h2>Thumbnail batching</h2>

<p>The last optimization is truly the <i>coup de grace</i> for the ListView control. In the function called <b>batchRenderer</b>, we find this structure for <i>renderComplete</i> (most code omitted):</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">renderComplete: itemPromise.then(function (i) {<br />    item = i;<br />    <span style="color: rgb(0, 128, 0);">// ...</span><br />    <span style="color: rgb(0, 0, 255);">return</span> item.ready;<br />}).then(function () {<br />    <span style="color: rgb(0, 0, 255);">return</span> item.loadImage(item.data.thumbnail);<br />}).then(thumbnailBatch()<br />).then(function (newimg) {<br />    img = newimg;<br />    element.insertBefore(img, element.firstElementChild);<br />    <span style="color: rgb(0, 0, 255);">return</span> item.isOnScreen();<br />}).then(function (onscreen) {<br />    <span style="color: rgb(0, 128, 0);">//...</span><br />})<br /></pre>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </div>
</blockquote>

<p>This is almost the same as the <b>multistageRenderer</b> except for the insertion of this mysterious call to a function called <b>thumbnailBatch</b> between the <b>item.loadImage</b> call and the <b>item.isOnScreen</b> check. The placement of <b>thumbnailBatch</b> in the chain indicates that its return value must be a completed handler that itself returns another promise.</p>

<p>Confused? Well, we’ll get to the bottom of it! But we first need a little more background as to what we’re trying to accomplish.</p>

<p>If we just had a ListView with a single item, various loading optimizations wouldn’t be noticeable. But ListViews typically have many items, and the rendering function is called for each one. In the <b>multistageRenderer</b> of the previous section, the rendering of each item kicks off an async <b>item.loadImage</b> operation to download its thumbnail from an arbitrary URI, and each operation can take an arbitrary amount of time. So for the list as a whole, we might have a bunch of simultaneous <b>loadImage</b> calls going on, with the rendering of each item waiting on the completion of its particular thumbnail. So far so good.</p>

<p>An important characteristic that’s not at all visible in <b>multistageRenderer</b>, however, is that the <i>img</i> element for the thumbnail is <i>already</i> in the DOM, and the <b>loadImage</b> function sets that image’s <i>src</i> attribute as soon as the download has finished. This in turn triggers an update in the rendering engine as soon as we return from the rest of the promise chain, which is essentially synchronous after that point.</p>

<p>It’s possible, then, that a bunch of thumbnails could come back to the UI thread within a short amount of time. This will cause excess churn in the rendering engine and poor visual performance. To avoid this churn, we want to fully create these <i>img</i> elements <i>before</i> they’re in the DOM, and then add them in batches such that they’re all handled in a single rendering pass.</p>

<p>The sample does this through a piece of promise-magic code a function called <b>createBatch</b>. <b>createBatch</b> is called just once for the whole app, and its result—another function—is stored in the variable named <b>thumbnailBatch</b>:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> thumbnailBatch;<br />thumbnailBatch = createBatch();<br /></pre>
  </div>
</blockquote>

<p>A call to this <b>thumbnailBatch</b> function, as I’ll refer to it from here on, is again inserted into the promise chain of the renderer. This purpose of this insertion, given the nature of the batching code as we’ll see shortly, is to group together a set of loaded <i>img</i> elements, releasing them for further processing at suitable intervals. Again, just looking at the promise chain in the renderer, a call to <b>thumbnailBatch()</b> must return a completed handler function that returns a promise, and the fulfillment value of that promise (looking at the next step in the chain) must be an <i>img</i> element that can then be added to the DOM. By adding those images to the DOM <i>after</i> the batching has taken place, we combine that whole group into the same rendering pass.</p>

<p>This is an important difference between the <b>batchRenderer</b> and the <b>multistageRenderer</b> of the previous section: in the latter, the thumbnail’s <i>img</i> element already exists in the DOM and is passed to <b>loadImage</b> as the second parameter. So when <b>loadImage</b> sets the image’s <i>src</i> attribute, a rendering update is triggered. Within <b>batchRenderer</b>, however, that <i>img</i> element is separately created within <b>loadImage</b> (where <i>src</i> is also set), but the <i>img</i> is not yet in the DOM. It’s only added to the DOM after the <b>thumbnailBatch</b> step completes, making it part of a group within that single layout pass.</p>

<p>So now let’s see how that batching works. Here’s the <b>createBatch</b> function in its entirety:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">function</span> createBatch(waitPeriod) {<br />    <span style="color: rgb(0, 0, 255);">var</span> batchTimeout = WinJS.Promise.<span style="color: rgb(0, 0, 255);">as</span>();<br />    <span style="color: rgb(0, 0, 255);">var</span> batchedItems = [];<br /><br />    <span style="color: rgb(0, 0, 255);">function</span> completeBatch() {<br />        <span style="color: rgb(0, 0, 255);">var</span> callbacks = batchedItems;<br />        batchedItems = [];<br />        <span style="color: rgb(0, 0, 255);">for</span> (<span style="color: rgb(0, 0, 255);">var</span> i = 0; i &lt; callbacks.length; i++) {<br />            callbacks[i]();<br />        }<br />    }<br /><br />    <span style="color: rgb(0, 0, 255);">return</span> <span style="color: rgb(0, 0, 255);">function</span> () {<br />        batchTimeout.cancel();<br />        batchTimeout = WinJS.Promise.timeout(waitPeriod || 64).then(completeBatch);<br /><br />        <span style="color: rgb(0, 0, 255);">var</span> delayedPromise = <span style="color: rgb(0, 0, 255);">new</span> WinJS.Promise(<span style="color: rgb(0, 0, 255);">function</span> (c) {<br />            batchedItems.push(c);<br />        });<br /><br />        <span style="color: rgb(0, 0, 255);">return</span> <span style="color: rgb(0, 0, 255);">function</span> (v) {<br />            <span style="color: rgb(0, 0, 255);">return</span> delayedPromise.then(<span style="color: rgb(0, 0, 255);">function</span> () {<br />                <span style="color: rgb(0, 0, 255);">return</span> v;<br />            });<br />        };<br />    };<br />}<br /></pre>
  </div>
</blockquote>

<p>Again, <b>createBatch</b> is called just <i>once</i> and its <b>thumbnailBatch</b> result is called for <i>each </i>rendered item<i> </i>in the list. The completed handler that <b>thumbnailBatch</b> generates is then called whenever a <b>loadImage</b> operation completes.</p>

<p>Such a completed handler might just as easily have been inserted directly into the rendering function, but what we’re trying to do here is coordinate activities <i>across multiple items </i>rather than just on a per-item basis. This coordination is achieved through the two variables created and initialized at the beginning of <b>createBatch</b>: <i>batchedTimeout</i>, initialized as an empty promise, and <i>batchedItems</i>, initialized an array of functions that’s initially empty. <b>createBatch</b> also declares a function, <b>completeBatch</b>, that simply empties <i>batchedItems</i>, calling each function in the array:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">function</span> completeBatch() {<br />    <span style="color: rgb(0, 128, 0);">// Copy and clear the array so that the next batch can start to accumulate</span><br />    <span style="color: rgb(0, 128, 0);">// while we're processing the previous one.</span><br />    <span style="color: rgb(0, 0, 255);">var</span> callbacks = batchedItems;<br />    batchedItems = [];<br />    <span style="color: rgb(0, 0, 255);">for</span> (<span style="color: rgb(0, 0, 255);">var</span> i = 0; i &lt; callbacks.length; i++) {<br />        callbacks[i]();<br />    }<br />}</pre>
  </div>
</blockquote>

<p>Now let’s see what happens within <b>thumbnailBatch</b> (the function returned from <b>createBatch</b>), which is again called for each item being rendered. First, we <i>cancel</i> any existing <i>batchedTimeout</i> and immediately recreate it:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">batchTimeout.cancel();<br />batchTimeout = WinJS.Promise.timeout(waitPeriod || 64).then(completeBatch);<br /></pre>
  </div>
</blockquote>

<p>The second line shows the future delivery/fulfillment pattern discussed in the All About Promises post &lt;TODO: link&gt;: it says to call <b>completeBatch</b> after a delay of <i>waitPeriod</i> milliseconds (with a default of 64ms). This means that so long as <b>thumbnailBatch</b> is being called again within <i>waitPeriod</i> of a previous call, <b>batchTimeout</b> will be reset to another <i>waitPeriod</i>. And because <b>thumbnailBatch</b> is only called <i>after </i>an <b>item.loadImage</b> call completes, we’re effectively saying that any <b>loadImage</b> operations that complete within <i>waitPeriod</i> of the previous one will be included in the same batch. When there’s a gap longer than <i>waitPeriod</i> the batch is processed—images are added to the DOM—and the next batch begins.</p>

<p>After handling this timeout business, the <b>thumbnailBatch</b> creates a new promise that simply pushes the complete dispatcher function into the <i>batchedItems</i> array:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">var delayedPromise = <span style="color: rgb(0, 0, 255);">new</span> WinJS.Promise(function (c) {<br />    batchedItems.push(c);<br />});<br /></pre>
  </div>
</blockquote>

<p>Remember from All About Promises &lt;TODO: link&gt; that a promise is just a code construct, and that’s all we have here. The newly created promise has no async behavior in and of itself: we’re just adding the complete dispatcher function, <i>c</i>, to <i>batchedItems</i>. But of course, we don’t do anything with the dispatcher until <i>batchedTimeout</i> completes asynchronously, so there is in fact an async relationship here. When the timeout happens and we clear the batch (inside <b>completeBatch</b>), we’ll invoke any completed handlers given elsewhere to <b>delayedPromise.then</b>.</p>

<p>This brings us to the last lines of code in <b>createBatch</b>, which is the function that <b>thumbnailBatch</b> actually returns. This function is exactly the completed handler that gets inserted into the renderer’s whole promise chain:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">return</span> <span style="color: rgb(0, 0, 255);">function</span> (v) {<br />    <span style="color: rgb(0, 0, 255);">return</span> delayedPromise.then(<span style="color: rgb(0, 0, 255);">function</span> () {<br />        <span style="color: rgb(0, 0, 255);">return</span> v;<br />    });<br />};<br /></pre>
  </div>
</blockquote>

<p>In fact, let’s put this piece of code directly into the promise chain so we can see the resulting relationships:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">return</span> item.loadImage(item.data.thumbnail);<br />}).then(<span style="color: rgb(0, 0, 255);">function</span> (v) {<br />    <span style="color: rgb(0, 0, 255);">return</span> delayedPromise.then(<span style="color: rgb(0, 0, 255);">function</span> () {<br />        <span style="color: rgb(0, 0, 255);">return</span> v;<br />    });<br />).then(<span style="color: rgb(0, 0, 255);">function</span> (newimg) {<br /></pre>
  </div>
</blockquote>

<p>Now we can see that the argument <i>v</i> is the result of <b>item.loadImage</b>, which is the <i>img</i> element created for us. If we didn’t want to do batching, we could just say <b>return WinJS.Promise.as(v)</b> and the whole chain would still work: <i>v</i> would then be passed on synchronously and show up as <i>newimg</i> in the next step.</p>

<p>Instead, though, we’re returning a promise from <b>delayedPromise.then</b> which won’t be fulfilled—with <i>v</i>—until the current <i>batchedTimeout</i> is fulfilled. At that time—when again there’s a gap of <i>waitPeriod</i> between <b>loadImage</b> completions—those <i>img</i> elements are then delivered to the next step in the chain where they’re added to the DOM.</p>

<p>And that’s it!</p>

<h2>In Closing</h2>

<p>The five different rendering functions demonstrated in the <a href="http://code.msdn.microsoft.com/windowsapps/ListView-performance-39fb71f0" target="_blank">HTML ListView optimizing performance sample</a> all have one thing in common: they show how the asynchronous relationship between the ListView and the renderer—expressed through promises—allows the renderer tremendous flexibility in how and when it produces elements for items in the list. In writing your own apps, the strategy you use for ListView optimization greatly depends on the size of your data source, the complexity of the items themselves, and the amount of data that you’re obtaining asynchronously for those items (such as downloading remote images). Clearly, you’ll want to keep item renderers as simple as you can to still meet your performance goals. But in any case, you now have all the tools you need to help the ListView—and your app—perform its best.</p>

<p>Kraig Brockschmidt 
  <br />Program Manager, Windows Ecosystem Team 

  <br />Author, <a href="http://blogs.msdn.com/b/microsoft_press/archive/2012/10/29/free-ebook-programming-windows-8-apps-with-html-css-and-javascript.aspx"><i>Programming Windows 8 Apps in HTML, CSS, and JavaScript</i></a></p>]]></content:encoded>
    </item>
    <item>
      <title>All about promises (for Windows Store apps written in JavaScript)</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/all-about-promises-for-windows-store-apps-written-in-javascript</link>
      <pubDate>Tue, 11 Jun 2013 08:30:00 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/06/11/all-about-promises-for-windows-store-apps-written-in-javascript/</guid>
      <description><![CDATA[When writing Windows Store apps in JavaScript, you encounter these constructs called promises as...]]></description>
      <content:encoded><![CDATA[<p>When writing Windows Store apps in JavaScript, you encounter these constructs called <i><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh700339.aspx">promises</a> </i>as soon as you do anything that involves an asynchronous API. It also doesn’t take very long before writing promise chains for sequential asynchronous operations becomes second nature.</p>  <p>In the course of your development work, however, you’ll probably encounter other uses of promises where it’s not entirely clear to see what’s going on. A good example of this is optimizing item rendering functions for a ListView control as shown in the <a href="http://code.msdn.microsoft.com/windowsapps/ListView-performance-39fb71f0">HTML ListView optimizing performance sample</a>. We’ll explore this in a subsequent post. Or consider this little gem that Josh Williams showed in his <a href="https://channel9.msdn.com/Events/Build/2012/4-101">Deep Dive into WinJS</a> talk at //build 2012 (slightly modified):</p>  <blockquote>   <div id="codeSnippetWrapper">     <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">list.reduce(<span style="color: rgb(0, 0, 255);">function</span> callback (prev, item, i) {<br />    <span style="color: rgb(0, 0, 255);">var</span> result = doOperationAsync(item);<br />    <span style="color: rgb(0, 0, 255);">return</span> WinJS.Promise.join({ prev: prev, result: result}).then(<span style="color: rgb(0, 0, 255);">function</span> (v) {<br />        console.log(i + <span style="color: rgb(0, 96, 128);">&quot;, item: &quot;</span> + item+ <span style="color: rgb(0, 96, 128);">&quot;, &quot;</span> + v.result);<br />    });<br />})<br /></pre>
  </div>
</blockquote>

<p>This snippet joins promises for parallel async operations and delivers their results sequentially according to the order in <i>list</i>. If you can look at this code and immediately understand what it does, feel free to skip this post altogether! If not, let’s take a closer look at how promises really work, and their expression in WinJS—the Windows Library for JavaScript—so we can understand these kinds of patterns.</p>

<h2>What is a promise, exactly? The promise relationships</h2>

<p>Let’s begin with a fundamental truth: a promise is really nothing more than a code construct or, if you will, a calling convention. As such, promises have no inherent relationship to async operations—they just so happen to be very <i>useful </i>in that regard! A promise is simply an object representing a value that might be available at some point in the future, or might already be available. In this way, a promise is just like how we use the term in human relationships. If I say, “I promise to deliver you a dozen donuts,” then clearly I don’t need to have those donuts in my possession right now, but I certainly assume that I <i>will </i>have them some time in the future. And when I do, I’ll deliver them.</p>

<p>A promise thus implies a relationship between two agents: the <i>originator</i> who makes the promise to deliver some goods, and the <i>consumer </i>who is both the recipient of that promise and the goods themselves. How the originator goes about obtaining those goods is its own business. Similarly, the consumer can do whatever it wants with the promise itself and the delivered goods. It can even share the promise with other consumers.</p>

<p>Between originator and consumer, there are also two stages of this relationship, <i>creation</i> and <i>fulfillment</i>. All this is shown in the following diagram.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/0844.promise_diagram_577C7B9B.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/0844.promise_5F00_diagram_5F00_577C7B9B.png"><img title="promise_diagram" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="promise_diagram" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/0458.promise_diagram_thumb_0FBAF2B4.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/0458.promise_5F00_diagram_5F00_thumb_5F00_0FBAF2B4.png" width="700" height="341" /></a></p>

<p>Having two stages of the relationship is why promises work well with asynchronous delivery, as we can see when we follow the flow in the diagram. The key part is that once the consumer gets acknowledgment of the request—the promise—it can go on with life (asynchronously) rather than waiting (synchronously). This means the consumer can do something else while it’s waiting for the promise to be fulfilled, such as responding to other requests, which is the whole purpose of async APIs in the first place. And what if the goods are already available? Then the promise is immediately fulfilled, making the whole thing a kind of synchronous calling convention.</p>

<p>Of course, there’s a bit more to this relationship that we have to consider. You’ve certainly made promises in your life, and have had promises made to you. Although many of those promises have been fulfilled, the reality is that many promises are broken—it’s possible for the pizza delivery person to have an accident on the way to your home! Broken promises are just a fact of life, one that we have to accept in both our personal lives and in asynchronous programming.</p>

<p>Within the promise relationship, then, this means that originator needs a way to say, “I’m sorry, but I can’t make good on this promise” and the consumer needs a way to know that this is the case. Secondly, as consumers, we can sometimes be rather impatient about promises made to us! So if the originator can track its progress in fulfilling its promise, the consumer also needs a way to receive that information. And third, the consumer can also cancel the order and tell the originator that it no longer needs the goods.</p>

<p>Adding these requirements to the diagram, we can now see the complete relationship:</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/4251.promise_diagram_2_23D40F3D.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/4251.promise_5F00_diagram_5F00_2_5F00_23D40F3D.png"><img title="promise_diagram_2" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="promise_diagram_2" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/0550.promise_diagram_2_thumb_1CB4D2C5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/0550.promise_5F00_diagram_5F00_2_5F00_thumb_5F00_1CB4D2C5.png" width="700" height="432" /></a></p>

<p>Let’s now see how these relationships manifest in code.</p>

<h2>The promise construct and promise chains</h2>

<p>There are actually a number of different proposals or specifications for promises. The one used in Windows and WinJS is known as <a href="http://wiki.commonjs.org/wiki/Promises/A">Common JS/Promises A</a>, which says a promise—what’s returned by an originator to represent a value to deliver in the future—is an object with a function called <b>then</b>. Consumers subscribe to fulfillment of the promise by calling <b>then</b>. (Promises in Windows also support a similar function called <b>done</b> that’s used in promise chains, as we’ll see shortly.)</p>

<p>To this function the consumer passes up to three optional functions as arguments, in this order:</p>

<ol>
  <li>A <i>completed handler</i>. The originator calls this function when the promised value is available, and if that value already <i>is </i>available, the completed handler is called immediately (synchronously) from within <b>then</b>.</li>

  <li>An optional <i>error handler</i> that’s called when there’s a failure to acquire the promised value. For any given promise, the completed handler is never called if the error handler has been called.</li>

  <li>An optional <i>progress handler</i>, that’s periodically called with intermediate results if the operation supports it. (In WinRT, this means the API has a return value of <b>IAsync[Action | Operation]WithProgress</b>; those with <b>IAsync[Action | Operation]</b> don’t.)</li>
</ol>

<p>Note that you can pass <i>null</i> for any of these arguments, as when you want to attach only an error handler and not a completed handler. </p>

<p>On the other side of the relationship, a consumer may subscribe as many handlers as it wants to the same promise by calling <b>then</b> multiple times. It can also share the promise with other consumers who may also call <b>then</b> to their hearts’ content. This is entirely supported.</p>

<p>This means that a promise must manage lists of all the handlers it receives and invoke them at the appropriate times. Promises also need to allow for cancellation, as outlined in the full relationship.</p>

<p>The other requirement that comes from the <i>Promises A</i> specification is that the <b>then</b> method itself returns a promise. This second promise is fulfilled when the completed handler given to the first <b>promise.then</b> returns, with the return value being delivered as the result of this second promise. Consider this code snippet:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> promise1 = someOperationAsync();<br /><span style="color: rgb(0, 0, 255);">var</span> promise2 = promise1.then(<span style="color: rgb(0, 0, 255);">function</span> completedHandler1 (result1) { <span style="color: rgb(0, 0, 255);">return</span> 7103; } );<br />promise2.then(<span style="color: rgb(0, 0, 255);">function</span> completedHandler2 (result2) { });<br /></pre>
  </div>
</blockquote>

<p>The chain of execution here is that <b>someOperationAsync</b> gets started, returning <i>promise1</i>. While that operation is underway, we call <b>promise1.then</b>, which immediately returns <i>promise2</i>. Be very clear that <b>completedHandler1</b> is not called unless the result of the async operation is already available. Let’s assume we’re still waiting, so we go right into the call to <b>promise2.then</b>, and again, completedHandler2 will <i>not </i>be called at this time.</p>

<p>Sometime later, <b>someOperationAsync</b> completes with a value of, say, 14618. <i>promise1 </i>is now fulfilled, so it calls <b>completedHandler1</b> with that value, so <i>result1</i> will be 14618. <b>completedHandler1</b> now executes, returning the value 7103. At this point <i>promise2 </i>is fulfilled, so it calls <b>completedHandler2</b> with <i>result2 </i>equal to 7103.</p>

<p>Now what if a completed handler returns another promise? This case is handled a little differently. Let’s say that <b>completedHandler1</b> in the code above returns a promise like so:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> promise2 = promise1.then(<span style="color: rgb(0, 0, 255);">function</span> completedHandler1 (result1) {<br />    <span style="color: rgb(0, 0, 255);">var</span> promise2a = anotherOperationAsync();<br />    <span style="color: rgb(0, 0, 255);">return</span> promise2a;<br />});<br /></pre>
  </div>
</blockquote>

<p>In this case, <i>result2 </i>in <b>completedHandler2 </b>won’t be <i>promise2a</i> itself, but the <u>fulfillment</u> value of <i>promise2a</i>. That is, because the completed handler returns a promise, <i>promise2</i> as returned from <b>promise1.then</b>, will be fulfilled with the results of <i>promise2a</i>.</p>

<p>This characteristic is precisely what makes it possible to chain together sequential async operations, where the results from each operation in the chain feeds into the next. Without intermediate variables or named handlers, you often see this pattern for promise chains:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">operation1().then(<span style="color: rgb(0, 0, 255);">function</span> (result1) {<br />    <span style="color: rgb(0, 0, 255);">return</span> operation2(result1)<br />}).then(<span style="color: rgb(0, 0, 255);">function</span> (result2) {<br />    <span style="color: rgb(0, 0, 255);">return</span> operation3(result2);<br />}).then(<span style="color: rgb(0, 0, 255);">function</span> (result3) {<br />    <span style="color: rgb(0, 0, 255);">return</span> operation4(result3);<br />}).then(<span style="color: rgb(0, 0, 255);">function</span> (result4) {<br />    <span style="color: rgb(0, 0, 255);">return</span> operation5(result4)<br />}).then(<span style="color: rgb(0, 0, 255);">function</span> (result5) {<br />    <span style="color: rgb(0, 128, 0);">//And so on</span><br />});<br /></pre>
  </div>
</blockquote>

<p>Each completed handler, of course, will likely do something more with the results it receives, but in all chains you’ll see this core structure. What’s also true is that all the <b>then</b> methods here execute one right after the other, as all they’re doing is saving away the given completed handler and returning another promise. So by the time we reach the end of this code, only <i>operation1 </i>has started and no completed handlers have been called. But a bunch of intermediate promises from all the <b>then</b> calls have been created and wired up to one another to manage the chain as the sequential operations progress.</p>

<p>It’s worth noting that the same sequence can be achieved by nesting each subsequent operation within the previous completed handler, in which case you won’t have all the <i>return</i> statements. However, such nestings become an indentation nightmare, especially if you start adding progress and error handlers with each call to <b>then</b>.</p>

<p>Speaking of which, one of the features of promises in WinJS is that errors that occur in any part of the chain automatically propagate to the end of the chain. This means you should be able to simply attach a single error handler on the last call to <b>then</b> instead of having handlers at every level. The caveat, however, is that for various subtle reasons, those errors get swallowed if the last link in the chain is a call to <b>then</b>. This is why WinJS also provides a <b>done</b> method on promises. This method accepts the same arguments as <b>then</b> but indicates that the chain is complete (it returns <i>undefined </i>rather than another promise). Any error handler attached to <b>done</b> is then called for any errors in the entire chain. Furthermore, lacking an error handler, <b>done</b> throws an exception to the app level where it can be handled by <b>window.onerror</b> of <b>WinJS.Application.onerror</b> events. In short, all chains should ideally end in <b>done</b> to make sure exceptions surface and get handled properly.</p>

<p>Of course, if you write a function whose <i>purpose</i> is to return the last promise from a long chain of <b>then</b> calls, you’ll still use <b>then </b>at the end: the responsibility for handling errors then belongs to the caller who might use that promise in another chain altogether.</p>

<h2>Creating promises: the WinJS.Promise class</h2>

<p>While you can always create your own promise classes around the <i>Promises A</i> spec, it’s actually quite a lot of work that’s best left to a library. For this reason WinJS provides a robust, well-tested, and flexible promise class called <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx"><b>WinJS.Promise</b></a>. This allows you to easily create promises around different values and operations without having to manage the details of the originator/consumer relationships or the behavior of <b>then</b>.</p>

<p>When needed, you can (and should) use <b>new WinJS.Promise</b>–or a suitable helper function, as noted in the next section—to create promises around both asynchronous operations and existing (synchronous) values alike. Remember that a promise is just a code construct: there’s no requirement that a promise has to wrap an async operation or async <i>anything</i>. Similarly, the mere act of wrapping some piece of code in a promise doesn’t automatically <i>make </i>it run asynchronously<i>. </i>That’s still work you have to do yourself.</p>

<p>As a simple example of using <b>WinJS.Promise</b> directly, let’s say we want to perform a long computation—just adding up a bunch of numbers from one to some maximum—but do it asynchronously. We could invent our own callback mechanism for such a routine, but if we wrap it within a promise, we allow it to be chained or joined with other promises from other APIs. (Along these lines, the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br229787.aspx"><b>WinJS.xhr</b></a> function wraps the asynchronous <b>XmlHttpRequest</b> of JavaScript within a promise, so you don’t have to deal with the latter’s particular event structure.)</p>

<p>We can of course use a JavaScript worker for a long computation, of course, but for the sake of illustration we’ll just keep this on the UI thread and use <b>setImmediate</b> to break the operation into steps. Here’s how we can implement it within a promise structure using <b>WinJS.Promise</b>:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">function</span> calculateIntegerSum(max, step) {<br />    <span style="color: rgb(0, 128, 0);">//The WinJS.Promise constructor's argument is an initializer function that receives </span><br />    <span style="color: rgb(0, 128, 0);">//dispatchers for completed, error, and progress cases.</span><br />    <span style="color: rgb(0, 0, 255);">return</span> <span style="color: rgb(0, 0, 255);">new</span> WinJS.Promise(<span style="color: rgb(0, 0, 255);">function</span> (completeDispatch, errorDispatch, progressDispatch) {<br />        <span style="color: rgb(0, 0, 255);">var</span> sum = 0;<br /><br />        <span style="color: rgb(0, 0, 255);">function</span> iterate(args) {<br />            <span style="color: rgb(0, 0, 255);">for</span> (<span style="color: rgb(0, 0, 255);">var</span> i = args.start; i &lt; args.end; i++) {<br />                sum += i;<br />            };<br /><br />            <span style="color: rgb(0, 0, 255);">if</span> (i &gt;= max) {<br />                <span style="color: rgb(0, 128, 0);">//Complete--dispatch results to completed handlers</span><br />                completeDispatch(sum);<br />            } <span style="color: rgb(0, 0, 255);">else</span> {<br />                <span style="color: rgb(0, 128, 0);">//Dispatch intermediate results to progress handlers</span><br />                progressDispatch(sum);<br />                setImmediate(iterate, { start: args.end, end: Math.min(args.end + step, max) });<br />            }<br />        }<br />            <br />        setImmediate(iterate, { start: 0, end: Math.min(step, max) });<br />    });<br />}<br /></pre>
  </div>
</blockquote>

<p>When calling <b>new WinJS.Promise</b>, the single argument to its constructor is an <i>initializer</i> function (anonymous in this case). The initializer encapsulates the operation to perform, but be very clear that this function itself executes <i>synchronously </i>on the UI thread. So if we just performed a long calculation here without using <b>setImmediate,</b> we would block the UI thread for all that time. Again, placing code inside a promise doesn’t<i> </i>automatically make it asynchronous—the initializer function needs to set that up itself.</p>

<p>For arguments, the initializer function receives three <i>dispatchers</i> for the completed, error, and progress cases that promises support. As you can see, we call these dispatchers at appropriate times during the operation with the appropriate arguments.</p>

<p>I call these functions “dispatchers” because they’re not the same thing as the handlers that consumers subscribe to the promise’s <b>then</b> method (or <b>done</b>, but I won’t keep reminding you). Under the hood, WinJS is managing arrays of those handlers, which is what allows any numbers of consumers to subscribe any number of handlers. When you invoke one of these dispatchers, WinJS iterates through its internal list and invokes all those handlers on your behalf. <b>WinJS.Promise</b> also makes sure that its <b>then</b> returns another promise, as required for chaining.</p>

<p>In short, <b>WinJS.Promise</b> is providing all the surrounding details of a promise. This allows you to concentrate on the core operation that the promise represents, which is embodied in the initializer function.</p>

<h2>Helpers for creating promises</h2>

<p>The primary helper function to create a promise is the static method <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211664.aspx"><b>WinJS.Promise.as</b></a>, which wraps <i>any</i> value in a promise. Such a wrapper on an already existing value just turns right around and calls any completed handler passed to <b>then</b>. This specifically allows you to treat arbitrary known values as promises, such that you can intermix and compose them (through joining or chaining) with other promises. Using <b>as</b> on an existing promise just returns that promise.</p>

<p>The other static helper function is <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br229729.aspx"><b>WinJS.Promise.timeout</b></a>, which provides a convenient wrapper around <b>setTimeout</b> and <b>setImmediate</b>. You can also create a promise that cancels a second promise if that second one is not fulfilled within a certain number of milliseconds.</p>

<p>Do note that the <b>timeout</b> promises around <b>setTimeout</b> and <b>setImmediate</b> are themselves fulfilled with <i>undefined</i>. A common question is then, “How can these be used to deliver some other result after the timeout?” The answer uses the fact that <b>then</b> returns another promise that’s fulfilled with the return value of the completed handler. This line of code, for example:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> p = WinJS.Promise.timeout(1000).then(<span style="color: rgb(0, 0, 255);">function</span> () { <span style="color: rgb(0, 0, 255);">return</span> 12345; });</pre>
  </div>
</blockquote>

<p>creates the promise <i>p</i> that will be fulfilled with the value 12345 after one second. In other words, <b>WinJS.Promise.timeout(…).then(function () { return &lt;value&gt;} )</b> is a pattern to deliver <i>&lt;value&gt;</i> after the given timeout. And if <i>&lt;value&gt;</i> itself is another promise, it means to deliver the fulfillment value from that promise at some point after the timeout.</p>

<h2>Cancellation and generating promise errors</h2>

<p>In the code we just saw, you might have noticed two deficiencies. First is that there’s no way to cancel the operation once it gets started. The second is that we don’t do a very good job handling errors.</p>

<p>The trick in both these cases is that promise-producing functions like <b>calculateIntegerSum</b> function must always return a promise. If an operation can’t complete or never gets started in the first place, that promise is in what’s called the <i>error state</i>. This means that the promise doesn’t have and never <i>will</i> have a result that it can pass to any completed handlers: it only ever calls its error handlers. Indeed, if a consumer calls <b>then</b> on a promise, that’s already in the error state, the promise immediately (synchronously) invokes the error handler given to <b>then</b>.</p>

<p>A <b>WinJS.Promise</b> enters the error state for two reasons: the consumer calls its <b>cancel</b> method or the code within the initializer function calls the error dispatcher. When this happens, error handlers are given whatever error value was either caught or propagated in the promise. If you’re creating an operation within a <b>WinJS.Promise</b>, you can also use an instance of <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211689.aspx"><b>WinJS.ErrorFromName</b></a>. This is just a JavaScript object that contains a <i>name</i> property identifying the error and a <i>message</i> property containing more information. For example, when a promise is canceled, error handlers receive an error object with both <i>name</i> and <i>message</i> name set to “Canceled”.</p>

<p>But now what if you can’t even start the operation in the first place? For example, if you call <b>calculateIntegerSum</b> with bad arguments (like 0, 0), it shouldn’t even attempt to start counting and should instead return a promise in the error state. Such is the purpose of the static method <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br229784.aspx"><b>WinJS.Promise.wrapError</b></a>. This takes an instance of <b>WinJS.ErrorFromName</b> and returns a promise in the error state, which we would return in this case instead of a new <b>WinJS.Promise</b> instance.</p>

<p>The other part to all this is that although a call to the promise’s <b>cancel</b> method puts the promise itself into the error state, how do we stop the async operation that’s underway? In the previous <b>calculateIntegerSum</b> implementation, it will just keep calling <b>setImmediate</b> until the operation is complete, regardless of the state of the promise we created. In fact, if the operation calls the complete dispatcher after the promise has been canceled, the promise just ignores that completion.</p>

<p>What’s needed, then, is a way for the promise to tell the operation that it no longer needs to continue its work. For this reason the <b>WinJS.Promise</b> constructor takes a second function argument that’s called if the promise is canceled. In our example, a call to this function would need to prevent the next call to <b>setImmediate</b>, thereby stopping the computation. Here’s how that looks, along with proper error handling:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">function</span> calculateIntegerSum(max, step) {<br />    <span style="color: rgb(0, 128, 0);">//Return a promise in the error state for bad arguments</span><br />    <span style="color: rgb(0, 0, 255);">if</span> (max &lt; 1 || step &lt; 1) {<br />        <span style="color: rgb(0, 0, 255);">var</span> err = <span style="color: rgb(0, 0, 255);">new</span> WinJS.ErrorFromName(<span style="color: rgb(0, 96, 128);">&quot;calculateIntegerSum&quot;</span>, <span style="color: rgb(0, 96, 128);">&quot;max and step must be 1 or greater&quot;</span>);<br />        <span style="color: rgb(0, 0, 255);">return</span> WinJS.Promise.wrapError(err);<br />    }<br /><br />    <span style="color: rgb(0, 0, 255);">var</span> _cancel = <span style="color: rgb(0, 0, 255);">false</span>;<br /><br />    <span style="color: rgb(0, 128, 0);">//The WinJS.Promise constructor's argument is an initializer function that receives </span><br />    <span style="color: rgb(0, 128, 0);">//dispatchers for completed, error, and progress cases.</span><br />    <span style="color: rgb(0, 0, 255);">return</span> <span style="color: rgb(0, 0, 255);">new</span> WinJS.Promise(<span style="color: rgb(0, 0, 255);">function</span> (completeDispatch, errorDispatch, progressDispatch) {<br />        <span style="color: rgb(0, 0, 255);">var</span> sum = 0;<br /><br />        <span style="color: rgb(0, 0, 255);">function</span> iterate(args) {<br />            <span style="color: rgb(0, 0, 255);">for</span> (<span style="color: rgb(0, 0, 255);">var</span> i = args.start; i &lt; args.end; i++) {<br />                sum += i;<br />            };<br /><br />            <span style="color: rgb(0, 128, 0);">//If for some reason there was an error, create the error with WinJS.ErrorFromName</span><br />            <span style="color: rgb(0, 128, 0);">//and pass to errorDispatch</span><br />            <span style="color: rgb(0, 0, 255);">if</span> (<span style="color: rgb(0, 0, 255);">false</span> <span style="color: rgb(0, 128, 0);">/* replace with any necessary error check -- we don’t have any here */</span>) {<br />                errorDispatch(<span style="color: rgb(0, 0, 255);">new</span> WinJS.ErrorFromName(<span style="color: rgb(0, 96, 128);">&quot;calculateIntegerSum (scenario 7)&quot;</span>, <span style="color: rgb(0, 96, 128);">&quot;error occurred&quot;</span>));<br />            }<br /><br />            <span style="color: rgb(0, 0, 255);">if</span> (i &gt;= max) {<br />                <span style="color: rgb(0, 128, 0);">//Complete--dispatch results to completed handlers</span><br />                completeDispatch(sum); <br />            } <span style="color: rgb(0, 0, 255);">else</span> {<br />                <span style="color: rgb(0, 128, 0);">//Dispatch intermediate results to progress handlers</span><br />                progressDispatch(sum);<br /><br />                <span style="color: rgb(0, 128, 0);">//Interrupt the operation if canceled</span><br />                <span style="color: rgb(0, 0, 255);">if</span> (!_cancel) {<br />                    setImmediate(iterate, { start: args.end, end: Math.min(args.end + step, max) });<br />                }<br />            }<br />        }<br />            <br />        setImmediate(iterate, { start: 0, end: Math.min(step, max) });<br />    },<br />    <span style="color: rgb(0, 128, 0);">//Cancellation function for the WinJS.Promise constructor</span><br />    <span style="color: rgb(0, 0, 255);">function</span> () {<br />        _cancel = <span style="color: rgb(0, 0, 255);">true</span>;<br />    });<br />}<br /></pre>
  </div>
</blockquote>

<p>Altogether, creating instances of <b>WinJS.Promise</b> has many uses. For example, if you have a library that talks to a web service through some other async method, you can wrap those operations within promises. You might also use a new promise to combine multiple async operations (or other promises!) from different sources into a single promise where you want control over all the relationships involved. Within the code of an initializer for <b>WinJS.Promise</b>, you can certainly have your own handlers for other async operations and their promises. You can use these to encapsulate automatic retry mechanisms for network timeouts and such, hook into a generic progress updater UI, or add under-the-hood logging or analytics. In all these ways, the rest of your code never needs to know about the details and can just deal with promises from the consumer side.</p>

<p>Along these lines, it’s fairly straightforward to wrap a JavaScript worker into a promise such that it looks and behaves like other asynchronous operations in WinRT. Workers, as you might know, deliver their results through a <b>postMessage</b> call that raises a <b>message</b> event on the worker object in the app. The following code, then, links that event to a promise that’s fulfilled with whatever results are delivered in that message:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 128, 0);">// This is the function variable we're wiring up.</span><br /><span style="color: rgb(0, 0, 255);">var</span> workerCompleteDispatch = <span style="color: rgb(0, 0, 255);">null</span>;<br /><br /><span style="color: rgb(0, 0, 255);">var</span> promiseJS = <span style="color: rgb(0, 0, 255);">new</span> WinJS.Promise(<span style="color: rgb(0, 0, 255);">function</span> (completeDispatch, errorDispatch, progressDispatch) {<br />    workerCompleteDispatch = completeDispatch;<br />});<br /><br /><span style="color: rgb(0, 128, 0);">// Worker is created here and stored in the 'worker' variable</span><br /><br /><span style="color: rgb(0, 128, 0);">// Listen for worker events</span><br />worker.onmessage = <span style="color: rgb(0, 0, 255);">function</span> (e) {<br />    <span style="color: rgb(0, 0, 255);">if</span> (workerCompleteDispatch != <span style="color: rgb(0, 0, 255);">null</span>) {<br />        workerCompleteDispatch(e.data.results); <span style="color: rgb(0, 128, 0);">/* event args depends on the worker */</span><br />    }<br />}<br /><br />promiseJS.done(<span style="color: rgb(0, 0, 255);">function</span> (result) {<br />    <span style="color: rgb(0, 128, 0);">// Output for JS worker</span><br />});<br /></pre>
  </div>
</blockquote>

<p>To expand this code to handle errors from the worker, you’d save the error dispatcher in another variable, have the <b>message</b> event handler check for error information in its event args, and the call the error dispatcher instead of the complete dispatcher as appropriate.</p>

<h2>Joining parallel promises</h2>

<p>As promises are often used to wrap asynchronous operations, it’s certainly possible that you can have multiple operations going on in parallel. In these cases, you might want to know when either one promise in a group is fulfilled, or when all the promises in the group are fulfilled. The static functions <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br229660.aspx"><b>WinJS.Promise.any</b></a> and <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211774.aspx"><b>WinJS.Promise.join</b></a> provide for this.</p>

<p>Both functions accept an array of value or an object with value properties. Those values can be promises, and any non-promise values are wrapped with <b>WinJS.Promise.as</b>, such that the whole array or object is composed of promises.</p>

<p>Here are the characteristics of <b>any</b>:</p>

<ul>
  <li><b>any</b> creates a single promise that is fulfilled when one of the others is fulfilled or fails with an error (a logical OR). In essence, <b>any</b><i> </i>attaches completed handlers to all those promises, and as soon as one completed handler is called, it calls whatever completed handlers the <b>any</b><i> </i>promise has itself received.</li>

  <li>After the <b>any</b><i> </i>promise is fulfilled (that is, after the first promise in the list is fulfilled), the other operations in the list continue to run, calling whatever completed, error, or progress handlers are assigned to those promises individually.</li>

  <li>If you cancel the promise from <b>any</b>, then all the promises in the list are canceled.</li>
</ul>

<p>As for <b>join</b>:</p>

<ul>
  <li><b>join</b> creates a single promise that is fulfilled when <i>all</i> the others are fulfilled or fail with errors (a logical AND). In essence, <b>join</b><i> </i>attaches completed and error handlers to all those promises, and waits until all those handlers are called before it calls whatever completed handlers it receives itself.</li>

  <li>The <b>join</b> promise also reports progress to any progress handlers you provide. The intermediate result in this case is an array of results from those individual promises that have been fulfilled so far.</li>

  <li>If you cancel promise from <b>join</b> it cancels all the other promises that are still pending.</li>
</ul>

<p>Beyond <b>any</b> and <b>join</b>, there are two other static <b>WinJS.Promise</b> methods to know about, which can come in handy:</p>

<ul>
  <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211765.aspx"><b>is</b></a> determines whether an arbitrary value is a promise, returning a Boolean. It basically makes sure it’s an object with a function named “then”; it doesn’t test for “done”.</li>

  <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br229727.aspx"><b>theneach</b></a><i> </i>applies completed, error, and progress handlers to a group of promises (using <b>then</b>), returning the results as another group of values inside a promise. Any of the handlers can be <i>null</i>.</li>
</ul>

<h2>Parallel promises with sequential results</h2>

<p>With <b>WinJS.Promise.join</b> and <b>WinJS.Promise.any</b> we have the ability to work with parallel promises, that is, with parallel async operations. The promise returned by <b>join</b>, again, is fulfilled when all the promises in an array are fulfilled. However, those promises will likely complete in a random order. What if you have a set of operations that can execute this way, but you want to process their results in a well-defined order, namely the order that their promises appear in an array?</p>

<p>To do this you need to join each subsequent promise to the <b>join</b> of all those that came before, and the bit of code with which we began this post does exactly that. Here’s that code again, but rewritten to make the promises explicit. (Assume <i>list</i><b> </b>is an array of values of some sort that are used as arguments for a hypothetical promise-producing async call <b>doOperationAsync</b>):</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">list.reduce(<span style="color: rgb(0, 0, 255);">function</span> callback (prev, item, i) {<br />    <span style="color: rgb(0, 0, 255);">var</span> opPromise = doOperationAsync(item);<br />    <span style="color: rgb(0, 0, 255);">var</span> join = WinJS.Promise.join({ prev: prev, result: opPromise});<br /><br />    <span style="color: rgb(0, 0, 255);">return</span> join.then(<span style="color: rgb(0, 0, 255);">function</span> completed (v) {<br />        console.log(i + <span style="color: rgb(0, 96, 128);">&quot;, item: &quot;</span> + item+ <span style="color: rgb(0, 96, 128);">&quot;, &quot;</span> + v.result);<br />    });<br />})<br /></pre>
  </div>
</blockquote>

<p>To understand this code we have to first understand how the array’s <a href="http://msdn.microsoft.com/en-us/library/ie/ff679975(v=vs.94).aspx"><b>reduce</b></a> method works. For each item in the array, <b>reduce</b> calls the function argument, here named <b>callback</b>, which receives four arguments (only three of which are used in the code):</p>

<ul>
  <li><i>prev</i> The value that was returned from the <i>previous</i> call to <b>callback</b> (this is <i>null</i> for the first item).</li>

  <li><i>item</i> The current value from the array.</li>

  <li><i>i</i> The index of item in the list.</li>

  <li><i>source</i> The original array.</li>
</ul>

<p>For the first item in the list, we get promise which I’ll call <b>opPromise<sub>1</sub></b>. As <b>prev</b> is <i>null</i>, we’re joining <b>[WinJS.Promise.as(null), opPromise<sub>1</sub>]</b>. But notice that we’re not returning <b>join</b> itself. Instead, we’re attaching a completed handler (which I’ve called <b>completed</b>) to that join and returning the promise from its <b>then</b>.</p>

<p>Remember that the promise returned from <b>then</b> will be fulfilled when the completed handler returns. This means that what we’re returning from <b>callback</b> is a promise that’s not completed until the first item’s <b>completed</b> handler has processed the results from <b>opPromise<sub>1</sub></b>. And if you look back at the result of a join, it’s fulfilled with an object that contains the results from the promises in the original list. That means that the fulfillment value <i>v</i> will contain both a <i>prev</i> property and a <i>result</i> property, where the latter is the result of <b>opPromise<sub>1</sub></b>.</p>

<p>With the next item in <i>list</i>, <b>callback</b> receives a <i>prev</i> that contains the promise from the previous <b>join.then</b>. We’ll then create a new join of <b>opPromise<sub>1</sub>.then</b> and <b>opPromise<sub>2</sub></b>. As a result, this join not completes until both <b>opPromise<sub>2</sub></b> is fullfilled <i>and</i> the completed handler for <b>opPromise<sub>1</sub></b> returns. Voila! The <b>completed<sub>2</sub></b> handler we now attach to this <b>join</b> isn’t called until after <b>completed<sub>1</sub></b> has returned.</p>

<p>The same dependencies continue to be built up for each item in list—the promise from <b>join.then</b> for item <i>n </i>aren’t fulfilled until <b>completed<i><sub>n</sub></i></b> returns. This guarantees that the completed handlers are called in the same sequence as <i>list</i>.</p>

<h2>In closing</h2>

<p>In this post we’ve seen that promises in themselves are just a code construct or a calling convention—albeit a powerful one—to represent a specific relationship between an originator, who has values to deliver at an arbitrarily later time, and a consumer that wants to know when those values are available. As such, promises work very well to represent results from asynchronous operations, and are used extensively within Windows Store apps written in JavaScript. The specification for promises also allows sequential async operations to be chained together, with each intermediate result flowing from one link to the next.</p>

<p>The Windows Library for JavaScript, WinJS, provides a robust implementation of promises that you can use to wrap any kind of operation of your own. It also provides helpers for common scenarios such as joining together promises for parallel operations. With these, WinJS makes it possible to work with asynchronous operations very efficiently and effectively.</p>

<p>Kraig Brockschmidt 
  <br />Program Manager, Windows Ecosystem Team 

  <br />Author, <a href="http://blogs.msdn.com/b/microsoft_press/archive/2012/10/29/free-ebook-programming-windows-8-apps-with-html-css-and-javascript.aspx"><i>Programming Windows 8 Apps in HTML, CSS, and JavaScript</i></a></p>]]></content:encoded>
    </item>
    <item>
      <title>Join the Game On Virtual Event</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/join-the-game-on-virtual-event</link>
      <pubDate>Fri, 07 Jun 2013 09:35:00 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/06/07/join-the-game-on-virtual-event/</guid>
      <description><![CDATA[Games are a key class of apps in the Windows Store. If you’re looking to build a Windows Store game,...]]></description>
      <content:encoded><![CDATA[<p>Games are a key class of apps in the Windows Store. If you’re looking to build a Windows Store game, we’d like to help you with this virtual game building event. The event is free and open to both new game developers and professionals. </p>  <p>We’ll be using <a href="https://aka.ms/yoyogamesgamemaker" target="_blank">GameMaker: Studio</a> from YoYo Games, to show you how to create and publish high-quality games in less time. GameMaker:Studio has a lot of great built-in design options and drag-and-drop tools that make it easy to get started even if you don’t have a game idea or development experience just yet. However, if you’re a more experienced game developer, the advanced tools help you to create a one-of-a-kind game experience. </p>  <p><a href="https://aka.ms/gameonevent"><img title="clip_image002" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="clip_image002" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/8666.clip_image002_0385EAB3.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/8666.clip_5F00_image002_5F00_0385EAB3.jpg" width="500" height="154" /></a></p>  <p>The online event begins on Saturday, June 15<sup>th</sup>, 10 am PDT, with a launch session and live chat. You’ll learn about different game types and how to add graphics, levels and sound to base games, while exploring ways to make the game your own. Support continues throughout the week with one-on-one assistance through the GameMaker forums.</p>  <p>Whether you’re a student, first-time developer, or seasoned pro, this event can get you started creating, uploading, and publishing games to the Windows Store. Learn more, sign up, and check out the free tools and resources at <a href="http://msdnevents.com/gameon/" target="_blank">http://msdnevents.com/gameon/</a>. </p>  <p>--Robert Rodriguez-Lawson, Senior Content Publishing Manager, Windows Developer Content</p>]]></content:encoded>
    </item>
    <item>
      <title>Credential Locker: Your solution for handling usernames and passwords in your Windows Store app</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/credential-locker-your-solution-for-handling-usernames-and-passwords-in-your-windows-store-app</link>
      <pubDate>Thu, 30 May 2013 08:00:00 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/05/30/credential-locker-your-solution-for-handling-usernames-and-passwords-in-your-windows-store-app/</guid>
      <description><![CDATA[If you haven’t yet heard about the Credential Locker that's available for Windows Store apps, it’s...]]></description>
      <content:encoded><![CDATA[<p>If you haven’t yet heard about the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465069.aspx" target="_blank">Credential Locker</a> that's available for Windows Store apps, it’s time you did. Why? Because it not only simplifies the task of <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465060.aspx" target="_blank">storing</a> and <a href="http://msdn.microsoft.com/en-us/library/windows/apps/jj839731.aspx" target="_blank">retrieving user credentials</a>, it stores them securely, and credentials roam with users “for free” along with their Microsoft account.</p>  <p>Say you have an app that connects to a service to access protected resources such as media files, social networking, etc. Your service requires login information for each user. So, you’ve built UI into your app that gets the username and password for the user, which is then used to log the user into the service. Everything works like a champ.</p>  <p>Now you want to go that extra mile for your users and store their login information securely so they don’t have to log in every time they use your app. Enter Credential Locker. With a few simple calls to the Credential Locker API, you can store the username and password for your user and easily retrieve them and log the user in the next time they open your app.</p>  <h2>Secure storage</h2>  <p>The great advantage that Credential Locker brings to your app is that it stores the user credentials in a secure location, and the credential information is encrypted when it’s stored on disk. Sure, you could store your user credentials in a file in the local storage for your app, but storing user credentials in plain text presents a considerable security hole. If a user’s system is compromised in some way, the user’s username and password are easy to access and manipulate. If the username and password are stored using Credential Locker, the best that a malicious source could get a hold of is an encrypted file.</p>  <p>The Credential Locker is unique to each Windows PC user and access to a credential is limited to the app that stored it. That is, you can only retrieve a credential that you stored for your app. Likewise, no other apps can get to the credentials that your app has stored in the locker.</p>  <h2>Roaming credentials</h2>  <p>As an added benefit to your users, when you store their username and password using Credential Locker, the stored credentials roam with their Microsoft account to any other trusted machine they use with that Microsoft account. This makes your secure app even more convenient for your users because your app can log them in automatically—without re-prompting the user for credentials--from any trusted machine they have installed your app on and associated with their Microsoft account.</p>  <p>Things work a little differently for domain accounts. If there are credentials stored with your Microsoft account, and you associate that account with a domain account (such as the account that you use at work), your credentials will roam to that domain account. However, any new credentials added when signed on with the domain account won’t roam. This ensures that private credentials for the domain aren’t exposed outside of the domain.</p>  <h2>Storing user credentials</h2>  <p>Storing user credentials in the Credential Locker is a quick, two-step process. First, you obtain a reference to the Credential Locker using the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.passwordvault.aspx" target="_blank">PasswordVault</a> object from the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.aspx" target="_blank">Windows.Security.Credentials</a> namespace. Then, you create a <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.passwordcredential.aspx" target="_blank">PasswordCredential</a> object that contains an identifier for your app, the username and the password, and pass that to the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh701231.aspx" target="_blank">PasswordVault.Add()</a> method to add the credential to the locker.</p>  <p><strong>C#</strong></p>  <blockquote>   <div id="codeSnippetWrapper">     <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">var vault = <span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordVault();<br />vault.Add(<span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordCredential(<br />    <span style="color: rgb(0, 96, 128);">&quot;My App&quot;</span>, username, password));<br /></pre>
  </div>
</blockquote>

<p><strong>JavaScript</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> vault = <span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordVault();<br />vault.add(<span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordCredential(<br />    <span style="color: rgb(0, 96, 128);">&quot;My App&quot;</span>, username, password));<br /></pre>
  </div>
</blockquote>

<h2>Retrieving user credentials</h2>

<p>You have several options for retrieving user credentials from the Credential Locker after you have a reference to the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.passwordvault.aspx" target="_blank">PasswordVault</a> object.</p>

<ul>
  <li>You can retrieve all the credentials the user has supplied for your app in the locker with the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.passwordvault.retrieveall.aspx" target="_blank">PasswordVault.RetrieveAll()</a> method.</li>

  <li>If you know the username for the stored credentials, you can retrieve all the credentials for that username with the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.passwordvault.findallbyusername.aspx" target="_blank">PasswordVault.FindAllByUserName()</a> method.</li>

  <li>If you know the resource name for the stored credentials, you can retrieve all the credentials for that resource name with the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.passwordvault.findallbyresource.aspx" target="_blank">PasswordVault.FindAllByResource()</a> method.</li>

  <li>Finally, if you know both the username and the resource name for a credential, you can retrieve just that credential with the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.passwordvault.retrieve.aspx" target="_blank">PasswordVault.Retrieve()</a> method.</li>
</ul>

<p>Let’s look at an example where we have stored the resource name globally in an app and we log the user on automatically if we find a credential for them. In the case where we find multiple credentials for the user, we ask the user to select a default credential to use when logging on.</p>

<p><strong>C#</strong></p>

<blockquote>
  <div>
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">private</span> <span style="color: rgb(0, 0, 255);">string</span> resourceName = <span style="color: rgb(0, 96, 128);">&quot;My App&quot;</span>;<br /><span style="color: rgb(0, 0, 255);">private</span> <span style="color: rgb(0, 0, 255);">string</span> defaultUserName;<br /><br /><span style="color: rgb(0, 0, 255);">private</span> <span style="color: rgb(0, 0, 255);">void</span> Login()<br />{<br />    var loginCredential = GetCredentialFromLocker();<br /><br />    <span style="color: rgb(0, 0, 255);">if</span> (loginCredential != <span style="color: rgb(0, 0, 255);">null</span>)<br />    {<br />        <span style="color: rgb(0, 128, 0);">// There is a credential stored in the locker.</span><br />        <span style="color: rgb(0, 128, 0);">// Populate the Password property of the credential</span><br />        <span style="color: rgb(0, 128, 0);">// for automatic login.</span><br />        loginCredential.RetrievePassword();<br />    }<br />    <span style="color: rgb(0, 0, 255);">else</span><br />    {<br />        <span style="color: rgb(0, 128, 0);">// There is no credential stored in the locker.</span><br />        <span style="color: rgb(0, 128, 0);">// Display UI to get user credentials.</span><br />        loginCredential = GetLoginCredentialUI();<br />    }<br /><br />    <span style="color: rgb(0, 128, 0);">// Log the user in.</span><br />    ServerLogin(loginCredential.UserName, loginCredential.Password);<br />}<br /><br /><br /><span style="color: rgb(0, 0, 255);">private</span> Windows.Security.Credentials.PasswordCredential GetCredentialFromLocker()<br />{<br />    Windows.Security.Credentials.PasswordCredential credential = <span style="color: rgb(0, 0, 255);">null</span>;<br /><br />    var vault = <span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordVault();<br />    var credentialList = vault.FindAllByResource(resourceName);<br />    <span style="color: rgb(0, 0, 255);">if</span> (credentialList.Count &gt; 0)<br />    {<br />        <span style="color: rgb(0, 0, 255);">if</span> (credentialList.Count == 1)<br />        {<br />            credential = credentialList[0];<br />        }<br />        <span style="color: rgb(0, 0, 255);">else</span><br />        {<br />            <span style="color: rgb(0, 128, 0);">// When there are multiple usernames,</span><br />            <span style="color: rgb(0, 128, 0);">// retrieve the default username. If one doesn’t</span><br />            <span style="color: rgb(0, 128, 0);">// exist, then display UI to have the user select</span><br />            <span style="color: rgb(0, 128, 0);">// a default username.</span><br /><br />            defaultUserName = GetDefaultUserNameUI();<br /><br />            credential = vault.Retrieve(resourceName, defaultUserName);<br />        }<br />    }<br /><br />    <span style="color: rgb(0, 0, 255);">return</span> credential;<br />}<br /></pre>
  </div>
</blockquote>

<div>
  <br /><strong>JavaScript</strong></div>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> resourceName = <span style="color: rgb(0, 96, 128);">&quot;My App&quot;</span>;<br /><span style="color: rgb(0, 0, 255);">var</span> defaultUserName;<br /><br /><span style="color: rgb(0, 0, 255);">function</span> login() {<br />    <span style="color: rgb(0, 0, 255);">var</span> loginCredential = getCredentialFromLocker();<br /><br />    <span style="color: rgb(0, 0, 255);">if</span> (loginCredential != <span style="color: rgb(0, 0, 255);">null</span>) {<br />        <span style="color: rgb(0, 128, 0);">// There is a credential stored in the locker.</span><br />        <span style="color: rgb(0, 128, 0);">// Populate the Password property of the credential</span><br />        <span style="color: rgb(0, 128, 0);">// for automatic login.</span><br />        loginCredential.retrievePassword();<br />    } <span style="color: rgb(0, 0, 255);">else</span> {<br />        <span style="color: rgb(0, 128, 0);">// There is no credential stored in the locker.</span><br />        <span style="color: rgb(0, 128, 0);">// Display UI to get user credentials.</span><br />        loginCredential = getLoginCredentialUI();<br />    }<br /><br />    <span style="color: rgb(0, 128, 0);">// Log the user in.</span><br />    serverLogin(loginCredential.userName, loginCredential.password);<br />}<br /><br /><br /><span style="color: rgb(0, 0, 255);">function</span> GetCredentialFromLocker() {<br />    <span style="color: rgb(0, 0, 255);">var</span> credential = <span style="color: rgb(0, 0, 255);">null</span>;<br /><br />    <span style="color: rgb(0, 0, 255);">var</span> vault = <span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordVault();<br />    <span style="color: rgb(0, 0, 255);">var</span> credentialList = vault.findAllByResource(resourceName);<br />    <span style="color: rgb(0, 0, 255);">if</span> (credentialList.length &gt; 0) {<br />        <span style="color: rgb(0, 0, 255);">if</span> (credentialList.length == 1) {<br />            credential = credentialList[0];<br />        } <span style="color: rgb(0, 0, 255);">else</span> {<br />            <span style="color: rgb(0, 128, 0);">// When there are multiple usernames,</span><br />            <span style="color: rgb(0, 128, 0);">// retrieve the default username. If one doesn’t</span><br />            <span style="color: rgb(0, 128, 0);">// exist, display UI to have the user select</span><br />            <span style="color: rgb(0, 128, 0);">// a default username.</span><br /><br />            defaultUserName = getDefaultUserNameUI();<br />            credential = vault.retrieve(resourceName, defaultUserName);<br />        }<br />    }<br /><br />    <span style="color: rgb(0, 0, 255);">return</span> credential;<br />}<br /></pre>
  </div>
</blockquote>

<h2>Deleting user credentials</h2>

<p>Deleting user credentials in the Credential Locker is also a quick, two-step process. Again, you obtain a reference to the Credential Locker using the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.passwordvault.aspx" target="_blank">PasswordVault</a> object from the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.aspx" target="_blank">Windows.Security.Credentials</a> namespace. Then, you pass the credential you want to delete to the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh701242.aspx" target="_blank">PasswordVault.Remove()</a> method.</p>

<p><strong>C#</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">var vault = <span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordVault();<br />vault.Remove(<span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordCredential(<br />    <span style="color: rgb(0, 96, 128);">&quot;My App&quot;</span>, username, password));<br /></pre>
  </div>
</blockquote>

<p><strong>JavaScript</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> vault = <span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordVault();<br />vault.remove(<span style="color: rgb(0, 0, 255);">new</span> Windows.Security.Credentials.PasswordCredential(<br />    <span style="color: rgb(0, 96, 128);">&quot;My App&quot;</span>, username, password));<br /></pre>
  </div>
</blockquote>

<h2>Easy and secure</h2>

<p>As you can see, the Credential Locker is an easy-to-use feature that simplifies your task of authenticating users and storing those user credentials for future use—all in a highly secure fashion.</p>

<p>Other Windows 8 app authentication topics include the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465281.aspx" target="_blank">Web Authentication Broker</a>, which you can use to retrieve an authentication token from a website (for example, OAuth), and <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh770853.aspx" target="_blank">personalizing your app based on a user’s Microsoft account</a>.</p>

<p>For more info, see</p>

<ul>
  <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211367.aspx" target="_blank">Managing user info (JavaScript)</a></li>

  <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/BR229572(v=win.10).aspx" target="_blank">Managing user info (Windows Store apps using C#/VB/C++ and XAML)</a></li>

  <li><a href="http://code.msdn.microsoft.com/windowsapps/PasswordVault-f01be74a" target="_blank">Credential Locker sample</a></li>

  <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.credentials.aspx" target="_blank">Windows.Security.Credentials</a></li>
</ul>

<p><i></i></p>

<p>--Doug Rothaus, Senior Content Developer, Windows Developer Content</p>

<p>Special thanks to Yashar Bahman for his help and contributions to this post.</p>]]></content:encoded>
    </item>
    <item>
      <title>Create location aware apps using geolocation and Bing Maps</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/create-location-aware-apps-using-geolocation-and-bing-maps</link>
      <pubDate>Wed, 22 May 2013 08:00:00 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/05/22/create-location-aware-apps-using-geolocation-and-bing-maps/</guid>
      <description><![CDATA[By tying together a user’s location to the business logic of your app, you can easily provide app...]]></description>
      <content:encoded><![CDATA[<p>By tying together a user’s location to the business logic of your app, you can easily provide app users with weather, coupons, sporting events, or concert listings for their current location. You can use the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br229921.aspx" target="_blank">geolocation</a> capabilities of Windows 8, along with the Bing Maps SDK, to create great <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465148.aspx" target="_blank">location aware Windows Store apps</a>.</p>  <p>Let’s take a look at how your app can use the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br225603.aspx" target="_blank">location service</a> to provide users location-specific info with either an IP address, WiFi network, or GPS data. Once you have the location, you can use the Bing Maps SDK to show the user where they are. </p>  <h2>Retrieving Location</h2>  <p>The <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.aspx">Windows.Devices.Geolocation</a> namespace is used for retrieving your location. Whether you use GPS, a WiFi network, or an IP address to retrieve a user’s location depends on two primary factors:</p>  <ol>   <li>The accuracy level requested. This is the ideal level of accuracy to meet your app’s needs. </li>    <li>The availability of location data.&#160; Meaning, not all devices have GPS built in.&#160;&#160; Or a network or Wi-Fi connection may not be available when the location is requested.</li> </ol>  <h3><a>Desired accuracy</a></h3>  <p>When requesting a location, your app should specify your <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator.desiredaccuracy.aspx" target="_blank">desired accuracy</a> so the location data can be returned as quickly as possible within the given range.&#160; Each of the location types have degrees of accuracy:</p>  <ul>   <li><a href="http://en.wikipedia.org/wiki/Gps" target="_blank">GPS</a> – GPS provides the most accuracy, down to approximately 10 meters.&#160; However, if the GPS sensor needs to ‘wake up’ and acquire satellite data and then triangulate the data, it can take a minute or two to return the location details. But, once the GPS has acquired satellite connections, it can then acquire the next location point more quickly.&#160; Of course, the more the GPS is used, the more power it consumes. The <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator.desiredaccuracy.aspx" target="_blank">Geolocator.DesiredAccuracy</a> property must be set to High to enable to GPS to acquire data.</li>    <li><a href="http://en.wikipedia.org/wiki/Wi-Fi" target="_blank">Wi-Fi</a> – A Wi-Fi connection can provide accuracy between 50-500 meters.&#160; If the connection exists, the location data can be returned faster than a GPS can acquire satellite connections. Set the DesiredAccuracy property to Default in order to acquire the location with Wi-Fi.</li>    <li><a href="http://en.wikipedia.org/wiki/IP_address" target="_blank">IP</a> – IP level resolution can bring accuracy down to about the 1 kilometer level.&#160; If the network connection exists, the location data can be returned faster than a GPS can acquire a satellite connection. You also set the DesiredAccuracy property to Default to acquire the location with IP. The location service returns the highest accuracy it can and lets you know how accurate it is in the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geocoordinate.accuracy.aspx" target="_blank">Geocoordinate.Accuracy</a> property.</li> </ul>  <p>Consider your desired accuracy value carefully. It can affect your app’s performance and power consumption.&#160; For example, if your app is providing a weather forecast, you rarely need the high accuracy of GPS.&#160; Also be sure to indicate the accuracy of your data by displaying an error radius based on the accuracy of the data returned. Here is the C# code to set your desired accuracy:</p>  <p><strong>C#</strong></p>  <blockquote>   <div id="codeSnippetWrapper">     <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">Geolocator geolocator = <span style="color: rgb(0, 0, 255);">new</span> Geolocator();<br />geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;<br /></pre>
  </div>
</blockquote>

<br />No matter what accuracy you want, the call to get your location is: 

<p><strong>C#</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token);</pre>
  </div>
</blockquote>

<p>Here’s the JavaScript code that creates an instance of the Geolocator class, sets the desired accuracy, and then gets the current location. Note that the ‘promise’ variable below is a <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx" target="_blank">WinJS.Promise</a> object – you’ll need to use the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh701079.aspx" target="_blank">done</a> method to access the data from the call to <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br225537.aspx" target="_blank">getGeopositionAsync</a>.</p>

<p><strong>JavaScript</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> geolocator = Windows.Devices.Geolocation.Geolocator();<br />geolocator.desiredAccuracy =<br />Windows.Devices.Geolocation.PositionAccuracy.high;<br /><br /><span style="color: rgb(0, 128, 0);">// Get the geoposition, capturing the request in a 'promise' object.</span><br /><span style="color: rgb(0, 0, 255);">var</span> promise = geolocator.getGeopositionAsync();<br /></pre>
  </div>
</blockquote>

<br />Remember that if you set your desired accuracy to High, you can’t be assured that the user’s device will be able to return high accuracy. Their PC may not have a GPS or it may be turned off or they may not be connected to Wi-Fi, etc. Always be prepared to gracefully handle these instances of lower accuracy data. How you do this depends on the functionality of your app. Can you continue with lower accuracy? Can you require GPS level accuracy? See the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465148.aspx" target="_blank">Guidelines for location-aware apps</a> for more info. 

<h3>Bing Maps</h3>

<p>The <a href="http://apps.microsoft.com/webpdp/app/97a2179c-38be-45a3-933e-0d2dbf14a142" target="_blank">Bing Maps app</a> is a good example of an app that adapts to the accuracy of the location data available to it.&#160; On a desktop PC, which typically doesn’t have GPS or Wi-Fi, it finds the location based on the IP address and <a>zooms in to a region level when mapping </a>the current location.&#160; On a laptop, which typically has a wireless card, it uses the Wi-Fi to get a more precise location and zoom in further when showing current location.&#160; If the user zooms in even further, the current location icon will show an error radius.&#160; On a device with GPS, Bing Maps gets the high accuracy location data from the GPS and displays a more accurate location.</p>

<h3>Bing Weather</h3>

<p>As mentioned above, an app like the <a href="http://apps.microsoft.com/webpdp/app/421ba874-f903-4965-9b82-d60f3ba3cae0" target="_blank">Bing Weather app</a> only needs region information.&#160; Because of this, it can specify that it only needs low accuracy allowing it to quickly get a location value back.&#160; This makes the app more responsive to the user.&#160; Other examples of apps that may need only region level information include radio station guides, shopping deals, or local news feeds.</p>

<h2>Displaying location data with the Bing Maps SDK</h2>

<p>After you have the location information from your call to <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator.getgeopositionasync.aspx" target="_blank">GetGeopositionAsync</a>, you’ll want to display it on a map.</p>

<ul>
  <li>First, convert the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geoposition.aspx" target="_blank">Geoposition</a> into a <a href="http://msdn.microsoft.com/en-us/library/hh846500.aspx" target="_blank">Location</a> that can be used with Bing Maps, use the following code:</li>
</ul>

<p>&#160;</p>

<p><strong>C#</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">Location location = <span style="color: rgb(0, 0, 255);">new</span> Location(pos.Coordinate.Latitude, pos.Coordinate.Longitude);</pre>
  </div>
</blockquote>

<p><strong>JavaScript:</strong></p>

<blockquote>
  <div>
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">promise.done(<br />  <span style="color: rgb(0, 0, 255);">function</span> (pos) {<br />    <span style="color: rgb(0, 128, 0);">// Get the coordinates of the current location.</span><br />    <span style="color: rgb(0, 0, 255);">var</span> coord = pos.coordinate,<br />    location = <span style="color: rgb(0, 0, 255);">new</span> Microsoft.Maps.Location(coord.latitude, coord.longitude);<br /> <br />  },<br />  <span style="color: rgb(0, 0, 255);">function</span> (err) {<br />    <span style="color: rgb(0, 128, 0);">// Handle the error.</span><br />  });<br /></pre>
  </div>
</blockquote>

<p>&#160;</p>

<ul>
  <li>Next, display your location using Bing Maps. You can get the Bing Maps SDK <a href="http://visualstudiogallery.msdn.microsoft.com/bb764f67-6b2c-4e14-b2d3-17477ae1eaca">here</a>. You’ll also need to get a Bing Maps Key by registering on the Bing Maps Portal and following the instructions for <a href="http://msdn.microsoft.com/en-us/library/ff428642.aspx">Getting a Bing Maps Key</a>. When you register make sure you look at the usage restrictions for each type of key and choose one that is appropriate for your app. 

    <br />Add a Bing Maps control to your designer and insert your key into the credentials.</li>
</ul>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">&lt;</span><span style="color: rgb(128, 0, 0);">Page</span><br />    <span style="color: rgb(255, 0, 0);">xmlns</span><span style="color: rgb(0, 0, 255);">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span><br />    <span style="color: rgb(255, 0, 0);">xmlns:x</span><span style="color: rgb(0, 0, 255);">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span><br />    <span style="color: rgb(255, 0, 0);">xmlns:local</span><span style="color: rgb(0, 0, 255);">=&quot;using:SimpleMapping&quot;</span><br />    <span style="color: rgb(255, 0, 0);">xmlns:d</span><span style="color: rgb(0, 0, 255);">=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;</span><br />    <span style="color: rgb(255, 0, 0);">xmlns:mc</span><span style="color: rgb(0, 0, 255);">=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;</span><br />    <span style="color: rgb(255, 0, 0);">xmlns:Maps</span><span style="color: rgb(0, 0, 255);">=&quot;using:Bing.Maps&quot;</span><br />    <span style="color: rgb(255, 0, 0);">x:Class</span><span style="color: rgb(0, 0, 255);">=&quot;SimpleMapping.MainPage&quot;</span><br />    <span style="color: rgb(255, 0, 0);">mc:Ignorable</span><span style="color: rgb(0, 0, 255);">=&quot;d&quot;</span><span style="color: rgb(0, 0, 255);">&gt;</span><br /><br />    <span style="color: rgb(0, 0, 255);">&lt;</span><span style="color: rgb(128, 0, 0);">Grid</span> <span style="color: rgb(255, 0, 0);">Background</span><span style="color: rgb(0, 0, 255);">=&quot;{StaticResource ApplicationPageBackgroundThemeBrush}&quot;</span><span style="color: rgb(0, 0, 255);">&gt;</span><br />        <span style="color: rgb(0, 0, 255);">&lt;</span><span style="color: rgb(128, 0, 0);">Maps:Map</span> <span style="color: rgb(255, 0, 0);">x:Name</span><span style="color: rgb(0, 0, 255);">=&quot;Map&quot;</span> <span style="color: rgb(255, 0, 0);">Margin</span><span style="color: rgb(0, 0, 255);">=&quot;0,120,0,0&quot;</span> <span style="color: rgb(255, 0, 0);">Credentials</span><span style="color: rgb(0, 0, 255);">=&quot;Insert Your Bing Maps Key Here&quot;</span><span style="color: rgb(0, 0, 255);">/&gt;</span><br />    <span style="color: rgb(0, 0, 255);">&lt;/</span><span style="color: rgb(128, 0, 0);">Grid</span><span style="color: rgb(0, 0, 255);">&gt;</span><br /><span style="color: rgb(0, 0, 255);">&lt;/</span><span style="color: rgb(128, 0, 0);">Page</span><span style="color: rgb(0, 0, 255);">&gt;</span></pre>
  </div>
</blockquote>

<ul>
  <li>Now you can use the following code to the page in your app where the map is displayed. This sets the zoom level of the map and shows the location. Learn more about zoom level in <a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj850315.aspx" target="_blank">How to display your location on a Bing Map</a>:</li>
</ul>

<p><strong>C#</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">double</span> zoomLevel = 13.0f;<br /><br />Map.SetView(location, zoomLevel);<br /></pre>
  </div>
</blockquote>

<br />Adding a Bing Maps control to your app in JavaScript and HTML requires a little more work. Add the following &lt;script&gt; tag to the HTML of your app: 

<div>&#160;</div>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">&lt;</span><span style="color: rgb(128, 0, 0);">script</span> <span style="color: rgb(255, 0, 0);">type</span><span style="color: rgb(0, 0, 255);">=&quot;text/javascript&quot;</span> <br />   <span style="color: rgb(255, 0, 0);">src</span><span style="color: rgb(0, 0, 255);">=&quot;ms-appx:///Bing.Maps.JavaScript//js/veapicore.js&quot;</span><span style="color: rgb(0, 0, 255);">&gt;</span><br />/script<span style="color: rgb(0, 0, 255);">&gt;</span><br /></pre>
  </div>
</blockquote>

<p>Then, you’ll need to create a &lt;div&gt; tag to contain the map, setting the id attribute so that you can access it.</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">&lt;</span><span style="color: rgb(128, 0, 0);">div</span> <span style="color: rgb(255, 0, 0);">id</span>=’<span style="color: rgb(255, 0, 0);">map-div</span>’<span style="color: rgb(0, 0, 255);">&gt;&lt;/</span><span style="color: rgb(128, 0, 0);">div</span><span style="color: rgb(0, 0, 255);">&gt;</span></pre>
  </div>
</blockquote>

<p>Last, you’ll need to initialize the map control in the HTML page. Here’s some JavaScript code that does so:</p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 128, 0);">// Load the Microsoft.Maps.Map module and then call getMap when the </span><br /><span style="color: rgb(0, 128, 0);">// module has loaded.</span><br /><span style="color: rgb(0, 0, 255);">function</span> initMap() {<br />  Microsoft.Maps.loadModule(<span style="color: rgb(0, 96, 128);">'Microsoft.Maps.Map'</span>, <br />    { <br />      callback: getMap, <br />      culture: <span style="color: rgb(0, 96, 128);">&quot;en&quot;</span>, <br />      homeRegion: <span style="color: rgb(0, 96, 128);">&quot;US&quot;</span> <br />  });<br />}<br /><br /><span style="color: rgb(0, 128, 0);">// Get the div to contain the map from the interface of the app.</span><br /><span style="color: rgb(0, 0, 255);">function</span> getMap() {<br /><br />  <span style="color: rgb(0, 128, 0);">// Create a new instance of the Map class, passing in the app ID.</span><br />  <span style="color: rgb(0, 0, 255);">var</span> map = <span style="color: rgb(0, 0, 255);">new</span> Microsoft.Maps.Map(<br />    document.getElementById(mapDivId), <br />    { credentials: “Insert your credentials here” });<br /><br />  <span style="color: rgb(0, 128, 0);">// Set the initial zoom level and type of map.</span><br />  map.setView({<br />    mapTypeId: Microsoft.Maps.MapTypeId.road,<br />    zoom: 3<br />  });<br />}<br /></pre>
  </div>
</blockquote>

<ul>
  <li>Finally, any app that uses location must respect the user’s permissions settings, which can change at any time.&#160; The Weather app uses location to get the weather for the current location.&#160; But at any time, the user may go into the Settings and turn the Locations permissions off.&#160; Your app always has to handle the possibility that the Location permission has been disabled.&#160; In this case, the Weather app displays a “Your location cannot be found. Change your Permissions to allow Weather to user your location.” message. See the User experience guidelines in <a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh465148(v=win.10).aspx" target="_blank">Guidelines for location-aware apps</a> for examples of handling location permissions. 

    <br /><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/0882.bing-weather_2FEEBCEF.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/0882.bing_2D00_weather_5F00_2FEEBCEF.jpg"><img title="Bing Weather app" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Bing Weather app using location to get weather for the current location" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/7356.bing-weather_thumb_084840C5.jpg" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/7356.bing_2D00_weather_5F00_thumb_5F00_084840C5.jpg" width="600" height="450" /></a></li>
</ul>

<p>&#160;</p>

<p>For full details on using geolocation and the Bing Maps SDK, <a></a><a>we have a new </a><a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj850315.aspx" target="_blank">video, how-to topic</a> , and <a href="http://code.msdn.microsoft.com/windowsapps/Simple-geolocation-with-7b385c3c" target="_blank">code sample</a> that leads you through the steps of asynchronously acquiring your location and then using the Bing Maps SDK to show where you are in a visual manner. The video, how-to topic, and sample guide you through enabling the location capability, getting the location asynchronously, setting the map to a given location, and setting the location icon based on the accuracy of the location data. You can also find more info in <a href="http://msdn.microsoft.com/en-us/library/hh846481.aspx" target="_blank">Bing Maps for Windows Store Apps</a>.</p>

<h2>Wrapping up</h2>

<p>Location can be a powerful and time saving feature to add to your app. You can provide the user with more pertinent information based on where they are. Whether it’s a list of local radio stations, shopping deals, traffic information, or weather information, the control to tailor that information based on location can make your app more useful. And the ability to make that happen automatically, without user interaction, saves the user time and makes them more likely to use your app.</p>

<p>--Ross Heise, Senior Content Developer, Windows Developer Content</p>

<p>&#160;&#160; Special thanks to Jon Kay and Eric Schmidt for their help and contributions to this post.</p>]]></content:encoded>
    </item>
    <item>
      <title>Introducing a new Windows Dev Center experience</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/introducing-a-new-windows-dev-center-experience</link>
      <pubDate>Wed, 15 May 2013 13:15:00 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/05/15/introducing-a-new-windows-dev-center-experience/</guid>
      <description><![CDATA[Since launching the Windows Dev Center in October, 2011, we’ve worked closely with developers and...]]></description>
      <content:encoded><![CDATA[<p>Since launching the <a href="http://msdn.microsoft.com/en-us/windows/default.aspx" target="_blank">Windows Dev Center</a> in October, 2011, we’ve worked closely with developers and designers around the world to understand how we can provide the best guidance, inspiration, and samples for app builders. With millions of visitors and your feedback, we’ve been evaluating what’s been working well and what experiences can be improved.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/0172.windows_dev_center_1EC86298.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/0172.windows_5F00_dev_5F00_center_5F00_1EC86298.png"><img title="Windows Developer Center" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Windows Developer Center" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/0184.windows_dev_center_thumb_1DEFFCAE.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/0184.windows_5F00_dev_5F00_center_5F00_thumb_5F00_1DEFFCAE.png" width="600" height="338" /></a></p>  <h2>What’s new</h2>  <p>The Windows team is focused on growing a vibrant and thriving app ecosystem. This is manifested in three ways: great apps, great economics, and great reach opportunity. The new Dev Center connects app builders, designers and businesses with the resources they need to succeed in developing great apps and building a business with Windows.</p>  <p>To support those goals, the Dev Center evolved in these areas:</p>  <ol>   <li>The navigation model has changed so you can find the content relevant to where you are in the app development lifecycle</li>    <li>The site design highlights top tasks, scenarios, and new content </li> </ol>  <p>In addition to the content, samples, and downloads that developers want; we’ve made it easier to access resources for designers and businesses. </p>  <p>Depending on what you’re building, you can navigate to one of four areas: <a href="http://msdn.microsoft.com/en-US/windows/apps/br229512" target="_blank">Windows Store apps</a>, <a href="http://msdn.microsoft.com/en-US/ie/" target="_blank">Internet Explorer</a>, <a href="http://msdn.microsoft.com/en-US/windows/desktop" target="_blank">Windows desktop</a>, and <a href="http://msdn.microsoft.com/en-US/windows/hardware" target="_blank">Hardware</a>. Each of these presents a new experience that addresses the points mentioned above. In this post, we’ll take a closer look at the specific changes made for Windows Store apps.</p>  <h2>The right content for your role</h2>  <p>The most informative website isn’t useful if you can’t find what you’re looking for. With hundreds of thousands of topics in the Dev Center, organization and discoverability of content is critical. For Windows Store app development, that means a tighter focus based on role and scenario – from putting everything you need to get started in one place, to better support for designers and businesses. Here are some of the highlights.</p>  <h3>Developers</h3>  <p>We’ve streamlined the content you need to build great Windows Store apps. When you go to the <a href="http://msdn.microsoft.com/en-US/windows/apps/" target="_blank">Windows Store apps home page</a>, you’ll see: </p>  <ul>   <li>“Key tasks and content” prominently called out to help you jump into the content you need. Local events in your region are highlighted, as well as new resources just added to the site. </li>    <li>Downloads to help you dive right into coding, all the resources you need to get started, and our detailed guidance on getting your app into the Windows Store. </li>    <li>Important code samples are highlighted, and how-to guidance is more easily navigated with an eye toward the development lifecycle. </li>    <li>“<a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211360.aspx" target="_blank">One Dev Minute</a>” videos throughout the site, which give you a quick look at how to add features to your app. </li> </ul>  <h3>Designers</h3>  <p>We’ve overhauled the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh779072.aspx" target="_blank">Design section</a> of the site to make it both easier to use and more comprehensive. You can find useful downloads and reusable design assets more easily, and design inspiration and case studies give you the tools you need to make a unique experience on Windows. Everything you need to build a beautiful app that stands out from the crowd is right at your fingertips, with a page design that’s touch-friendly and easy-to-use.</p>  <h3>Businesses</h3>  <p>The business opportunity of the Windows Store is significant, with a better economic model than competitive platforms and flexibility that enables you to build the business you want. The new <a href="http://go.microsoft.com/fwlink/?LinkID=285998" target="_blank">Market section</a> of the site provides great tips for marketing your apps, evaluating telemetry data, and passing app certification. We’ve learned a lot about how to make certification easier and have improved the content to help you breeze through the process.</p>  <p>Of course, many of you fill multiple roles, and we think the new site organization supports that as well. From hobbyists to creative agencies to the largest enterprise software developers, the new site organization will help you achieve your creative and business vision with Windows.</p>  <h2>There’s more to come, and we want your input</h2>  <p>With <a href="http://www.buildwindows.com">BUILD 2013</a> a little more than a month away, there’s plenty to talk about. We’re working hard to produce new content to expand on what will be shared at this year’s event. In addition to keeping up with this blog, other ways to stay connected include following <a href="https://twitter.com/#!/windevs" target="_blank">@windevs</a> on Twitter and subscribing to the <a href="http://www.windowsstore.com/newsletter-signup" target="_blank">Windows Store newsletter</a>.</p>  <p>As we roll out more content to help you design, develop, and market your Windows Store apps, we want to keep improving your Dev Center experience! To make it easier for you to tell us what you think, we’ve provided two new feedback options at the bottom of every page. Please provide feedback– we’re listening and are always working to address your concerns.</p>  <p>&#160;</p>  <p>Keith Boyd, Content Publishing Manager, Windows Developer Content</p>]]></content:encoded>
    </item>
    <item>
      <title>Sharing to your target app</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/sharing-to-your-target-app</link>
      <pubDate>Wed, 08 May 2013 08:00:00 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/05/08/sharing-to-your-target-app/</guid>
      <description><![CDATA[In Sharing from your app, we introduced the idea of sharing content from the example app Food with...]]></description>
      <content:encoded><![CDATA[<p>In <a href="http://blogs.msdn.com/b/windowsappdev/archive/2012/12/12/sharing-from-your-app.aspx" target="_blank">Sharing from your app</a>, we introduced the idea of sharing content from the example app <a href="http://blogs.msdn.com/b/windowsappdev/archive/2012/07/11/creating-metro-style-apps-that-stand-out-from-the-crowd.aspx" target="_blank">Food with Friends</a> to several target apps that let the user accomplish rich end-to-end scenarios. Apps in Windows 8 offer interesting content that your customers will want to <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465251.aspx" target="_blank">share</a> with friends or other apps. With a compelling and well-designed share target, your app can be at the heart of a social and connected experience for your customers.</p>  <p>In this post we look at how you can use the Share target contract for your apps, especially those like Food with Friends. Using this contract, your app can <i>receive content</i> from other apps and use that content to improve its quality. We want to help you make your app the best in its category!</p>  <p>A target app is built using the Share target <a href="http://blogs.msdn.com/b/windowsappdev/archive/2012/03/23/activating-windows-8-contracts-in-your-app.aspx" target="_blank">contract</a><u></u> and is designed for a quick and easy sharing experience. Not every app in Windows will be a share target, but if your app can publish, transform, store or somehow add value to content it receives from another app, there are benefits to creating a Share target. </p>  <ul>   <li>Your app will always show up in the target app list. It’s instantly relevant and connected to other apps that can share data you want. </li>    <li>The share contract creates a bridge between your app and any source app without either app requiring one-to-one integration. </li>    <li>Because the Share charm is always present and available in the OS, it gives your target app a presence in the OS that extends beyond the boundaries of your app. This can potentially point more customers to your app!</li> </ul>  <h2>Receiving shared content</h2>  <p>Let’s take a look at few examples that show how you can deliver compelling experiences through a Share target app.</p>  <p>You might already be familiar with the Mail and People apps on Windows 8. Mail creates an easy and personal share target experience for receiving and sharing content with one or more friends. The People app lets you share content with broader audiences on your social networks. In addition to social sharing, you can go a step further with in app-to-app sharing. Productivity apps like SkyDrive can receive files from anywhere in Windows and store these on the cloud; note-taking apps can receive text, links and possibly data in a wide variety of other formats and archive it for reference later. There’s also plenty of room to get creative. </p>  <p>Look at how the two pictures below show the share flow when sharing a photo from the Photos app to PuzzleTouch, a game app that turns the picture into a visual puzzle. </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/8637.puzzletouch1_6E4332DA.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/8637.puzzletouch1_5F00_6E4332DA.png"><img title="Source app on the left; list of filtered target apps that can receive photos in the Share pane on the right. " style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Source app on the left; list of filtered target apps that can receive photos in the Share pane on the right. " src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/1307.puzzletouch1_thumb_2681A9F3.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/1307.puzzletouch1_5F00_thumb_5F00_2681A9F3.png" width="700" height="394" /></a></p>  <p align="center"><i>Figure 1: Source app on the left; list of filtered target apps that can receive photos in the Share pane on the right.      <br />PuzzleTouch is one of the Share targets that can receive a picture from the Photos app. </i></p>  <p align="left"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/6661.puzzletouch2_463083BB.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/6661.puzzletouch2_5F00_463083BB.png"><img title="On the right, the target app preview lets the user select what type of puzzle they " style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="On the right, the target app preview lets the user select what type of puzzle they " src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/2474.puzzletouch2_thumb_65DF5D83.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/2474.puzzletouch2_5F00_thumb_5F00_65DF5D83.png" width="700" height="394" /></a></p>  <p align="center"><i>Figure 2: On the right, the target app preview lets the user select what type of puzzle they      <br />want to build. The puzzle is ready when the user switches back to the app. </i></p>  <h2>What is a share target app?</h2>  <p>An end-to-end sharing experience in Windows has two components. You have a source app that makes its content available in different formats to Windows. You also have a share target app that registers to recognize certain formats and act as the destination for the content being shared. Using the Share contract, the source app and the share target app communicate with each other.</p>  <p>When you think about the share experience for your app, consider that the share target app is rendered in the hosted Share window. Make sure you design the experience so your user can quickly preview their content and confirm sharing in this view. This example shows the Mail share target app view that allows a user to quickly share a link from the browser with one of his or her mail contacts. </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/8561.Share-Target-Image_3ED44139.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/8561.Share_2D00_Target_2D00_Image_5F00_3ED44139.png"><img title="Share Target Image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Share Target Image" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/6011.Share-Target-Image_thumb_4FD86F1C.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/6011.Share_2D00_Target_2D00_Image_5F00_thumb_5F00_4FD86F1C.png" width="700" height="435" /></a></p>  <p align="center"><i>Figure 3: Sharing a link from the Photos app using the Mail target app</i></p>  <h2>Scenarios for Food with Friends</h2>  <p>Now, let’s consider how <a href="http://blogs.msdn.com/b/windowsappdev/archive/2012/07/11/creating-metro-style-apps-that-stand-out-from-the-crowd.aspx" target="_blank">Food with Friends</a> creates a compelling Share target app experience. If you’re familiar with the app, you’ll see two main actions that a user can take in Food with Friends – <i>creating a plan</i> and <i>adding a restaurant to their Wishlist</i>. Of course, there are other actions such as writing a review, posting a comment, viewing your friends’ wish lists, and so on, but those experiences make sense within the context of the main app. For the two core scenarios that stand out, let’s do a quick sanity-check to see if these can be effectively completed via the Food with Friends target app.</p>  <h3>Create Tonight’s plan</h3>  <p>While a core scenario of the main app, this isn’t the best scenario for a Share target experience. Here’s why: The Share target experience is meant to be quick and easy. Creating a plan is a much more involved task – a user would want to know what other restaurants her friends want to try out, compare a few restaurants from their Wishlist, review ratings and so on. Because planning involves leveraging details that are best presented in the main app view, condensing that functionality into the Share target app is not compelling. </p>  <p><b></b></p>  <h3>Add to Wishlist</h3>  <p>This scenario works really well as a short and directed task in the Share target. Some highlights in this app experience:<b></b></p>  <ul>   <li>People come across restaurants in other apps, whether these are trip planning apps, local city apps with recommendations, food blogs, and so on. Food with Friends is a great destination for aggregating restaurants in the ‘My Wishlist’ section. </li>    <li>The target app view of an app is designed for a user to quickly take action while in the context of a different app. Thus, adding a restaurant to a Wishlist is an excellent option to surface in the Share target. </li>    <li>While it’s certainly possible for the user to switch apps, repeat the search to find the restaurant, and then add the restaurant to their Wishlist, it’s a much easier experience to quick tap on Share.</li> </ul>  <p>The Food with Friends Wishlist seems to be a great share target app experience that we want to design and build. Here’s the end-to-end scenario we have in mind:</p>  <p>While browsing an app that shows me local food trucks, I find a food truck recommendation that sounds interesting. I want to add the food truck from this app to My Wishlist in Food with Friends to help with planning later.</p>  <p align="center"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/7658.contoso_truck_6C263411.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/7658.contoso_5F00_truck_5F00_6C263411.png"><img title="Browsing an app that shows local food trucks and recommends places of interest" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Browsing an app that shows local food trucks and recommends places of interest" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/3022.contoso_truck_thumb_4B9EF45F.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/3022.contoso_5F00_truck_5F00_thumb_5F00_4B9EF45F.png" width="700" height="394" /></a><em>Figure 4: Browsing an app that shows local food trucks and recommends places of interest</em></p>  <p>This image shows the share target app view that we want to use:</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/3835.contoso_truck2_565C4BB4.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/3835.contoso_5F00_truck2_5F00_565C4BB4.png"><img title="The share target app view" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="The share target app view" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/8637.contoso_truck2_thumb_760B257C.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/8637.contoso_5F00_truck2_5F00_thumb_5F00_760B257C.png" width="700" height="394" /></a></p>  <p align="center"><em>Figure 5: The share target app view</em></p>  <p>By completing the share action in the target app view, users can curate restaurants in Food with Friends, without switching context from their current immersive app experience. </p>  <h2>Implementing a share target</h2>  <p>Now that you’ve seen some examples of when to implement a share target, let’s look at how you implement a share target. First, decide which data formats your app can receive. </p>  <h3>Which data formats should you support?</h3>  <p>With Share you can support either standard data formats such as text, URI, HTML, bitmaps, files or custom data formats such as the ones listed on <a href="http://schema.org" target="_blank">http://schema.org</a> . Windows filters target apps by the data formats they support to display the filtered target app list in the Share pane. Your app should support data formats that are important to the app experience. For example, if your app is about viewing photos, supporting text formats might not be helpful. If you declare support for multiple data formats, decide which one helps you represent the shared data best so you can pick that format from the data package first. </p>  <p>Since Food with Friends is implementing a share target experience that lets users share restaurants to the app, we’ll use the <a href="http://schema.org/Restaurant" target="_blank">Restaurant</a><u></u> data format listed on <a href="http://schema.org" target="_blank">http://schema.org</a>. Food with Friends can register with the Share target contract to receive this data format. Then, using the data in the received package, it can build a compelling experience in its target app view that allows the user to add that restaurant to their Wishlist. </p>  <p>While some source apps may specifically share out the <a href="http://schema.org/Restaurant" target="_blank">Restaurant</a><u></u> data format, other source apps may represent similar information using other data formats like <a href="http://schema.org/Place" target="_blank">Place</a><u></u>, <a href="http://schema.org/LocalBusiness" target="_blank">LocalBusiness</a><u></u> and <a href="http://schema.org/FoodEstablishment" target="_blank">FoodEstablishment</a> listed on <a href="http://schema.org/" target="_blank">schema.org</a><u></u>. Thus, Food with Friends can support receiving multiple formats in the share contract to cater to a wider variety of source apps.</p>  <p>Food with Friends supports the following formats in the Share target declarations of the app manifest:</p>  <ul>   <li><u><a href="http://schema.org/Restaurant" target="_blank">Restaurant</a></u></li>    <li><u><a href="http://schema.org/Place" target="_blank">Place</a></u></li>    <li><u><a href="http://schema.org/LocalBusiness" target="_blank">LocalBusiness</a></u></li>    <li><u><a href="http://schema.org/FoodEstablishment" target="_blank">FoodEstablishment</a></u><u></u></li> </ul>  <p><u></u></p>  <p>We’re focusing on the <a href="http://schema.org/Restaurant" target="_blank">Restaurant</a><u></u> data type for the sake of brevity, but the concepts apply to other data types as well.</p>  <h3>Which data formats and scenarios should you scope out? </h3>  <p>Food with Friends will only support adding the restaurant to the user’s Wishlist if the restaurant information received matches that of a restaurant that the app is already aware of. This is intentional to avoid multiple copies of restaurants in the app. </p>  <p>We’re not supporting standard data types because most text, files, photos, URI or HTML shared from source apps won’t be mapped to a restaurant or local business. For example, if Food with Friends supported receiving text, it would show up in the target app list for a notetaking source app. In this case, Food With Friends would need to provide an error message telling the user why this app doesn’t work with their source app. Bottom line, the data formats are what connect a source app that has something to offer a target app. If the data formats aren’t the same, there’s nothing worthwhile to share.</p>  <p>Make sure you consider all data formats that help identify what you care about, scope out the data formats that dilute your share experience.</p>  <h3>Supporting the Share target contract</h3>  <p>To support data formats, declare them in the Visual Studio manifest designer for your app. This is what happens when a user selects your app as the target of a share action:</p>  <ol>   <li>A new instance of the app is launched in the share target window over the source app. </li>    <li>A <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.activation.sharetargetactivatedeventargs.aspx" target="_blank">share target activation</a> event is fired and your app receives a <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br205977.aspx" target="_blank">ShareOperation</a><b></b> object as a result.</li>    <li>Your app can retrieve the data that the user shared from this object. </li>    <li>You can use this data to render the target app view and complete the user’s share. </li> </ol>  <p>For more info about how to create this experience, see the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465255.aspx" target="_blank">Receiving shared content</a> <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465255.aspx"><u>Quickstart</u></a> guide. </p>  <p>Additionally, Visual Studio supports a template for share targets. Right-click your project, select <b>Add Item</b>, <b>Add New Item</b>, click <b>Share Target Contract</b> from the list and you get code added for supporting the contract. The <a href="http://code.msdn.microsoft.com/windowsapps/Sharing-Content-Target-App-e2689782" target="_blank">Share target code sample</a><u></u> shows how to receive shared content.</p>  <h2>Designing a tailored target app view</h2>  <p>When the user selects a target app from the list of apps in the Share pane, Windows launches the app in the app’s share target view. The target app view is a special view hosted in the Share pane and is different from the app’s main view. <a href="http://blogs.msdn.com/b/windowsappdev/archive/2012/03/23/activating-windows-8-contracts-in-your-app.aspx" target="_blank">Activating Windows 8 contracts in your app</a><u></u> gives more info about hosted views and handling activation for these views. The target app view is designed to help complete the share action initiated by the user. In this view, users should be able to preview their content at a glance, take simple actions, and confirm their intent to share. </p>  <p>Before we look at the target app design for Food with Friends, let’s consider a target app that you might already know. The images below show the target app view for the Mail app alongside the full view of the app in <a></a>Windows 8.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/1307.target-app_4AC68E75.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/1307.target_2D00_app_5F00_4AC68E75.png"><img title="Sharing from Photos to the Mail target app on the right" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Sharing from Photos to the Mail target app on the right" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/0724.target-app_thumb_5583E5CA.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/0724.target_2D00_app_5F00_thumb_5F00_5583E5CA.png" width="700" height="438" /></a></p>  <p align="center"><i>Figure 6: Sharing from Photos to the Mail target app on the right</i></p>  <p align="left"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/1385.mail_154DCC50.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/1385.mail_5F00_154DCC50.png"><img title="Composing a new mail in the main app view of Mail" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Composing a new mail in the main app view of Mail" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/2055.mail_thumb_510D6503.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/2055.mail_5F00_thumb_5F00_510D6503.png" width="700" height="438" /></a></p>  <p align="center"><em>Figure 7: Composing a new mail in the main app view of Mail</em></p>  <p>Notice that Mail’s share target app view is simpler than its full app view. It provides a clean and minimal preview of the content the user is about to share in the form of a thumbnail and associated text and HTML. It provides a <b>To</b> line for adding recipients, an input area for composing a quick message and an easy to way to confirm sending the mail through the <b>Send</b> button.</p>  <p>Despite this simpler view, the app’s target app view is clearly identifiable as an avatar of the Mail app, which reinforces user confidence about the destination of the shared content.</p>  <h2>Food with Friends as a share target app</h2>  <p>Now that you have a general idea about design for the target app view, let’s discuss how Food with Friends can create a target app helps users add restaurants to the ‘My Wishlist.’ </p>  <p>When Food with Friends receives the data package containing a <a href="http://schema.org/Restaurant">Restaurant</a> from the source app, it can use the details in the <a href="http://schema.org/Restaurant">Restaurant</a> data format to identify which restaurant from its existing database matches the received data package. The app can then show a preview of this restaurant in the target app view. This reinforces confidence in the integrity of the content being shared. </p>  <p>This image shows the target app view for Food with Friends –</p>  <p align="center"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/3857.contoso_truck3_0305058E.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/3857.contoso_5F00_truck3_5F00_0305058E.png"><img title="The target app view for Food with Friends" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="The target app view for Food with Friends" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/5584.contoso_truck3_thumb_1B94A2DE.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/5584.contoso_5F00_truck3_5F00_thumb_5F00_1B94A2DE.png" width="700" height="394" /></a><em>Figure 8: The target app view for Food with Friends</em></p>  <p>As you can see this view of Food with Friends is simple and tailored for a share target app - It shows a preview of the restaurant that the user is about to share and a simple actionable button, <b>Add to Wishlist</b> that clarifies the destination of the shared content in the main app. When the user taps or clicks this button, it confirms the share operation. By requiring a tap or click here, we help prevent accidental sharing and build confidence in the overall Share experience. </p>  <p>If the app finds multiple restaurants that match the info of the data package content, Food with Friends uses the share target app view to show the options and let the user pick which ones to share. </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/5582.contoso_truck4_70500BD6.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/5582.contoso_5F00_truck4_5F00_70500BD6.png"><img title="Target app view shows options so users can pick which items to share" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Target app view shows options so users can pick which items to share" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/6175.contoso_truck4_thumb_6FE3D8E1.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/6175.contoso_5F00_truck4_5F00_thumb_5F00_6FE3D8E1.png" width="700" height="394" /></a></p>  <p align="center"><em>Figure 9: Target app view shows options so users can pick which items to share</em></p>  <p>&#160;</p>  <p>In case the app cannot accurately identify a restaurant or a valid set of options based on the received data package, use the target app view to communicate that message. </p>  <h2>Creating a QuickLink</h2>  <p>A <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.datatransfer.sharetarget.quicklink.aspx" target="_blank">QuickLink</a> is a provision of the Share API that lets users share content to familiar destinations within your target app quickly. A QuickLink acts as a customized link to your target view, providing specific actions. When Windows filters the list of target apps available to the user, the list of QuickLinks is featured at the top of the Share pane as the list of available targets. These familiar destinations or user actions may include places or people that are shared with often through the target app. For example, the Mail app returns QuickLinks for previously mailed contacts. Similarly, you can add QuickLinks to folders, groups, notebooks, and playlists that you share often to your target app. </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/5001.quicklink_2FADBF67.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/5001.quicklink_5F00_2FADBF67.png"><img title="Share pane shows a QuickLink provided by the Mail target app for contacts " style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Share pane shows a QuickLink provided by the Mail target app for contacts " src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/1374.quicklink_thumb_334BDA44.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/1374.quicklink_5F00_thumb_5F00_334BDA44.png" width="700" height="438" /></a></p>  <p align="center"><i>Figure 10: Share pane shows a QuickLink provided by the Mail target app for contacts      <br />that have been previously mailed using the target app</i></p>  <p>The target app can provide a <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.datatransfer.sharetarget.quicklink.aspx" target="_blank">QuickLink</a><u></u> by calling <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br205977.aspx" target="_blank">ShareOperation</a><u></u><b><u> </u></b>objects’<b><u> </u></b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.datatransfer.sharetarget.shareoperation.reportcompleted.aspx" target="_blank">reportCompleted</a><b></b><b><u> </u></b>method. A QuickLink must have a title, an icon, and an ID. The title (like &quot;Email Mom&quot;) and icon appear when the user taps the Share charm. The ID is what your app uses to access any custom information, such as an email address, a folder location and so on. See <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh758299.aspx" target="_blank">How to Create a QuickLink</a><u></u> to learn more about this tool.&#160; </p>  <p>Note: QuickLinks are useful when the app supports multiple actions from the target app. Because Food with Friends only supports a single action in the Share target i.e. <b>Add to Wishlist</b>, the app doesn’t implement QuickLinks. </p>  <h2>Extended share and error reporting</h2>  <p>Sometimes source apps share large chunks of data like photos, videos, or files resulting in longer data transfer times. These types of share operations are known as <i>extended shares</i> where your target app might need more time to receive and process the data. </p>  <p>Because sharing is to be fast and fluid and the target app view is a lightweight, hosted view over the main app, users might tap away from the target app view to get back to their main app. Thus, target apps shouldn’t rely on or expect user interaction with the target app view after sharing has begun. Target apps can rely on using the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br205977.aspx" target="_blank">ShareOperation</a><b></b> object and its methods to let Windows know that the app is processing data. </p>  <ul>   <li><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.datatransfer.sharetarget.shareoperation.reportstarted.aspx" target="_blank">reportStarted</a></b> – call this method to let Windows know your app has started retrieving the data in the DataPackage object from the source app. </li>    <li><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.datatransfer.sharetarget.shareoperation.reportdataretrieved.aspx" target="_blank">reportDataRetrieved</a></b><b><u> </u></b>– call this method to let Windows know your app has finished retrieving the data in the package.</li>    <li><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.datatransfer.sharetarget.shareoperation.reportcompleted.aspx" target="_blank">reportCompleted</a></b><b><u> – </u></b>call this method to let Windows know your app has completed the Share operation.<b><u> </u></b><b><u></u></b></li> </ul>  <p>When your app is processing data for an extended share, give the user a progress UI in the target app view. This informs the user that their request is underway and reinforces confidence when they return to your app and check on the progress of the share operation. Check out <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465487.aspx" target="_blank">Quickstart: adding progress controls</a><u></u> to learn more about progress controls in Windows 8. </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/0702.progress-bar_52FAB40C.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/0702.progress_2D00_bar_5F00_52FAB40C.png"><img title="progress bar" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="progress bar" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/3438.progress-bar_thumb_40B1ED4A.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/3438.progress_2D00_bar_5F00_thumb_5F00_40B1ED4A.png" width="700" height="438" /></a></p>  <p align="center"><i>Figure 11: Mail target app view shows a progress ring when completing an extended share such as sending over large attachments</i></p>  <p>If something goes wrong during the data transfer and your target app has to end the share operation, you can call <b><u>reportError</u></b> to send an error message to Windows. The user will see the message when they check status of the share in the Share pane. After you report the error, your app is shut down and the share is ended. The user will need to start again to share the content to your app.</p>  <p>In the Food with Friends share target example, if the app cannot identify a restaurant in its database that matches the restaurant that was shared from the source app via the <a href="http://schema.org/Restaurant" target="_blank">Restaurant</a><u></u> data format, the app should report an error. </p>  <h2>Let’s review!</h2>  <p>App-to-app sharing provides a great opportunity to share target apps. By enabling your app to receive shared content, your users get value from your app even when they are involved in another activity. We hope you have a better understanding of the design principles as well data types, classes and properties that you can use to create a great share target destination. We’re excited to discover how your apps will transform shared content and create broader and richer end-user experiences.</p>  <p>If you want to learn more about sharing, read <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh464923.aspx" target="_blank">Sharing and Exchanging Data</a><u></u> and the <a href="http://code.msdn.microsoft.com/windowsapps/Sharing-Content-Target-App-e2689782" target="_blank">Share content target app sample</a><u></u> to get started!</p>  <p>Ishita Kapur</p>  <p>Program Manager</p>  <p>Windows User Experience</p>]]></content:encoded>
    </item>
    <item>
      <title>Develop a cutting edge app with NFC</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/develop-a-cutting-edge-app-with-nfc</link>
      <pubDate>Thu, 18 Apr 2013 15:25:54 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/04/18/develop-a-cutting-edge-app-with-nfc/</guid>
      <description><![CDATA[Near Field Communication (NFC) is an emerging, short range wireless technology. With a precise range...]]></description>
      <content:encoded><![CDATA[<p>Near Field Communication (NFC) is an emerging, short range wireless technology. With a precise range of 2 cm, people can physically tap devices together to send/receive content. Tapping lets you select something (or someone) quickly. Not only is it quick, it’s also easy to understand. Once you see it, you get it; there’s no manual needed.</p>  <p>For example, imagine you are looking at some photos with a friend and she wants your pictures; with NFC, you can simply tap your device against her PC to send the photos. Over simplifying? Maybe, but the main idea is that it’s simple to share content between devices.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/1732.NFC-image_04E645BB.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/1732.NFC_2D00_image_5F00_04E645BB.png"><img title="&#39;This image shows the Nokia 360 speaker sharing its Bluetooth pairing information with a Windows Phone" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="&#39;This image shows the Nokia 360 speaker sharing its Bluetooth pairing information with a Windows Phone" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/3566.NFC-image_thumb_38420917.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/3566.NFC_2D00_image_5F00_thumb_5F00_38420917.png" width="400" height="348" /></a></p>  <p align="center">Figure 1: This image shows the Nokia 360 speaker sharing its Bluetooth    <br />pairing information with a Windows Phone</p>  <p>Similar to Bluetooth or Wi-Fi, NFC is a standard wireless protocol defined by the <a href="http://www.nfc-forum.org/home/" target="_blank">NFC Forum</a><u></u><u>. </u>Your PC needs an NFC radio. There are lots of Windows 8 PCs that have NFC radios integrated directly into them. If NFC isn’t already part of your PC, you can buy NFC dongles to plug into your PC.</p>  <p>NFC offers some cool capabilities. People can tap and send photos, tap a menu and order a meal at a restaurant, or even tap to pair a Bluetooth device.&#160; These scenarios are pretty different from each other, but the thing they have in common is the 'tap' to initiate the experience.&#160; NFC is used in variety of devices, such as PCs, phones, speakers, headsets, wireless displays, etc..., to make connecting devices together a really intuitive experience.&#160; Also, NFC uses RFID tags; these are really cheap, lightweight passive antennas that can hold a sizable amount of data and can be stuck on virtually anything, most commonly posters.&#160; For example, buying a movie ticket could be as simple as tapping the movie poster!&#160; These are called NFC tags.&#160; We'll walk through a basic example of tapping an NFC tag to demonstrate some key concepts of the NFC API.</p>  <p>But first, let’s take a closer look at what it means to tap devices together.</p>  <h2>Defining a ‘Tap’</h2>  <p>Whether you’re tapping to pair a Bluetooth mouse or tapping to share photos, it’s important for users to tap devices together the same way. And while tapping is a well understood concept, tapping your PC against another device is new to most people. Here are some guidelines for tapping that let users know:</p>  <ol>   <li>     <div align="center"><b>Where to tap devices together</b> – by using a touchmark, also known as the ‘Tap and Do’ visual mark, indicating where the NFC antenna is located. Depending on the PC model, you tap different parts of the PC. For example, you may tap on the back on a tablet but on the front an all-in-one. Here’s what the mark looks like on any NFC enabled, Windows 8 PC:         <br /></div>     <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/0830.NFC-logo_66E85720.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/0830.NFC_2D00_logo_5F00_66E85720.png"><img title="Tap and Do visual mark" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Tap and Do visual mark" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/5611.NFC-logo_thumb_3FAE0DEB.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/5611.NFC_2D00_logo_5F00_thumb_5F00_3FAE0DEB.png" width="200" height="147" /></a>      <p align="center">Figure 2: Tap and Do visual mark</p>   </li>    <li><b>Devices are communicating with each other</b> - During the tap, users should have confidence that something is going on; even if they can’t see the data being transferred. Therefore, Windows plays a sound when devices are in-range and communicating with each other.</li> </ol>  <p>Windows does these things automatically, so you won’t need to worry about them. For more info on these user experience elements, see the <a href="http://msdn.microsoft.com/en-us/library/windows/hardware/hh770524.aspx" target="_blank">Windows 8 Near Field Proximity Implementation Specification</a><u></u>. With that in mind, let's check out some of the cool scenarios you can experience with NFC.</p>  <h2>When to use NFC </h2>  <p>Use NFC when a user needs to select something, or someone, in your app. NFC gives you an intuitive way to select; and it’s often faster (and cooler!) than manually searching. The tap is a trigger to initiate an experience; and depending on your app, the experience can range from receiving a photo to starting a playlist. It’s really up to your app to decide what happens after the tap. So, to keep it simple, we classify this range of experiences as ‘Tap and Do’ experiences.</p>  <p>Below are a few examples of using NFC to select something in an app. You could Tap and…</p>  <ul>   <li><u>Get information from a poster</u>: <a href="http://www.nfc-forum.org/news/pr/view?item_key=2c0cb92de7d47bbbe7c99f13912b3307fc03c1c6" target="_blank">NFC tags</a> are light, cheap RFID tags; they cost between $0.15 - $1.00 (price varies on printing cost). These are comparable to QR codes, but are easier and faster to use.&#160; Tapping a tag feels more comfortable than taking a picture of the bar code (and hoping the camera got the right angle).&#160; Manufacturers are increasingly embedding tags into posters in high traffic areas like airports, metro stations, and bus stops. They can hold between 48 B – 4 KB of data. You can program a tag to launch your app to a specific page. </li> </ul>  <ul>   <li>E<u>xchange contact information</u>: instead of spelling out your contact information to a friend, and hoping he didn’t misspell anything, tap devices together to exchange contact information. Similar to above, you can program your information to an NFC-business card/tag; or you could directly exchange information via an app.</li>    <li><u>Play your favorite music station</u>: whether you’re about to go work out, hopping into your car or just lounging at home – use an NFC tag to start a radio station. You can even have different music stations programmed on different tags; for example, one tag for the gym, one for lounging, and one for sleep.</li>    <li><u>Order dinner at a busy restaurant</u>: a popular restaurant at dinner time means you might be waiting a long time just to place an order. Instead, tap a tag at your table to order your food.</li>    <li><u>Play a multiplayer game with a friend: </u>you can easily connect a multiplayer game like Battleship, Chess, or Scrabble with a friend by tapping devices together. After the tap, the connection persists over an out-of-band transport with a bigger range and higher throughput, such as Bluetooth or Wi-Fi Direct. </li> </ul>  <p>By now, we’ve got a pretty good idea of when to use NFC; now for fun stuff – building an app that uses our Windows 8 Proximity (NFC) APIs.</p>  <h2>How to implement NFC </h2>  <p>As you can see NFC makes lots of everyday tasks easier for end-users. Take setting an alarm for example. I’m sure just about everyone has had a few experiences where they mistakenly set their alarm for the wrong time in the morning. When its late and you just want to get to sleep, you’re not always thinking at your best. NFC makes this easier by letting you just tap a preset tag, confirm, and then go to sleep worry free. So to help users with this everyday task let’s imagine you wrote a basic alarm app that let users set an alarm using an NFC tag. This breaks into two scenarios</p>  <ol>   <li><u>Setting an alarm <b>on</b> the tag</u>: NFC tags can be reusable, so the app should have a way for users to program an alarm. For example, a user may want to program different alarms – one for the week, another for the weekend. This is known as publishing data to a tag.</li>    <li><u>Setting an alarm <b>from</b> the tag</u>: After a user taps a tag, the app should launch to confirm setting an alarm. This means the app can be launched with context, or arguments. </li> </ol>  <p>The NFC API allows for several ways to achieve the same thing, but I’ll go over the simplest way to implement this scenario.</p>  <p>Let’s walk through a flow to set an alarm on an NFC tag:</p>  <ol>   <li>Mario launches the alarm app and sets a time, say 7.00 AM. Normal alarm stuff, nothing with NFC yet.</li>    <li>Mario selects an option to ‘Set alarm on an NFC tag’. At this time, the app calls the NFC APIs to publish information to the NFC radio, specifically an app identifier string &amp; 07:00. NFC tags use a standardized message format called NDEF, NFC Defined Exchange Format. Your app does <b>not </b>need to worry about formatting data into an NDEF message; Windows does this for you! Now, the user can tap the NFC tag.</li>    <li>Mario taps the tag against the PC and the app confirms programming the tag. After the tag is tapped, it’s important to let users know that your app successfully programmed the tag. As we discussed earlier – tapping your PC is a new concept for most people, so the confirmation gives users confidence that what they just did worked. The app knows a message was successfully transmitted by registering for a message transmitted handler.</li> </ol>  <p>The NFC APIs are located in the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.proximity.aspx" target="_blank">Windows.Networking.Proximity</a> namespace. They come into play at step 2 – after the user selects the option to ‘Set alarm on NFC tag.’ First, the app initializes a proximity object. The proximity object is used to tell when a tag (or device) is in/out of range. Next, we’ll add the DeviceArrival event handler. The handler recognizes when the tag has been tapped, which means we can start writing information to the tag. It’s useful to let users know when you’re writing to a tag, so they don’t move it out of range. You can use the same event to recognize when any proximity device has been tapped.</p>  <p>The next code snippet shows how to initialize and add a DeviceArrival event handler.</p>  <p><strong>JavaScript</strong></p>  <blockquote>   <div>     <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> proximityDevice;<br /><br /><span style="color: rgb(0, 0, 255);">function</span> initializeProximityDevice() {<br />    proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();<br /><br />    <span style="color: rgb(0, 0, 255);">if</span> (proximityDevice) {<br />        proximityDevice.addEventListener(<span style="color: rgb(0, 96, 128);">&quot;devicearrived&quot;</span>, proximityDeviceArrived);<br />       <br />}<br />   <span style="color: rgb(0, 0, 255);">else</span> {<br />        <span style="color: rgb(0, 128, 0);">// No NFC radio on the PC, display an error message</span><br />    }<br /><br /><br /><span style="color: rgb(0, 0, 255);">function</span> proximityDeviceArrived(device) {<br />        <span style="color: rgb(0, 128, 0);">// Let the user know we’re ‘Writing to Tag’</span><br /><br />}<br />}<br /></pre>
  </div>
</blockquote>

<div>
  <br /><strong>C#</strong></div>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">private</span> <span style="color: rgb(0, 0, 255);">void</span> InitializeProximityDevice()<br />{<br /><br />Windows.Networking.Proximity.ProximityDevice proximityDevice;<br />    proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();<br /><br />    <span style="color: rgb(0, 0, 255);">if</span> (proximityDevice != <span style="color: rgb(0, 0, 255);">null</span>) {<br />        proximityDevice.DeviceArrived += ProximityDeviceArrived;<br />    <br />    }<br />    <span style="color: rgb(0, 0, 255);">else</span><br />    {<br />        <span style="color: rgb(0, 128, 0);">// No NFC radio on the PC, display an error message</span><br />    }<br />}<br /><br /><span style="color: rgb(0, 0, 255);">private</span> <span style="color: rgb(0, 0, 255);">void</span> ProximityDeviceArrived(Windows.Networking.Proximity.ProximityDevice device)<br />{<br />            <span style="color: rgb(0, 128, 0);">// Let the user know we’re ‘Writing to Tag’</span><br /><br />}<br /></pre>
  </div>
</blockquote>

<p>
  <br />Next, we publish information to the tag. The app publishes two things: an app identifier string, which consists of an app ID and app platform, and launch arguments. For Windows 8, the app Id is &lt;<a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.packageid.familyname.aspx" target="_blank">package family name</a>&gt;!&lt;<a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211415.aspx" target="_blank">app Id</a>&gt; and the app platform is ‘Windows.’ You must copy the app ID value from the ID attribute of the Application element in the package manifest for your app. The launch argument is ’07:00’ – the alarm set by the user. Let’s call this the <b>message</b>.</p>

<p>If the app works across platforms, Windows lets you publish alternate app ID(s) and app platform(s); which means you can tap the same tag on a different device which support NFC, like Windows Phone 8! You can find more information about <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.proximity.peerfinder.alternateidentities.aspx" target="_blank">Alternate IDs</a> on MSDN.</p>

<p>The app publishes the data to the tag using a method called <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh701134.aspx" target="_blank">publishBinaryMessage</a>. The method takes three parameters – messageType, message, and a messageTransmittedHandler function. We’ll set messageType to ‘LaunchApp:WriteTag’, which lets Windows know that your app wants to write information to an NFC tag. The message is just the message we defined earlier (app identified string and launch arguments); we’ll need to store the message as a binary message in a buffer. The messageTransmittedHandler function registers for callbacks. This lets your app know that the message has successfully been written to the tag. We’ll use this to tell the user two things: we’ve successfully written a message to the tag and the tag no longer needs to be in range.</p>

<p>Messages continue to be published until we call the StopPublishingMessage function or the ProximityDevice object is released. In this example, we’ll use the stop function. PublishBinaryMessage returns a publication ID; we’ll use this same publication ID to stop publishing the message onto the NFC Radio.</p>

<p>The next code snippet shows how to write data to an NFC tag:</p>

<p><strong>JavaScript</strong></p>

<blockquote>
  <div>
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> proximityDevice;<br /><br /><span style="color: rgb(0, 0, 255);">function</span> getAlarmTime(){<br /><br />    <span style="color: rgb(0, 128, 0);">// Grab time set by the user, call this variable ‘Alarm’</span><br />    <span style="color: rgb(0, 0, 255);">return</span> Alarm;<br /><br />}<br /><br /><span style="color: rgb(0, 0, 255);">function</span> publishLaunchApp() {<br />    proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();<br /><br /><span style="color: rgb(0, 0, 255);">if</span> (proximityDevice) {<br />        <span style="color: rgb(0, 128, 0);">// The format of the app launch string is: &quot;&lt;args&gt;\tWindows\t&lt;AppName&gt;&quot;.</span><br />        <span style="color: rgb(0, 128, 0);">// The string is tab or null delimited.</span><br /><br />        <span style="color: rgb(0, 128, 0);">// The &lt;args&gt; string can be an empty string (&quot;&quot;).</span><br />        <span style="color: rgb(0, 0, 255);">var</span> launchArgs = getAlarmTime();<br /><br />        <span style="color: rgb(0, 128, 0);">// The format of the AppName is: PackageFamilyName!PRAID.</span><br />        <span style="color: rgb(0, 0, 255);">var</span> praid = <span style="color: rgb(0, 96, 128);">&quot;AlarmApp&quot;</span>; <span style="color: rgb(0, 128, 0);">// The Application Id value from your package.appxmanifest.</span><br /><br />        <span style="color: rgb(0, 0, 255);">var</span> appName = Windows.ApplicationModel.Package.current.id.familyName + <span style="color: rgb(0, 96, 128);">&quot;!&quot;</span> + praid;<br /><br />        <span style="color: rgb(0, 0, 255);">var</span> launchAppMessage = launchArgs + <span style="color: rgb(0, 96, 128);">&quot;\tWindows\t&quot;</span> + appName;<br /><br />        <span style="color: rgb(0, 0, 255);">var</span> dataWriter = <span style="color: rgb(0, 0, 255);">new</span> Windows.Storage.Streams.DataWriter();<br />        dataWriter.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf16LE;<br />        dataWriter.writeString(launchAppMessage);<br />        <span style="color: rgb(0, 0, 255);">var</span> launchAppPubId =<br />             proximityDevice.publishBinaryMessage(<br />                 <span style="color: rgb(0, 96, 128);">&quot;LaunchApp:WriteTag&quot;</span>, <br />                 dataWriter.detachBuffer(), <br />                 proximityWriteTagLaunchAppMessageTransmitCallback);<br />        <br />    <span style="color: rgb(0, 0, 255);">if</span> (launchAppPubId != -1) {<br />            <span style="color: rgb(0, 128, 0);">// Stop publishing the message on NFC radio</span><br />        proximityDevice.stopPublishingMessage(launchAppPubId);<br />    }<br /><br />     }<br />}<br /><br /><span style="color: rgb(0, 0, 255);">function</span> proximityWriteTagLaunchAppMessageTransmitCallback() {<br />    <span style="color: rgb(0, 128, 0);">// Inform the user that: the message has been successfully written to a tag &amp; the tag no longer needs to be in range</span><br />}<br /></pre>
  </div>
</blockquote>

<div>
  <br /><strong>C#</strong></div>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">Windows.Networking.Proximity.ProximityDevice proximityDevice;<br /><br /><span style="color: rgb(0, 0, 255);">private</span> <span style="color: rgb(0, 0, 255);">string</span> GetAlarmTime(){<br /><br />    <span style="color: rgb(0, 128, 0);">// Grab time set by the user, call this variable ‘Alarm’</span><br />    <span style="color: rgb(0, 0, 255);">return</span> Alarm;<br />}<br /><br /><span style="color: rgb(0, 0, 255);">private</span> <span style="color: rgb(0, 0, 255);">void</span> PublishLaunchApp()<br />{<br />    proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();<br /><br /><span style="color: rgb(0, 0, 255);">if</span> (proximityDevice != <span style="color: rgb(0, 0, 255);">null</span>)<br />    {<br />        <span style="color: rgb(0, 128, 0);">// The format of the app launch string is: &quot;&lt;args&gt;\tWindows\t&lt;AppName&gt;&quot;.</span><br />        <span style="color: rgb(0, 128, 0);">// The string is tab or null delimited.</span><br /><br />        <span style="color: rgb(0, 128, 0);">// The &lt;args&gt; string can be an empty string (&quot;&quot;).</span><br />        <span style="color: rgb(0, 0, 255);">string</span> launchArgs = getAlarmTime();<br /><br />        <span style="color: rgb(0, 128, 0);">// The format of the AppName is: PackageFamilyName!PRAID.</span><br />        <span style="color: rgb(0, 0, 255);">string</span> praid = <span style="color: rgb(0, 96, 128);">&quot;MyAppId&quot;</span>; <span style="color: rgb(0, 128, 0);">// The Application Id value from your package.appxmanifest.</span><br /><br />        <span style="color: rgb(0, 0, 255);">string</span> appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + <span style="color: rgb(0, 96, 128);">&quot;!&quot;</span> + praid;<br /><br />        <span style="color: rgb(0, 0, 255);">string</span> launchAppMessage = launchArgs + <span style="color: rgb(0, 96, 128);">&quot;\tWindows\t&quot;</span> + appName;<br /><br />        var dataWriter = <span style="color: rgb(0, 0, 255);">new</span> Windows.Storage.Streams.DataWriter();<br />        dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;<br />        dataWriter.WriteString(launchAppMessage);<br />        var launchAppPubId =<br />        proximityDevice.PublishBinaryMessage(<br />            <span style="color: rgb(0, 96, 128);">&quot;LaunchApp:WriteTag&quot;</span>, dataWriter.DetachBuffer(), <br />            proximityWriteTagLaunchAppMessageTransmitCallback);<br />    <br />    <span style="color: rgb(0, 0, 255);">if</span> (launchAppPubId!= -1)<br />    {<br />        proximityDevice.StopPublishingMessage(launchAppPubId);<br />    <span style="color: rgb(0, 128, 0);">// Stop publishing the message on NFC radio</span><br />    }<br /><br />    }<br />}<br /><br /><span style="color: rgb(0, 0, 255);">private</span> <span style="color: rgb(0, 0, 255);">void</span> proximityWriteTagLaunchAppMessageTransmitCallback(<br />    Windows.Networking.Proximity.ProximityDevice sender,<br />    <span style="color: rgb(0, 0, 255);">long</span> messageId)<br />{<br />        <span style="color: rgb(0, 128, 0);">// Inform the user that: the message has been successfully written to a tag &amp; the tag no longer needs to be in range</span><br />}<br /></pre>
  </div>
</blockquote>

<br />That’s it! Now you know how to write to an NFC tag from a Windows Store app. Simple enough; so, let’s move onto the next scenario - setting an alarm <b>from</b> the tag. Let’s walk through a flow to read an alarm from an NFC tag: 

<ol>
  <li>Mario is reading his home screen/writing an email/playing a game/using Windows and he realizes he needs to set an alarm for Monday morning. He grabs his ‘Weekday alarm’ tag and taps it on his PC. He gets a toast inviting him to launch your Alarm app. Windows takes care of everything up until this point; your app doesn’t do a thing.</li>

  <li>Mario accepts and your app launches to a ‘Confirm Alarm?’ screen with a time of 7:00 AM. After Mario accepts the toast, Windows passes the launch arguments (same as above) to your app during activation. This is called contextual launching, which is the same thing as launching your app to specific page.</li>

  <li>Mario sets the alarm. Normal alarm stuff, no NFC.</li>
</ol>

<p>It’s easy enough to get the launch arguments from the NFC tag. The app needs to handle contextual launching from an NFC tag. Contextual launching is the synonymous with launching your app to a specific page. Our launch arguments specify an alarm, 7.00 AM, which your app uses to display a proposed alarm. Also, in case your app isn’t installed on the PC, Windows invites Mario to install your app from the Windows store – automatically!</p>

<p>The following code snippet shows how to implement contextual launching.</p>

<p><strong>JavaScript</strong></p>

<blockquote>
  <div>
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">app.onactivated = <span style="color: rgb(0, 0, 255);">function</span> (args) {<br />    <span style="color: rgb(0, 0, 255);">if</span> (args.detail.kind === activation.ActivationKind.launch) {<br />        <span style="color: rgb(0, 0, 255);">if</span> (args.detail.arguments == <span style="color: rgb(0, 96, 128);">&quot;Windows.Networking.Proximity.PeerFinder:StreamSocket&quot;</span>) {<br />            <span style="color: rgb(0, 128, 0);">//do nothing here.</span><br />        }<br />        <span style="color: rgb(0, 0, 255);">else</span> {<br />    <span style="color: rgb(0, 128, 0);">// Use args.detail.arguments to parse out ’07.00’ string, and display to the user</span><br />        }<br /><br />        args.setPromise(WinJS.UI.processAll());<br />    }<br />}<br /></pre>
  </div>
</blockquote>

<div>
  <br /><strong>C#</strong></div>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">async <span style="color: rgb(0, 0, 255);">protected</span> <span style="color: rgb(0, 0, 255);">override</span> <span style="color: rgb(0, 0, 255);">void</span> OnLaunched(LaunchActivatedEventArgs args)<br />        {<br />            <span style="color: rgb(0, 0, 255);">if</span> (args.Arguments == <span style="color: rgb(0, 96, 128);">&quot;Windows.Networking.Proximity.PeerFinder:StreamSocket&quot;</span>)<br />            {<br />                _isLaunchedByTap = <span style="color: rgb(0, 0, 255);">true</span>;<br />            }<br />            <span style="color: rgb(0, 0, 255);">else</span><br />            {<br /><span style="color: rgb(0, 128, 0);">// Use args.Arguments to parse out ’07.00’ string, and display to the user</span><br /><br />            }<br />            Window.Current.Activate();<br />        }<br /></pre>
  </div>
</blockquote>

<p>
  <br />That’s all your app has to do to support reading and writing to an NFC tag; pretty simple for a cutting edge scenario. Before I wrap up, let’s go over some good hygiene stuff – error handling.</p>

<h2>Error Handling</h2>

<p>There are a few common errors your app may run into.</p>

<ul>
  <li>The tapped tag is not NDEF formatted. Windows 8 doesn’t support automatically reformatting a tag to NDEF, so you’ll need to download and install an NDEF formatter.</li>

  <li>The tapped tag is read-only. Some NFC tags can be locked to read-only (similar to old school <a href="http://en.wikipedia.org/wiki/VHS" target="_blank">VHS tapes</a>).</li>

  <li>The tapped tag is too small and cannot hold all the data.</li>

  <li>A users PC doesn’t have NFC. As I mentioned from the start, NFC is an emerging technology; widespread adoption is still growing. To check whether a PC supports proximity, use the ProximityDevice.getDefault() method; the method returns NULL if no NFC radios are installed.</li>
</ul>

<h2>It’s fun and intuitive!</h2>

<p>NFC is finally here, ready for mainstream consumers – Windows has the ecosystem and a well-designed end-to-end UX. The technology has a lot of potential to make apps and device experiences incredibly interactive. It’s fun and intuitive. </p>

<p>NFC is a big area, so stay tuned for more blog posts on other cool Windows 8 NFC developer experiences.</p>

<p>For more info about NFC and proximity, check out the resources below.</p>

<h2>Resources</h2>

<div align="center">
  <table class="b8table" cellspacing="0" cellpadding="3" width="298" align="center" border="0"><tbody>
      <tr>
        <td valign="top" width="197">
          <p><strong>Link</strong></p>
        </td>

        <td valign="top" width="99">
          <p><strong>Types</strong></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="197">
          <p align="left"><u><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465215.aspx" target="_blank">Guidelines for using proximity experiences</a></u></p>
        </td>

        <td valign="top" width="99">
          <p>Doc</p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="197">
          <p align="left"><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br241250.aspx" target="_blank">Proximity APIs</a></p>
        </td>

        <td valign="top" width="99">
          <p>Doc</p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="197">
          <p align="left"><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh967765.aspx" target="_blank">Testing and troubleshooting proximity apps</a></p>
        </td>

        <td valign="top" width="99">
          <p>Doc</p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="197">
          <p align="left"><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465223.aspx" target="_blank">Publishing and subscribing (in further detail)</a></p>
        </td>

        <td valign="top" width="99">
          <p>Doc</p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="197">
          <p align="left"><a href="http://code.msdn.microsoft.com/windowsapps/Proximity-Sample-88129731" target="_blank">Proximity app sample</a></p>
        </td>

        <td valign="top" width="99">
          <p>Sample</p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="197">
          <p align="left"><a href="http://social.msdn.microsoft.com/Forums/en-us/category/windowsapps" target="_blank">Got a question on proximity? Ask it here</a></p>
        </td>

        <td valign="top" width="99">
          <p>Forum</p>
        </td>
      </tr>
    </tbody></table>
</div>

<p>Thanks,</p>

<p>Priya Dandawate 
  <br />Program Manager, Devices and Networking</p>

<p>Contributions by: Max Morris, Marzena Makuta,&#160; Mike Loholt, Jake Sabulsky, and Vishal Mhatre</p>]]></content:encoded>
    </item>
    <item>
      <title>Creating connected Windows Store apps</title>
      <link>https://docs.microsoft.com/archive/blogs/windowsappdev/creating-connected-windows-store-apps</link>
      <pubDate>Wed, 10 Apr 2013 09:00:00 GMT</pubDate>
      <dc:creator><![CDATA[Windows 8 Team]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/windowsappdev/2013/04/10/creating-connected-windows-store-apps/</guid>
      <description><![CDATA[People are continually surrounded by devices that are connected to a network. Even the latest...]]></description>
      <content:encoded><![CDATA[<p>People are continually surrounded by devices that are connected to a network. Even the latest refrigerators and washing machines can connect to the internet and home networks. So it’s no surprise that end-users expect their apps to be connected as well. These “connected apps” consume the latest content from the web—social media, digital media, blogs, and other types of content. Developing connected apps has become the norm, but it can still be a challenge to handle common issues like loss of network connectivity, metered network costs, or performance issues. Windows 8 makes it easier than ever before to write a connected app. </p>  <p>In this post, we’ll look at some useful tips to help you provide a fast and fluid, hassle-free, connected experience for users of your Windows Store apps: </p>  <ul>   <li>Pick the right API for your scenarios</li>    <li>Choose the right network capabilities</li>    <li>Adapt app behavior for metered networks</li>    <li>React to network status changes</li>    <li>Cache content for fluidity</li> </ul>  <p>Let’s dive into the details of each tip.</p>  <h2>Pick the right API</h2>  <p>If you're going to build a house, you want the right tools. You want a hammer for hammering nails, a saw for cutting boards, and a screwdriver for fastening with screws. In the same way, you’ll want to use the right networking APIs when you develop a connected Windows Store app. Windows 8 provides a variety of networking APIs that your app can use to communicate with other computers and devices over either the Internet or private networks. So your first step is to figure out what networking features your app needs. </p>  <p>The most common networking scenario is to access a web site to retrieve or store information. A simple example would be a game that uses a website to store user information and game scores. A more complex example might be an app that connects to a REST-based web service and uses a library provided by the web service to access or store information. Windows 8 has several APIs that connect with web services and web sites. With these APIs your app can access web services that support REST or send basic HTTP protocol commands (like GET and POST) to a web server. For web access, the API you want depends on the language you use to develop the app:</p>  <ul>   <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh453379.aspx" target="_blank">XMLHTTPRequest</a> and <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br229787.aspx" target="_blank">WinJS.xhr</a>—Apps written in JavaScript and HTML.</li>    <li><a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx" target="_blank">HttpClient</a>—Apps written in C# or Visual Basic .NET and XAML.</li>    <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh831163.aspx" target="_blank">XML HTTP Request 2</a> (IXHR2)—Apps written in C++ and XAML.</li> </ul>  <p>The following code shows how to perform a basic request and response with a REST-based web service. In this case, the web service could execute an ASP.NET script on the web server.</p>  <p><strong>JavaScript</strong></p>  <blockquote>   <div id="codeSnippetWrapper">     <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">function</span> makeXHRCall() {<br />    WinJS.xhr({ uri: <span style="color: rgb(0, 96, 128);">&quot;http://www.microsoft.com/en-us/default.aspx” }).done(<br />        function onComplete(result) {<br />            print(result.responseText);<br />        },<br />        function onError(err) {<br />            print(&quot;</span>Error: &quot; + err.responseText);<br />        });<br />}<br /></pre>
  </div>
</blockquote>

<p><strong>C#</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">private</span> async <span style="color: rgb(0, 0, 255);">void</span> MakeHttpCall()<br />{<br />    HttpClient httpClient = <span style="color: rgb(0, 0, 255);">new</span> HttpClient();<br />    <span style="color: rgb(0, 0, 255);">try</span> {<br />        <span style="color: rgb(0, 0, 255);">string</span> response = await httpClient.GetStringAsync(<span style="color: rgb(0, 96, 128);">&quot;http://www.microsoft.com/en-us/default.aspx&quot;</span>);<br />    }<br />    <span style="color: rgb(0, 0, 255);">catch</span> (Exception) {<br />        <span style="color: rgb(0, 128, 0);">// Handle exception.</span><br />    }<br />}<br /></pre>

    <br /></div>
</blockquote>

<p>For more info about <b>WinJS.xhr</b>, see<u> </u><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh761502.aspx" target="_blank">Connecting to web services (Windows Store apps using JavaScript and HTML)</a>. For more information about <b>HttpClient</b>, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh781239.aspx" target="_blank">Quickstart: Connecting using HttpClient (Windows Store apps using C#/VB/C++ and XAML)</a> and the <a href="http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664" target="_blank">HttpClient sample</a>.</p>

<p>Another common networking scenario is downloading or uploading files where the file transfer may take some time. An example would be a camera or photo gallery app that needs to upload or download photos or photo albums from a web service. These transfers can take a lot of time, so it doesn't make sense to have the user wait for the transfer to finish. The <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.backgroundtransfer.aspx" target="_blank">Windows.Networking.BackgroundTransfer</a> API provides the ability to download or upload files even when your app is no longer running. The app starts the transfer when it’s running in the foreground and has focus, and Windows 8 then continues the transfer in the background even if the app is no longer running.</p>

<p>Another more specialized scenario is accessing syndicated content. The <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.web.syndication.aspx" target="_blank">Windows.Web.Syndication</a> API can retrieve feeds in the RSS or Atom formats. In addition, the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.web.atompub.aspx" target="_blank">Windows.Web.AtomPub</a> API allows an app to publish data in various AtomPub formats.</p>

<p>For scenarios for which a specific, higher-level networking protocol is not available through an API, the Windows Runtime also supports TCP and UDP sockets (along with multicast). The <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.sockets.aspx" target="_blank">Windows.Networking.Sockets</a> API provides a <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.sockets.streamsocket.aspx" target="_blank">StreamSocket</a> (TCP) and <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.sockets.datagramsocket.aspx" target="_blank">DatagramSocket</a> (UDP) to let you to implement other, higher-layer protocols.</p>

<p><b>Note: </b>Windows 8 introduces a new type of socket called a <i>WebSocket</i>. For more information about WebSockets and when to use them, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh761442.aspx" target="_blank">Connecting with WebSockets</a>.</p>

<p>The following table provides a more complete list of supported networking features, with links to additional information.</p>

<div align="center">&#160; <table class="b8table" cellspacing="0" cellpadding="3" align="center" border="0"><tbody>
      <tr>
        <td valign="top" width="217">
          <p align="center"><b>APIs</b><b></b></p>
        </td>

        <td valign="top" width="221">
          <p align="center"><b>Functionality</b><b></b></p>
        </td>

        <td valign="top" width="145">
          <p align="center"><b>Examples</b><b></b></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="217">
          <ul>
            <li>
              <div align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.web.syndication.aspx" target="_blank">Windows.Web.Syndication</a></b><b></b></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.web.atompub.aspx" target="_blank">Windows.Web.AtomPub</a></b><b></b></div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>

        <td valign="top" width="221">
          <p align="left"></p>

          <p align="left">Retrieving feeds in the RSS or Atom formats across multiple versions. These APIs make it easy to implement support for newer formats such as OData. The Windows Runtime also supports the Atom Publishing Protocol, enabling the publication of Atom collections. 
            <br />For more information, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh452973.aspx/" target="_blank">Accessing and managing syndicated content</a>.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="145">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/Syndication-sample-07ef6b0d" target="_blank">Syndication sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/AtomPub-sample-c1fcdc8e" target="_blank">AtomPub sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">RSS Readers</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="217">
          <p align="left"></p>

          <p align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.backgroundtransfer.aspx" target="_blank">Windows.Networking.BackgroundTransfer</a></b></p>

          <p align="left"></p>
        </td>

        <td valign="top" width="221">
          <p align="left"></p>

          <p align="left">Uninterrupted, cost-aware, and resumeable downloading and uploading of content, even when the calling app is not in the foreground. This API supports content transfer using the HTTP, HTTPS, and FTP protocols. 
            <br />For more information, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh452979.aspx" target="_blank">Transferring data in the background</a>.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="145">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/Background-Transfer-Sample-d7833f61" target="_blank">Background Transfer sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">SkyDrive</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Xbox Video</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="217">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh453379.aspx" target="_blank">XMLHTTPRequest</a></b><b> (JavaScript</b><b>) </b></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br229787.aspx" target="_blank">WinJS.xhr</a></b><b> </b><b>(JavaScript)</b></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left"><b><a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx" target="_blank">HttpClient</a></b><b> </b><b>(C#)</b></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh831163.aspx">XML HTTP Request 2</a></b><b> (IXHR2)</b><b> </b><b>(C++)</b><b></b></div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>

        <td valign="top" width="221">
          <p align="left"></p>

          <p align="left">Interacting with REST-based web services and other HTTP-based protocols. 
            <br />For more information, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh761502.aspx" target="_blank">Connecting to web services</a>.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="145">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/XHR-handling-navigation-50d03a7a" target="_blank">XHR, handling navigation errors, and URL schemes sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664" target="_blank">HttpClient sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Bing Maps</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="217">
          <p align="left"></p>

          <p align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.proximity.aspx" target="_blank">Windows.Networking.Proximity</a></b></p>

          <p align="left"></p>
        </td>

        <td valign="top" width="221">
          <p align="left"></p>

          <p align="left">Detecting close proximity between two devices, after which apps can trigger network communication between them using socket APIs. 
            <br />For more information, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465229.aspx" target="_blank">Supporting proximity and tapping</a>.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="145">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/Proximity-Sample-88129731" target="_blank">Proximity sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Games</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Collaborative apps</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="217">
          <p align="left"></p>

          <p align="left"><b><a href="http://msdn.microsoft.com/library/windows/apps/BR207928" target="_blank">Windows.Storage.Pickers</a></b><b></b></p>

          <p align="left"></p>
        </td>

        <td valign="top" width="221">
          <p align="left"></p>

          <p align="left">Communicating with remote file shares. 
            <br />For more information, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh464959.aspx" target="_blank">Accessing data and files</a>.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="145">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/File-picker-sample-9f294cba" target="_blank">File picker sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Xbox Music</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Photos</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="217">
          <p align="left"></p>

          <p align="left"><b><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.sockets.aspx" target="_blank">Windows.Networking.Sockets</a></b><b></b></p>

          <p align="left"></p>
        </td>

        <td valign="top" width="221">
          <p align="left"></p>

          <p align="left">Connecting to a service that uses a protocol not supported by APIs already mentioned, like SMTP, MAPI, or telnet, or connecting to another device on the same local network. Also used for apps that require socket-like semantics (asynchronous, bidirectional) to connect through the web (including HTTP proxies) to a new service. 
            <br />For more information, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh452977.aspx" target="_blank">Connecting with sockets</a>.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="145">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/StreamSocket-Sample-8c573931" target="_blank">StreamSocket sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/DatagramSocket-sample-76a7d82b" target="_blank">DatagramSocket sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/Connecting-with-WebSockets-643b10ab" target="_blank">Connecting with WebSockets sample</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left"><a href="http://code.msdn.microsoft.com/windowsapps/site/search?query=controlchanneltrigger&amp;f%5B0%5D.Value=controlchanneltrigger&amp;f%5B0%5D.Type=SearchText&amp;ac=3" target="_blank">ControlChannelTrigger samples</a></div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Lync, collaborative whiteboard, or stock pickers</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="217">
          <p align="left"></p>

          <p align="left"><b><a href="http://msdn.microsoft.com/library/windows/apps/BR241587" target="_blank">Windows.Storage.ApplicationData</a></b></p>

          <p align="left"></p>
        </td>

        <td valign="top" width="221">
          <p align="left"></p>

          <p align="left">Windows 8 automatically transitions certain application data between user devices. Roaming application data benefits apps where the user utilizes more than one device, such as a PC at work and a tablet at home, and installs the app on multiple devices. 
            <br />For more information, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465094.aspx" target="_blank">Guidelines for roaming application data</a>.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="145">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left"><a href="http://go.microsoft.com/fwlink/p/?linkid=231478" target="_blank">Application data sample</a></div>
            </li>
          </ul>
        </td>
      </tr>
    </tbody></table>
</div>

<h2>Choose the right network capabilities</h2>

<p>Network isolation is part of the app security model used by Windows 8. Windows actively discovers network boundaries and enforces network access restrictions for network isolation. When you deploy them properly, these capabilities help protect your users and apps from malicious attacks.</p>

<p>Apps must declare network isolation capabilities in order to define the scope of network access. Without declaring these capabilities, your app will not have access to network resources. See <a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh770532.aspx" target="_blank">How to set network capabilities</a> to learn more about how Windows enforces network isolation for apps. </p>

<p>Note that you can’t use networking as an interprocess communication mechanism between a Windows Store app and a desktop app on the same device. So you can’t use IP loopback addresses in a Windows Store app. There are limited exceptions for development purposes that allow use of IP loopback addresses when operating under the Visual Studio debugger. For more information, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh780593.aspx" target="_blank">How to enable loopback and troubleshoot network isolation</a>.</p>

<p>Network access requests come in two categories: </p>

<ol>
  <li><b>Outbound, client-initiated requests</b>: Your app acts as the client and initiates network access by sending an initial network request to a remote computer, usually a server. The app sends one or more requests to the server and the server sends back a single response or several responses. For example, all traffic from a web client app to a web server would be in this category.</li>

  <li><b>Inbound, unsolicited requests</b>: Your app acts as a network server and listens for inbound network requests from a remote computer. The remote computer initiates network access by sending an initial request to your app, which acts as a server. The remote computer sends one or more requests to your app, which sends back one or more responses to the remote computer. For example, an app that functions as a media server would be in this category.</li>
</ol>

<p>Follow the principle of least privilege and add only capabilities your app needs. Your app might need only outbound, client-initiated requests, or it may also need to receive inbound, unsolicited requests. Some apps may also need access to user credentials and certificates when authenticating over a network. </p>

<p>The following table details the network isolation capabilities and other related capabilities often needed for connected apps. The first three are the primary network-isolation capabilities that connected apps use. In fact, your connected app must enable at least one of those first three capabilities. The other entries in the table are additional capabilities often needed by some connected apps.</p>

<p>&#160;</p>

<div align="center">
  <table class="b8table" cellspacing="0" cellpadding="3" width="612" align="center" border="0"><tbody>
      <tr>
        <td valign="top" width="146">
          <p><b>Network capability</b></p>
        </td>

        <td valign="top" width="273">
          <p><b>Description</b></p>
        </td>

        <td valign="top" width="191">
          <p><b>Example apps</b></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="146">
          <p align="left">Internet (Client)</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="273">
          <p align="left"></p>

          <p align="left">Provides outbound access to the Internet and networks in public places like airports and coffee shops. Most apps that require Internet access should declare this capability.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="191">
          <p align="left">&#160;&#160;&#160;&#160;&#160;&#160;&#160; </p>

          <ul>
            <li>
              <div align="left">RSS readers</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Social networks</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Games</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="146">
          <p align="left"></p>

          <p align="left">Internet (Client &amp; Server)</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="273">
          <p align="left"></p>

          <p align="left">Provides both inbound and outbound access to the Internet and networks in public places like airports and coffee shops. Inbound access to critical ports are always blocked. This capability is a superset of the Internet (Client) capability; there is no need to declare both.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="191">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left">P2P apps</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Multiplayer games that discover players by using multicast</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="146">
          <p align="left"></p>

          <p align="left">Private Networks (Client &amp; Server)</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="273">
          <p align="left"></p>

          <p align="left">Provides inbound and outbound network access at private locations trusted by the user. These are usually home or work networks. Inbound access to critical ports are always blocked.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="191">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left">Apps that access network attached storage (NAS) content</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Line-of-business apps</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Multiplayer games that discover players by using multicast on a private (home or work) network</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="146">
          <p align="left"></p>

          <p align="left">Proximity</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="273">
          <p align="left"></p>

          <p align="left">Required for near-field proximity communication with devices. Allows apps to access the network to connect to a device in close proximity, with user consent to send or accept an invitation.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="191">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left">Multiplayer games with people in close proximity<i></i></div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="146">
          <p align="left"></p>

          <p align="left">Enterprise Authentication</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="273">
          <p align="left"></p>

          <p align="left">Provides the capability to connect to enterprise intranet resources that require domain credentials.</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="191">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left">Line-of-business apps</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="146">
          <p align="left"></p>

          <p align="left">Shared User Certificates</p>

          <p align="left"></p>
        </td>

        <td valign="top" width="273">
          <p align="left"></p>

          <p align="left">Provides the capability to access software and hardware certificates, such as smart card certificates, for validating a user's identity. When related APIs are invoked at run time, the user must take action (such as inserting a card or selecting a certificate). </p>

          <p align="left"></p>
        </td>

        <td valign="top" width="191">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left">Virtual private network apps</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">Line-of-business apps</div>
            </li>
          </ul>
        </td>
      </tr>
    </tbody></table>
</div>

<p>Use this checklist to make sure network isolation is configured in your app:</p>

<ul>
  <li>Determine the direction of network access that your app needs; outbound client-initiated requests, inbound unsolicited requests, or both.</li>

  <li>Determine the type of network resources that your app will communicate with: trusted resources on a home or work network, resources on the Internet, or both. </li>

  <li>Configure the minimum required network isolation capabilities in the app manifest. You can do this using the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br230259.aspx" target="_blank">App Manifest Designer</a> in Microsoft Visual Studio 2012, or <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211477.aspx" target="_blank">add them manually</a>.</li>

  <li>Deploy and run your app to test it using the network isolation tools provided for troubleshooting. For more information, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh780593.aspx" target="_blank">How to enable loopback and troubleshoot network isolation</a>.</li>
</ul>

<p>The following screen shot shows how to enable network capabilities using the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br230259.aspx" target="_blank">App Manifest Designer</a> in Microsoft Visual Studio 2012.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/7268.app-manifest-design_47107BBF.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/7268.app_2D00_manifest_2D00_design_5F00_47107BBF.png"><img title="Select network capabilities in your app’s package.appxmanifest in Visual Studio 2012" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="Select network capabilities in your app’s package.appxmanifest in Visual Studio 2012" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/7752.app-manifest-design_thumb_5EC7B325.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/7752.app_2D00_manifest_2D00_design_5F00_thumb_5F00_5EC7B325.png" width="600" height="318" /></a></p>

<p align="center"><em>Select network capabilities in your app’s package.appxmanifest in Visual Studio 2012</em></p>

<h2>Adapt app behavior for metered networks</h2>

<p>Think about the last time you were approaching your monthly data cap or perhaps travelled abroad. In these situations I typically ended up using my device and apps cautiously to prevent any unnecessary network charges. </p>

<p>Windows 8 addresses this user problem by allowing apps to monitor available network resources and behave accordingly when on metered networks. To promote user confidence in your apps, you can make it able to tell when a connection may incur costs and then adapt its behavior to avoid or reduce charges.</p>

<p>The <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.aspx" target="_blank">Windows.Networking.Connectivity</a> API provides info about the type and cost of a network connection. This allows your app to determine when it makes sense to use network resources normally, use them conservatively, or ask the user. </p>

<p>A <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectionprofile.aspx" target="_blank">ConnectionProfile</a> represents a network connection. Your app can use the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.aspx" target="_blank">ConnectionCost</a> of a <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectionprofile.aspx" target="_blank">ConnectionProfile</a> to determine whether to adapt its behavior. The <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.networkcosttype.aspx" target="_blank">NetworkCostType</a> property indicates the type of a network connection. There are four possible values:</p>

<ul>
  <li><b>Unrestricted</b>—Use of this network connection is unlimited. It has no usage charges or capacity constraints.</li>

  <li><b>Fixed</b>—Use of this network connection is unrestricted up to a specific limit.</li>

  <li><b>Variable</b>—Use of this network connection is metered on a per-byte basis.</li>

  <li><b>Unknown</b>—Cost information is not available for this network connection.</li>
</ul>

<p>Several other Boolean properties for the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.aspx" target="_blank">ConnectionCost</a> provide still more info. </p>

<ul>
  <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.roaming.aspx" target="_blank">Roaming</a>—The connection is to a network outside of the home provider.</li>

  <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.approachingdatalimit.aspx" target="_blank">ApproachingDataLimit</a>—The connection is approaching the usage allowance specified by the data plan.</li>

  <li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.overdatalimit.aspx" target="_blank">OverDataLimit</a>—The connection has exceeded the usage allowance specified by the data plan.</li>
</ul>

<p>Have your app respond to the conditions indicated by these properties. Whenever a connection is <b>Roaming</b>, the data costs associated with network usage could be high. When the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.networkcosttype.aspx" target="_blank">NetworkCostType</a> is <b>Variable</b>, the network is a metered network, where the user pays for the amount of data sent or received on the network. When the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.networkcosttype.aspx" target="_blank">NetworkCostType</a> is <b>Fixed</b>, there’s cause for concern if the user is already over the data limit or approaching it. </p>

<p>By using this information, an app can follow these guidelines to decide how best to use network resources.</p>

<div align="center">
  <table class="b8table" cellspacing="0" cellpadding="3" align="center" border="0"><tbody>
      <tr>
        <td valign="top" width="97">
          <p><b>Behavior</b></p>
        </td>

        <td valign="top" width="150">
          <p><b>Connection cost</b></p>
        </td>

        <td valign="top" width="168">
          <p><b>App guidelines</b></p>
        </td>

        <td valign="top" width="175">
          <p><b>Examples</b></p>
        </td>
      </tr>

      <tr>
        <td valign="top" width="97">
          <p align="left">Normal</p>

          <p align="left"></p>
        </td>

        <p align="left"></p>

        <td valign="top" width="150">
          <p align="left"></p>

          <p align="left"><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.networkcosttype.aspx" target="_blank">NetworkCostType</a> is <b>Unrestricted</b> or <b>Unknown</b> and <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.aspx" target="_blank">ConnectionCost</a> is not <b>Roaming</b></p>

          <p align="left"></p>
        </td>

        <p align="left"></p>

        <td valign="top" width="168">
          <p align="left"></p>

          <p align="left">App does not implement restrictions. App treats the connection as <b>Unlimited</b> in cost, and unrestricted by usage charges and capacity constraints.</p>

          <p align="left"></p>
        </td>

        <p align="left"></p>

        <td valign="top" width="175">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left">Media player app can play an entire HD movie.</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">App can download large file without any restrictions or prompts.</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>

        <p align="left"></p>
      </tr>

      <p align="left"></p>

      <tr>
        <p align="left"></p>

        <td valign="top" width="97">
          <p align="left"></p>

          <p align="left">Conservative</p>

          <p align="left"></p>
        </td>

        <p align="left"></p>

        <td valign="top" width="150">
          <p align="left"></p>

          <p align="left"><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.networkcosttype.aspx" target="_blank">NetworkCostType</a> is <b>Fixed</b> or <b>Variable</b> and <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.aspx" target="_blank">ConnectionCost</a> is not <b>Roaming</b> or <b>OverDataLimit</b></p>

          <p align="left"></p>
        </td>

        <p align="left"></p>

        <td valign="top" width="168">
          <p align="left"></p>

          <p align="left">App implements restrictions for optimizing network usage to handle operations on metered networks.</p>

          <p align="left"></p>
        </td>

        <p align="left"></p>

        <td valign="top" width="175">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left">Media player app can play movies in lower resolutions.</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">App can delay non-critical downloads.</div>
            </li>

            <p align="left"></p>
          </ul>

          <p align="left"></p>
        </td>

        <p align="left"></p>
      </tr>

      <p align="left"></p>

      <tr>
        <p align="left"></p>

        <td valign="top" width="97">
          <p align="left"></p>

          <p align="left">Opt-In</p>

          <p align="left"></p>
        </td>

        <p align="left"></p>

        <td valign="top" width="150">
          <p align="left"></p>

          <p align="left"><a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.aspx" target="_blank">ConnectionCost</a> is <b>Roaming</b> or <b>OverDataLimit</b></p>

          <p align="left"></p>
        </td>

        <p align="left"></p>

        <td valign="top" width="168">
          <p align="left"></p>

          <p align="left">App handles exceptional cases where the network access cost is substantially higher than plan cost.</p>

          <p align="left"></p>
        </td>

        <p align="left"></p>

        <td valign="top" width="175">
          <p align="left"></p>

          <ul>
            <p align="left"></p>

            <li>
              <div align="left">App prompts user to access the network.</div>
            </li>

            <p align="left"></p>

            <li>
              <div align="left">App suspends all background data network activities.<i></i></div>
            </li>
          </ul>
        </td>
      </tr>
    </tbody></table>
</div>

<p>This code example checks the connection cost and returns suggestions for appropriate app behavior. </p>

<p><strong>JavaScript</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> CostGuidance = { Normal: 0, Conservative: 1, OptIn: 2 };<br /><span style="color: rgb(0, 128, 0);">// GetCostGuidance returns an object with a Cost (with value of CostGuidance), </span><br /><span style="color: rgb(0, 128, 0);">// CostName (a string) and Reason, which says why the cost is what it is.</span><br /><span style="color: rgb(0, 0, 255);">function</span> GetCostGuidance() <br />{<br />    <span style="color: rgb(0, 0, 255);">var</span> connectionCost = Windows.Networking.Connectivity.NetworkInformation.getInternetConnectionProfile().getConnectionCost();<br />    <span style="color: rgb(0, 0, 255);">var</span> networkCostConstants = Windows.Networking.Connectivity.NetworkCostType;<br />    <span style="color: rgb(0, 0, 255);">var</span> Retval = <span style="color: rgb(0, 0, 255);">new</span> Object();<br />    <span style="color: rgb(0, 0, 255);">if</span> (connectionCost.roaming || connectionCost.overDataLimit)<br />    {<br />        Retval.Cost = CostGuidance.OptIn;<br />        Retval.CostName = <span style="color: rgb(0, 96, 128);">&quot;OptIn&quot;</span>;<br />        Retval.Reason = connectionCost.roaming<br />            ? <span style="color: rgb(0, 96, 128);">&quot;Connection is roaming; using the connection may result in additional charge.&quot;</span><br />            : <span style="color: rgb(0, 96, 128);">&quot;Connection has exceeded the usage cap limit.&quot;</span>;<br />    }<br />    <span style="color: rgb(0, 0, 255);">else</span> <span style="color: rgb(0, 0, 255);">if</span> (connectionCost.networkCostType == networkCostConstants.<span style="color: rgb(0, 0, 255);">fixed</span><br />        || connectionCost.networkCostType == networkCostConstants.variable)<br />    {<br />        Retval.Cost = CostGuidance.conservative;<br />        Retval.CostName = <span style="color: rgb(0, 96, 128);">&quot;Conservative&quot;</span>;<br />        Retval.Reason = connectionCost.networkCostType == NetworkCostType.<span style="color: rgb(0, 0, 255);">fixed</span><br />            ? <span style="color: rgb(0, 96, 128);">&quot;Connection has limited allowed usage.&quot;</span><br />            : <span style="color: rgb(0, 96, 128);">&quot;Connection is charged based on usage. &quot;</span>;<br />    }<br />    <span style="color: rgb(0, 0, 255);">else</span><br />    {<br />        Retval.Cost = CostGuidance.Normal;<br />        Retval.CostName = <span style="color: rgb(0, 96, 128);">&quot;Normal&quot;</span>;<br />        Retval.Reason = connectionCost.networkCostType == networkCostConstants.unknown<br />            ? <span style="color: rgb(0, 96, 128);">&quot;Connection is unknown.&quot;</span><br />            : <span style="color: rgb(0, 96, 128);">&quot;Connection cost is unrestricted.&quot;</span>;<br />    }<br /><br />    <span style="color: rgb(0, 0, 255);">return</span> Retval;<br />}<br /></pre>
  </div>
</blockquote>

<p><strong>C#</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">public</span> <span style="color: rgb(0, 0, 255);">enum</span> NetworkCost { Normal, Conservative, OptIn };<br /><span style="color: rgb(0, 0, 255);">public</span> <span style="color: rgb(0, 0, 255);">class</span> CostGuidance<br />{<br />    <span style="color: rgb(0, 0, 255);">public</span> CostGuidance()<br />    {<br />        var connectionCost = NetworkInformation.GetInternetConnectionProfile().GetConnectionCost();<br />        Init(connectionCost);<br />    }<br />    <span style="color: rgb(0, 0, 255);">public</span> NetworkCost Cost { get; <span style="color: rgb(0, 0, 255);">private</span> set; }<br />    <span style="color: rgb(0, 0, 255);">public</span> String Reason { get; <span style="color: rgb(0, 0, 255);">private</span> set; }<br /><br /><br />    <span style="color: rgb(0, 0, 255);">public</span> <span style="color: rgb(0, 0, 255);">void</span> Init(ConnectionCost connectionCost)<br />    {<br />        <span style="color: rgb(0, 0, 255);">if</span> (connectionCost == <span style="color: rgb(0, 0, 255);">null</span>) <span style="color: rgb(0, 0, 255);">return</span>;<br />        <span style="color: rgb(0, 0, 255);">if</span> (connectionCost.Roaming || connectionCost.OverDataLimit)<br />        {<br />            Cost = NetworkCost.OptIn;<br />            Reason = connectionCost.Roaming<br />                ? <span style="color: rgb(0, 96, 128);">&quot;Connection is roaming; using the connection may result in additional charge.&quot;</span><br />                : <span style="color: rgb(0, 96, 128);">&quot;Connection has exceeded the usage cap limit.&quot;</span>;<br />        }<br />        <span style="color: rgb(0, 0, 255);">else</span> <span style="color: rgb(0, 0, 255);">if</span> (connectionCost.NetworkCostType == NetworkCostType.Fixed<br />            || connectionCost.NetworkCostType == NetworkCostType.Variable)<br />        {<br />            Cost = NetworkCost.Conservative;<br />            Reason = connectionCost.NetworkCostType == NetworkCostType.Fixed<br />                ? <span style="color: rgb(0, 96, 128);">&quot;Connection has limited allowed usage.&quot;</span><br />                : <span style="color: rgb(0, 96, 128);">&quot;Connection is charged based on usage. &quot;</span>;<br />        }<br />        <span style="color: rgb(0, 0, 255);">else</span><br />        {<br />            Cost = NetworkCost.Normal;<br />            Reason = connectionCost.NetworkCostType == NetworkCostType.Unknown<br />                ? <span style="color: rgb(0, 96, 128);">&quot;Connection is unknown.&quot;</span><br />                : <span style="color: rgb(0, 96, 128);">&quot;Connection cost is unrestricted.&quot;</span>;<br />        }<br />    }<br />}<br /></pre>

    <br /></div>
</blockquote>

<p>Use the <a href="http://code.msdn.microsoft.com/windowsapps/Network-Information-Sample-63aaa201" target="_blank">network information sample</a> to learn more about adapting app behavior for metered networks.</p>

<p>Users can also run Task Manager to see the amount of network data that each app is consuming. This screen shot shows an example.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/5618.task-manager_6C99F920.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/5618.task_2D00_manager_5F00_6C99F920.png"><img title="App History tab in Task Manager allows users to see CPU and network consumption by apps" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="App History tab in Task Manager allows users to see CPU and network consumption by apps" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/51/31/metablogapi/3554.task-manager_thumb_4C7EEC63.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-51-31-metablogapi/3554.task_2D00_manager_5F00_thumb_5F00_4C7EEC63.png" width="600" height="545" /></a></p>

<p align="center"><em>App History tab in Task Manager allows users to see CPU and network consumption by apps</em></p>

<h2>React to network status changes</h2>

<p>In any mobile device scenario, networks can come and go. A mobile 3G or 4G broadband network could go out of range within a user’s home or garage while Wi-Fi is still available. Similarly, Wi-Fi may go out of range when a user leaves home. There may also be times when no network is available. Given the proliferation of Wi-Fi and mobile broadband networks, such network changes occur frequently. </p>

<p>A <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkinformation.networkstatuschanged" target="_blank">NetworkStatusChanged</a> event indicates that the <i>available cost</i> or <i>connectivity options</i> may have changed. To react to network status changes and provide a seamless customer experience when a change occurs, have your connected apps follow these scenario guidelines.</p>

<h3>Connection loss due to error</h3>

<p>In most cases, connections can be reestablished by simply retrying the network operation. If this fails, then wait for a <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkinformation.networkstatuschanged" target="_blank">NetworkStatusChanged</a> event. We recommend that apps use an increasing backoff interval between retries, starting with a value of 50 milliseconds and increasing this backoff interval exponentially if connections continue to fail.</p>

<h3>Loss of network</h3>

<p>Inform the user that the connection has been lost, then register and wait for a <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkinformation.networkstatuschanged" target="_blank">NetworkStatusChanged</a> event.</p>

<h3>New network availability</h3>

<p>There may be cases where the device is connected to multiple networks. For example, a user may be connected to mobile broadband and chatting with friends using the Windows 8 Messaging app before arriving at home and connecting to the unrestricted network there as well. The default policy in Windows 8 is to prefer an unrestricted network over a metered network, and a faster network over a slower network. However, existing connections established by an app do not automatically switch over to a new network. The app must get involved because only the app can make the best decision whether or not to switch to the new network. </p>

<p>For example, if a video stream is close to completion, it may not make sense to switch to the new network. However, if the current network is dropping packets, is too slow, or the stream will take additional time to complete, switching to the new network may be best.</p>

<p>If you determine that switching networks is plausible for your app scenario, follow these guidelines when you detect a new network:</p>

<ol>
  <li>Check the network costs of the existing and new network. If it makes sense to switch to the new network, try making a new network connection and retry the network operation based on the guidelines just mentioned. Windows automatically selects the unrestricted network over the metered network, and the faster network over the slower one if available.</li>

  <li>If the new network connection succeeds, use the new network connection in your app and cancel the original network operation on the previous network if the connection already exists.</li>
</ol>

<h3>Change in network cost</h3>

<p>A change in network cost can occur when the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.networkcosttype.aspx" target="_blank">NetworkCostType</a> is <b>Fixed</b> and usage is approaching the data limit or goes over the data limit. A change in network cost can also result if the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.networkcosttype.aspx" target="_blank">NetworkCostType</a> becomes <b>Variable</b>, or if <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.connectioncost.roaming.aspx" target="_blank">Roaming</a> changes to true. In these cases, adapt app behavior based on the guidelines in the preceding tip.</p>

<p>These code examples use the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkinformation.networkstatuschanged" target="_blank">NetworkStatusChanged</a> event to provide a seamless app experience for various network status changes. Both examples use a global Boolean variable called <i>registeredNetworkStatusNotification,</i> initially set to <b>false</b>. </p>

<p><strong>JavaScript</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 128, 0);">// Register for NetworkStatusChanged notifications, and display new </span><br /><span style="color: rgb(0, 128, 0);">// Internet ConnectionProfile info upon network status change.</span><br /><span style="color: rgb(0, 0, 255);">function</span> registerForNetworkStatusChange() {<br />    <span style="color: rgb(0, 0, 255);">try</span> {<br /><br />        <span style="color: rgb(0, 128, 0);">// Register for network status change notifications.</span><br />        <span style="color: rgb(0, 0, 255);">if</span> (!registeredNetworkStatusNotification) {<br />            <span style="color: rgb(0, 0, 255);">var</span> networkInfo.addEventListener(<span style="color: rgb(0, 96, 128);">&quot;networkstatuschanged&quot;</span>, onNetworkStatusChange);<br />            registeredNetworkStatusNotification = <span style="color: rgb(0, 0, 255);">true</span>;<br />        }<br />    }<br />    <span style="color: rgb(0, 0, 255);">catch</span> (e) {<br />        print(<span style="color: rgb(0, 96, 128);">&quot;An unexpected exception occurred: &quot;</span> + e.name + <span style="color: rgb(0, 96, 128);">&quot;: &quot;</span> + e.message);<br />    }<br />}<br /><br /><span style="color: rgb(0, 128, 0);">// Event handler for NetworkStatusChanged event</span><br /><span style="color: rgb(0, 0, 255);">function</span> onNetworkStatusChange(sender) {<br />    <span style="color: rgb(0, 0, 255);">try</span> {<br />        <span style="color: rgb(0, 128, 0);">// Get the ConnectionProfile that is currently used to connect </span><br />        <span style="color: rgb(0, 128, 0);">// to the Internet.</span><br />        <span style="color: rgb(0, 0, 255);">var</span> internetProfile = networkInfo.getInternetConnectionProfile();<br />        <span style="color: rgb(0, 0, 255);">if</span> (internetProfile === <span style="color: rgb(0, 0, 255);">null</span>) {<br />            print(<span style="color: rgb(0, 96, 128);">&quot;Not connected to Internet\n\r&quot;</span>);<br />        }<br />        <span style="color: rgb(0, 0, 255);">else</span> {<br />            internetProfileInfo += getConnectionProfileInfo(internetProfile) + <span style="color: rgb(0, 96, 128);">&quot;\n\r&quot;</span>;<br />            print(internetProfileInfo);<br />        }<br />        internetProfileInfo = <span style="color: rgb(0, 96, 128);">&quot;&quot;</span>;<br />    }<br />    <span style="color: rgb(0, 0, 255);">catch</span> (e) {<br />        print(<span style="color: rgb(0, 96, 128);">&quot;An unexpected exception occurred: &quot;</span> + e.name + <span style="color: rgb(0, 96, 128);">&quot;: &quot;</span> + e.message);<br />    }<br />}<br /></pre>

    <br /></div>
</blockquote>

<p><strong>C#</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 128, 0);">// Register for NetworkStatusChanged notifications, and display new </span><br /><span style="color: rgb(0, 128, 0);">// Internet ConnectionProfile info upon network status change.</span><br /><span style="color: rgb(0, 0, 255);">void</span> NetworkStatusChange()<br />{<br />    <span style="color: rgb(0, 128, 0);">// Register for network status change notifications.</span><br />    <span style="color: rgb(0, 0, 255);">try</span><br />    {<br />        var networkStatusCallback = <span style="color: rgb(0, 0, 255);">new</span> NetworkStatusChangedEventHandler(OnNetworkStatusChange);<br />        <span style="color: rgb(0, 0, 255);">if</span> (!registeredNetworkStatusNotification)<br />        {<br />            NetworkInformation.NetworkStatusChanged += networkStatusCallback;<br />            registeredNetworkStatusNotification = <span style="color: rgb(0, 0, 255);">true</span>;<br />        }<br />    }<br />    <span style="color: rgb(0, 0, 255);">catch</span> (Exception ex)<br />    {<br />        rootPage.NotifyUser(<span style="color: rgb(0, 96, 128);">&quot;Unexpected exception occurred: &quot;</span> + ex.ToString(), NotifyType.ErrorMessage);<br />    }<br />}<br /><br /><span style="color: rgb(0, 128, 0);">// Event handler for NetworkStatusChanged event</span><br />async <span style="color: rgb(0, 0, 255);">void</span> OnNetworkStatusChange(<span style="color: rgb(0, 0, 255);">object</span> sender)<br />{<br />    <span style="color: rgb(0, 0, 255);">try</span><br />    {<br />        <span style="color: rgb(0, 128, 0);">// Get the ConnectionProfile that is currently used to connect </span><br />        <span style="color: rgb(0, 128, 0);">// to the Internet                </span><br />        ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();<br /><br />        <span style="color: rgb(0, 0, 255);">if</span> (InternetConnectionProfile == <span style="color: rgb(0, 0, 255);">null</span>)<br />        {<br />            await _cd.RunAsync(CoreDispatcherPriority.Normal, () =&gt;<br />            {<br />                rootPage.NotifyUser(<span style="color: rgb(0, 96, 128);">&quot;Not connected to Internet\n&quot;</span>, NotifyType.StatusMessage);<br />            });<br />        }<br />        <span style="color: rgb(0, 0, 255);">else</span><br />        {<br />            connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile);<br />            await _cd.RunAsync(CoreDispatcherPriority.Normal, () =&gt;<br />            {<br />                rootPage.NotifyUser(connectionProfileInfo, NotifyType.StatusMessage);<br />            });<br />        }<br />        internetProfileInfo = <span style="color: rgb(0, 96, 128);">&quot;&quot;</span>;<br />    }<br />    <span style="color: rgb(0, 0, 255);">catch</span> (Exception ex)<br />    {<br />        rootPage.NotifyUser(<span style="color: rgb(0, 96, 128);">&quot;Unexpected exception occurred: &quot;</span> + ex.ToString(), NotifyType.ErrorMessage);<br />    }<br />}<br /></pre>
  </div>
</blockquote>

<p>To learn more about the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkinformation.networkstatuschanged" target="_blank">NetworkStatusChanged</a> event, see <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700376.aspx" target="_blank">Quickstart: Managing connection events and changes in availability</a> and the <a href="http://code.msdn.microsoft.com/windowsapps/Network-Information-Sample-63aaa201" target="_blank">Network information sample</a>.</p>

<h2>Cache content for fluidity</h2>

<p>Caching content to disk lets your app behave fast and fluidly. For example, an RSS feed reader app can immediately display feeds that were cached to disk from a previous session. As soon as the latest feeds are available, the app updates its content. Caching ensures that the user has content to read immediately upon launch while the app gets new content.</p>

<p>Windows 8 provides the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdata.aspx" target="_blank">ApplicationData</a><b></b> class in the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.aspx" target="_blank">Windows.Storage</a><b></b> namespace. This class provides access to the app data store. This data store consists of files and settings that are local to the device, roam across multiple devices, or are temporary.</p>

<p>Files are ideal for storing large data sets, databases, or data that is in a common file format. Files can exist in the Roaming, Local, or Temporary folders. Here’s what that means:</p>

<ul>
  <li>Roaming files are synchronized across multiple machines and devices where users have signed in with connected accounts. Roaming of files is not instant; the system weighs several factors to determine when to send the data. Keep the use of roaming data below the quota (available via the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdata.roamingstoragequota.aspx" target="_blank">RoamingStorageQuota</a><b></b> property); if the quota is exceeded, roaming of data will be suspended. Files cannot be roamed while an app is writing to them, so be sure to close your app’s file objects when they are no longer needed. </li>

  <li>Local files are not synchronized across machines. They remain on the machine on which they were originally written. </li>

  <li>Temporary files are subject to deletion when not in use. The system considers factors such as available disk capacity and the age of a file in determining when or whether to delete a temporary file.</li>
</ul>

<p>These code examples cache content to disk. Caching the server response allows your app to immediately display content to the user after a termination and relaunch. For brevity, these examples don’t show how to write settings to the app data store or how to respond to roaming events. The <a href="http://code.msdn.microsoft.com/windowsapps/ApplicationData-sample-fb043eb2" target="_blank">Application data sample</a> covers those details.</p>

<p><strong>JavaScript</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);"><span style="color: rgb(0, 0, 255);">var</span> roamingFolder = Windows.Storage.ApplicationData.current.roamingFolder;<br /><span style="color: rgb(0, 0, 255);">var</span> filename = <span style="color: rgb(0, 96, 128);">&quot;serverResponse.txt&quot;</span>;<br /><br /><span style="color: rgb(0, 0, 255);">function</span> cacheResponse(strResponse) {<br />    roamingFolder.createFileAsync(filename, Windows.Storage.CreationCollisionOption.replaceExisting)<br />        .done(<span style="color: rgb(0, 0, 255);">function</span> (file) {<br />            <span style="color: rgb(0, 0, 255);">return</span> Windows.Storage.FileIO.writeTextAsync(file, strResponse);<br />        });<br />}<br /><br /><span style="color: rgb(0, 0, 255);">function</span> getCachedResponse() {<br />    roamingFolder.getFileAsync(filename)<br />        .then(<span style="color: rgb(0, 0, 255);">function</span> (file) {<br />            <span style="color: rgb(0, 0, 255);">return</span> Windows.Storage.FileIO.readTextAsync(file);<br />        }).done(<span style="color: rgb(0, 0, 255);">function</span> (response) {<br />            print(response);<br />        }, <span style="color: rgb(0, 0, 255);">function</span> () {<br />            <span style="color: rgb(0, 128, 0);">// getFileAsync or readTextAsync failed. </span><br />            <span style="color: rgb(0, 128, 0);">// No cached response.</span><br />        });<br />}<br /></pre>

    <br /></div>
</blockquote>

<p><strong>C#</strong></p>

<blockquote>
  <div id="codeSnippetWrapper">
    <pre id="codeSnippet" style="margin: 0em; padding: 0px; width: 100%; text-align: left; color: black; line-height: 12pt; overflow: visible; font-family: &quot;Courier New&quot;, courier, monospace; font-size: 8pt; direction: ltr; background-color: rgb(244, 244, 244);">MainPage rootPage = MainPage.Current;<br />StorageFolder roamingFolder = <span style="color: rgb(0, 0, 255);">null</span>;<br /><span style="color: rgb(0, 0, 255);">const</span> <span style="color: rgb(0, 0, 255);">string</span> filename = <span style="color: rgb(0, 96, 128);">&quot;serverResponse.txt&quot;</span>;<br /><br />async <span style="color: rgb(0, 0, 255);">void</span> cacheResponse(<span style="color: rgb(0, 0, 255);">string</span> strResponse)<br />{<br />    StorageFile file = await roamingFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);<br />    await FileIO.WriteTextAsync(file, strResponse);<br />}<br /><br />async <span style="color: rgb(0, 0, 255);">void</span> getCachedResponse()<br />{<br />    <span style="color: rgb(0, 0, 255);">try</span><br />    {<br />        StorageFile file = await roamingFolder.GetFileAsync(filename);<br />        <span style="color: rgb(0, 0, 255);">string</span> response = await FileIO.ReadTextAsync(file);<br />    }<br />    <span style="color: rgb(0, 0, 255);">catch</span> (Exception)<br />    {<br />        <span style="color: rgb(0, 128, 0);">// getFileAsync or readTextAsync failed.</span><br />        <span style="color: rgb(0, 128, 0);">// No cached response.</span><br />    }<br />}<br /></pre>

    <br /></div>
</blockquote>

<p>For more info about the app data store, see the <a href="http://blogs.msdn.com/b/windowsappdev/archive/2012/07/17/roaming-your-app-data.aspx" target="_blank">roaming your app data</a> post and try out the <a href="http://code.msdn.microsoft.com/windowsapps/ApplicationData-sample-fb043eb2" target="_blank">Application data sample</a>.</p>

<h2>Wrapping it up</h2>

<p>When planning your Windows Store apps, use the guidelines in this post to provide a great, hassle-free, connected experience. These tips can make your development process easier, while maintaining fluidity and boosting user confidence in your apps.</p>

<p>- Suhail Khalid, Program Manager II, Windows</p>

<p>Contributions by: Steven Baker and Peter Smith</p>]]></content:encoded>
    </item>
  </channel>
</rss>