A question on the MSDN JavaScript apps forum recently asked why the app data APIs were in Windows.Storage.ApplicationData whereas the app's package folder property is off in Windows.ApplicationModel.Package. I responded with the following comments, which Howard Kapustein confirmed (he did much of this wrangling early on).

I don't know the exact history (this would've been taking place in early 2011) but I imagine it could've gone either way and someone eventually had to make a decision. Generally speaking, Windows.ApplicationModel has package information along with a bunch of APIs that deal with app-to-app communication, contracts, activation, suspend/resume, and background tasks. Windows.Storage, on the other hand, has everything to do with the file system.

Because appdata folders are probably more closely aligned with the file system than with the "app model" stuff, I can see why Windows.Storage was the landing place. After all, that's where you find all the other file I/O APIs, and I can imagine that if the ApplicationData APIs were in Windows.ApplicationModel, we'd be having the same question about why they weren't in Windows.Storage. :)

I would guess that there was probably an argument for putting the package information classes into Windows.Management.Deployment, which is probably it's most natural home. However, the rest of the APIs there are desktop-only and not accessible to Store apps, so it made some sense to put the Package class elsewhere. I expect this decision was probably made well after the decision to put ApplicationData into Windows.Storage.

It's also worth noting that the appdata folders are not technically part of the package, so it's really the installedLocation property that's the aberration. The rest of the Package and PackageId properties come from the Store and describes the package characteristics more than runtime state. Thus installedLocation just so happens to be the link between all the package info and the file system.

In the end, I think the structure that we have actually makes the most sense, because when you start talking about appdata you automatically end up in Windows.Storage.

Knowing the guys in API naming team that bandied all this kind of stuff about (guys like Harry Pierson, Jason Olson, and Brent Rector–and now I can add Howard Kapustein as well), I expect that they discussed all these pros and cons before making a decision. Howard describes it as "sausage making" if you want a great visual image!


I've seen this question come up twice lately, once via email and again on StackOverflow. The questions are something like this:

My app has strange behavior with its template bindings with WinJS. When I navigate to a page and then back, everything is fine, but if I navigate to the same page then the bindings get all jumbled and I see only the raw JSON.

I have an app written in JavaScript whose app bar commands navigate to different pages, including the page that's currently loaded. Navigating between different pages works fine, but navigating to the same page (essentially reloading it) loses event handlers on my buttons.

In short, strange things seem to happen when navigating (with WinJS.Navigation.navigate) to the same page that's already loaded. Here's what's happening.

Page navigation in WinJS is just a matter of DOM replacement. When you navigate using the navigator.js file that's part of the Visual Studio templates, the target “page” contents are loaded into the DOM and then the previous “page’s” contents are unloaded. You can see this in navigator.js in the _navigating method. It creates a new element for the page being loaded, renders that fragment therein, and then unloads the old page.

The ready method for the new page, however, is called before the old page is unloaded (this was a change in WinJS 2.0, as WinJS 1.0 unloaded the old page before calling ready). The upshot of this is that when you navigate to the same page that’s already loaded, page.html(A) is in the DOM when you load page.html(B).

As a result, anything you attempt to do in the DOM during the processed or ready methods, which includes adding event listeners or attaching templates, will find the elements in page.html(A) and not page.html(B). That is, when getElementById traverses the DOM it finds elements in (A) first and stops there; locating templates works in the same way, so any data bindings that include templates will get hooked up to the templates in (A).

But then, of course, as soon as you return from the ready method, page.html(A) gets unloaded, so all your hard work is thrown away!

Again, this is a behavior that appears when navigating to the same page that's already loaded, so the solution is to avoid navigating to the same page because it's just fraught with peril. In some cases you can disable the navigation controls in your UI so you can't navigate to the current page. However, that's not always easy to do, so here's a way to wrap your call to WinJS.Navigation.navigate with a check for whether you're already on the target page:

function navigateIfDifferent(target) {
    var page = document.getElementById("contenthost").winControl.pageControl;
    var fullTarget = "ms-appx://" + Windows.ApplicationModel.Package.current.id.name + target;
    if (fullTarget !== page.uri) {
        WinJS.Navigation.navigate(target);
    }
}

This assumes that the PageControlNavigator control that you're using is in a div called "contenthost" in default.html (which is what the VS template gives you). What I'm then doing is building the full in-package URI for the target page and comparing that to the uri of the current page control, which is also a full in-package URI. You could also strip off the ms-appx:// part from the current page URI and compare to the target URI. Either way–you can then replace calls to WinJS.Navigation.navigate with navigateIfDifferent.

On the flip side, there are likely some scenarios where you specifically want to reload or refresh the current page, so a self-navigation seems like a way to do this. It should be fairly obvious, though, that any page initialization you do in ready or processed can be moved into separate methods that you call elsewhere to refresh the page. Remember too that you can call WinJS.Binding.processAll at any time in your code to refresh the data binding–it's not specific to page loading or other initialization procedures.

I'd recommend this as the first choice, because it won't mess with everything else that's been set up in the DOM already, and should perform better than reloading everything. 

However, if you still want to navigate to the same page to reload, then you need to defer the processing you'd normally do in ready to a later time. You could use a call to setImmediate for this purpose (it should work–I haven't tried it directly), but a simpler means (thanks to Guillaume Leborgne) is to make sure you scope any element queries or selections using the page's root element that's passed as the element argument to the ready method. Using this as the starting point, you'll restrict the scope to the newly-loaded page rather than the whole document.

And as a final note, you can always go to the lower-level WinJS.UI.fragments API to do your own page-loading implementation.


I've been rather quiet on the blogging front lately, but not for lack of activity! For one, I'm the full owner of the technical posts that go up on Microsoft's dev blogs for Windows, http://blogs.windows.com/windows/b/buildingapps/, which merged together the Windows and Windows Phone dev blogs back in early April. Call me the developmental editor for just about anything posted under the "Windows Apps Team" byline.

But no excuse for personal blogging! These last few weeks I haven't wanted to add anything to my blog here because I've been migrating my site from godaddy.com (where the hosting cost went up and it's hard to find discounts now) to Microsoft Azure, where my Windows Store account gives me $150/month credit! (I believe you all are enjoying that too.) The trick was to migrate and merge my old ASP.NET site content with my WordPress blog content, which also meant redirecting the blog from a /blog subfolder to the root while getting the .aspx pages to redirect properly, especially Pages.aspx, which did a database lookup for articles and such that are now WordPress pages.

If you see some bad links or broken images in any posts here, let me know (kraig(at)kraigbrockschmidt.com). I'm doing a scrub but might miss something.

One issue that I ran into was rather interesting. With WordPress I wanted to switch from default permalinks using /?p=<post ID> URIs to "pretty name" URIs with dates and such (better for SEO). At the same time I wanted to make sure that /blog/<name> got redirected to just <name> give that I pulled WordPress into the site root.

Should have been easy with an Azure virtual directory, yes? At first, that seemed to work just fine–I added an entry on the Azure web site Configure page for /blog to go to sitewwwroot. I tested it, and it was good.

But when I changed the WordPress permalinks, I started getting either HTTP 404 errors or HTTP 500 errors when using /blog. What gives?

It boiled down to the fact that WordPress was interpreting /blog as part of a pretty name and therefore trying to do a post or page lookup, and not finding one would generate a 404. The 500 errors showed up when I had some Rewrite rules in web.config (that WordPress included for pretty permalinks), which seemed to generate confusion between the permalink system and Azure's virtual directory checking.

In the end, the solution was to insert a special redirect rule in web.config for "blog" specifically, so it'd get processed first and bypass the permalink system entirely. Here's what my web.config looks like:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <customErrors mode="Off"/>
  </system.web>
  <system.webServer>
    <staticContent>
      <remove fileExtension=".svg"/>
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml"/>
    </staticContent>

    <rewrite>
      <rules>
        <rule stopProcessing="true" name="Blog Rule">
          <match url="blog"/>
          <action url="index.php" redirectType="Permanent" type="Redirect"/>
        </rule>
        <rule name="wordpress" patternSyntax="Wildcard">
          <match url="*"/>
          <conditions>
            <add negate="true" matchType="IsFile" input="{REQUEST_FILENAME}"/>
            <add negate="true" matchType="IsDirectory" input="{REQUEST_FILENAME}"/>
          </conditions>
          <action url="index.php" type="Rewrite"/>
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

 

Hopefully this helps others who run into the same thing every now and then!


With the introduction of universal Windows apps at //build 2014, and the announcement of Windows Phone 8.1 that includes support for writing apps in HTML, CSS, and JavaScript, we do have some resources that are starting to emerge.

First, my newly-released second edition, http://aka.ms/BrockschmidtBook2, is very applicable to Phone apps. I didn't have time to spell out all the differences, but there is a summary of what to watch out for in Chapter 1, namely a few differences in controls and some parts of WinRT that aren't on the Phone.

Second, watch the Building Apps for Windows Blog for material in this area. For example, an upcoming post will spell out the controls story between Windows (WinJS 2.0) and Windows Phone (WinJS 2.1).

Third, Josh Williams and Ryan Salva did a demo session on building a universal app with HTML, CSS, and JavaScript at //build, which you can find on http://channel9.msdn.com/Events/Build/2014/2-540. What you'll see is that they do nearly all of the work in the Shared folder of the VS project, making only one small change at the end of the session to switch the Hub control in the Windows Store app to Pivot in the Phone app…the two controls, in fact, are identical in their API except for the top-level object names, so you just change the names and voila! You're in business.

Finally, there is a post on the Visual Studio blog on universal apps: http://blogs.msdn.com/b/visualstudio/archive/2014/04/08/building-windows-phone-8-1-apps-in-html.aspx.

More is certainly to come.


Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition, is now released! You can find this free ebook (PDF, Mobi, and epub) it on http://blogs.msdn.com/b/microsoft_press/archive/2014/04/08/free-ebook-programming-windows-store-apps-with-html-css-and-javascript-second-edition.aspx. Companion content is on http://download.microsoft.com/download/6/6/5/665AF7A6-2184-45DC-B9DA-C89185B01937/Programming_Windows_8_Apps_HTML_CSS_JavaScript_2E_CompContent.zip and the videos are on http://microsoftpressbooks.azurewebsites.net/programming_windows_apps_with_html_2ed/.

I have to say that it's ironic that although the book covers Windows 8.1 and is mostly applicable to Windows Phone 8.1 as well, announcements at //build changed the landscape almost immediately. For one, WinJS is now open source and isn't specific to Windows Store Apps, and WinJS 2.1 for Windows Phone has some differences from WinJS 2.0 for Windows Store apps. Oh well. Guess it's onto the third edition now! Still, I suspect that this book, being free and the most comprehensive, will continue to be the primary WinJS reference, open source or not.

 

 


The video of my talk at //build 2014 is online: http://channel9.msdn.com/Events/Build/2014/2-638. "Understanding Customer Patterns: Instrumenting Your App for Telemetry and Analytics." The written version of this is what I published on the App Builder's blog recently: http://blogs.windows.com/windows/b/appbuilder/archive/2014/03/20/instrumenting-your-app-for-telemetry-and-analytics.aspx.

Thanks to everyone that downloaded my 15+Puzzle app and played with it a bit. I also had a number of folks in the audience do it during the talk, which made a compelling presentation. And yes, I did give away all the prizes I had…about 6 people approached me afterwards showing the app with a medal. :)

 


This page is the collection point for errata in my book, Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition. If you find an error, please check the know error list below. If you've found a new error, please leave a comment with the details and I'll migrate into the body of this post. Thank you!

Page numbers given here refer to the PDF, but I also try to give the name of the nearest section header or sidebar title.

Multiple Chapters:

  • The website http://dev.windows.com has been revamped to include Windows Phone, Desktop, Hardware, and IE, so a "Dashboard" link no longer appears at this URI. To get to the right page, use the drop down along the top of the page to select "Windows Store Apps". This takes you to http://msdn.microsoft.com/en-US/windows/apps/ where "Dashboard" is visible.

 

Chapter 1:

  • Page 41: As of Windows 8.1 Update 1 (released shortly after the book was complete), local loopback and "brokered WinRT components" allow for inter-process communication between side-loaded apps and desktop processes. These capabilities are specifically designed for side-loaded apps in enterprise scenarios, and are not supported for apps installed via the Store. For more information, see Brokered WinRT component project templates now available (Building Apps for Windows Blog) for all the details.
     

Chapter 8:

  • Page 432: In the footnote I mention that WinJS.UI.ViewBox was removed for WinJS 2.0. Apparently it made it back in late in the game, so you can use it directly instead of writing your own code as shown in the book.
  • Page 453. I mention that the WinJS.UI.Hub control is only present in WinJS 2.0 for Windows 8.1. On Windows Phone 8.1 and WinJS 2.1 you have the WinJS.UI.Pivot control instead. The two are supposed to have virtually identical interfaces, so you should be able to replace WinJS.UI.Hub with WinJS.UI.Pivot and WinJS.UI.HubSection with WinJS.UI.PivotItem section in your HTML and be in business. I have not tested all this, however.

 

Chapter 11:

  • Page 612, last "Hint" under the section, "KnownFolders and the StorageLibrary Object" (or just above "Removable Storage")–the Library management sample now shows the proper use of removeEventListener for definitionChanged. (Got that bug fixed!)

 

Chapter 13:

  • Page 707: numbering in the list should start at 1.

 

Appendix D:

  • Page 1303: The AppointmentProviders example in the companion content has a bug on line 60 of html/manageAppointment.html, where the method call should be reportCompleted (it's missing the "d" at the end) and will throw an exception as it currently exists.

To follow up on my previous post, one part of my demo at //build is the telemetry data gathered from my 15+Puzzle game in the Windows Store. You can find it here: http://apps.microsoft.com/windows/app/15-puzzle/2406fbef-c596-4ddf-88a6-34542562dd75.

It's free, so go install it, play some games between now and next Thursday at 5:30pm, and I'll have some extra data to show. Thanks!

1_first screen


Another post of mine on the App Builder's blog: http://blogs.windows.com/windows/b/appbuilder/archive/2014/03/19/instrumenting-your-app-for-telemetry-and-analytics.aspx

This is much of what I'll be covering in my talk at //build 2014 in two weeks, and the material also appears in Chapter 20 of Programming Windows Store Apps with HTML, CSS, and JavaScript, which is getting finalized now. (Watch http://aka.ms/BrockschmidtBook2 for that announcement.)