In a number of forum questions over the years, I've seen devs struggling with using relative URIs to in-package resources. Typically it boisl down to the difference between something like "images/pix1.jpg" and "/images/pix1.jpg".

These two URIs mean, in the words of Jeremy Foster, "dive into the images folder and find pix1.jpg" and "go back to the root, then dive into the images folder and find pix1.jpg", respectively.

In Windows Store apps, it's helpful to remember that all such in-package 'relative' URIs are shorthands for ms-appx://<package_id>, as in ms-appx://<package_id>/images/pix1.jpg or just ms-appx:///images/pix1.jpg. A leading / on URIs, then, is what really makes the reference an absolute one, rather than a relative one. It just feels relative because you're not specifying a schema.

To be even more precise, a relative URI always must resolve against some base URI, which is defined by the referring document. Where people get tripped up is that when you're using WinJS page controls, such as ms-appx:///pages/somePage.html, then ms-appx:///pages becomes the base URI, and images/pix1.jpg will resolve to ms-appx:///pages/images/pix1.jpg. If you thought you were referring to the root images folder in the project, then you'll likely find the image not appearing at all. If you use /images/pix1.jpg, on the other hand, then you are making an absolute reference from the package root via shorthand, which resolves to ms-appx:///images/pix1.jpg.

The bottom line is that unless you really know that you're making a relative reference to the currently loaded HTML page, use a leading / to get back to your package root.


In a bit of departure from my usual subject matter, I wanted to share a writeup I did for my team in regards to an Android device I acquired for the purposes of doing some dev work with Xamarin and Cordova in Visual Studio on Windows.

The Short Story:

If you are looking for an Android tablet for dev work (like for the purposes of doing Cordova and Xamarin), the most important thing is that you can find a Windows USB driver for the thing. This is what will allow you to debug from Visual Studio, Xamarin Studio, Eclipse, and so on, or, to be specific, to run the first Xamarin tutorial project through which you get to order a free (and real) C# T-shirt.

[I was aksed why I thought I needed a real device when there are emulators. Emulators only go so far and fall short of where a device actually touches the physical world, e.g. sensors, NFC, attaching via USB, using touch for real, seeing real-world performance on target devices, and just understanding how something works when you’re holding it in your hand. Also, an emulator will never give you the full end to end experience of a consumer, e.g. switching between apps, multitasking, acquiring apps from a store, etc. I wouldn't ever ship an app without at least one real device test. In my work, specifically, the people I'm writing for are using real devices and having one myself, and immediately hitting a significant challenge, gave me a much better understanding of issues that we can help those customers solve.]

Anyway, if you have any particular device in mind, check the list on http://developer.android.com/tools/extras/oem-usb.html, and follow the links to the manufacturer pages to verify the existence of an easy-to-acquire driver. If you don’t find one, look for a different device that has one, or you can enjoy the process I describe below to essentially hack one.

And when you have a device, http://developer.android.com/tools/device.html is where you find info on how to unlock a device for dev work—has the great UI of going to a specific setting and tapping it seven times!

 

Sidebar: Getting the Device to Show Up in the Tools

Before going into the details of hacking a driver, a little aside on running apps on an Android device from Visual Studio. Tools talk to an Android device through the Android Debug Bridge, or abd, which is managed through the command line (see http://developer.android.com/tools/help/adb.html). You can easily get to a suitable command prompt through a button that shows up in Visual Studio if you’ve installed the multi-platform hybrid app tools or the Xamarin SDK (circled below):

Android devices in VS

If the adb isn’t seeing your device (which you can check on the command line with adb devices -l), it won’t show up in the drop-down list of debug targets. If this happens, here are steps you can try:

  1. Unplug the USB cable and reattach. This might be sufficient.
  2. It might be necessary to restart Visual Studio. I’ve found that VS will refresh itself when you attached/detach a device, but if it doesn’t, there’s always a restart.
  3. Open the command prompt and do adb kill-server and then adb start-server. You might need to restart VS again.

When VS sees the device, you can then enjoy all the usual capabilities of VS. Otherwise you get stuck with emulators that you probably won’t enjoy, especially when it comes to figuring out which one has which API level support to match your code project.

 

The Long Story: Hacking a USB Driver

When looking for a tablet, I shopped around on Amazon to find a middle-of-the-road, reasonably-priced, name-brand tablet. In the end I chose the Asus MemoPad 7, which looked much more reliable than the really cheap tablets, but not so expensive as the mainline Google or Samsung models.

Knowing what I now know, I probably would have chosen differently, because once I figured out how to unlock the tablet as a dev device, I found that ASUS didn’t have an appropriate USB driver on its site. This also meant that plugging the device into my system for the first time didn’t manage to find a driver, thus resulting in the undesirable  !  in Device Manager.

Turning to a full web search, I found some other possibilities, and pointed Device Manager to the place where I’d downloaded the driver package. However, each one I tried gave me that annoying message, “Windows could not find a driver for your device.”

Let me get a bit technical for a minute. Every USB device is uniquely identified by a Vendor ID or VID, and a Product ID or PID. So USB device people talk of the VID/PID for any given device, which you can always find for any device (driver or not) by viewing its properties in Device Manager, switching to the Details tab, and selecting Hardware Ids from the drop-down:

VID PID in Device Manager

Here you can see that the VID is 0B05 (Asus) and the PID is 5507.

When you see the “Windows could not find a driver for your device” message, it means that the .INF file for the driver that you pointed to does not contain an entry that matches the VID/PID of the device, and Windows will refuse to install the driver. This is true even if you know damn well that the driver will work, and that the silly driver package just hasn’t been updated properly.

Which brings us to the hack, and some learnings along the way.

Now lest you think an .INF file is some kind of magic, it’s not. It’s just a plain text file that describes the VID/PID combinations with which the driver will work. For example, I found a generic Asus ADB Driver package (all tablets really work with the same driver), and it had lots of entries like this:

%CompositeAdbInterface%     = USB_Install, USBVID_0B05&PID_4DEF&MI_01

None matched the 5507 PID, however. OK, so perhaps I could just add an appropriate line in the .INF file for the right VID/PID? (Making sure to enter the line in both the .NTx86 and .NTamd64 sections of the .INF file.)

Rats. No luck. The .INF file is just an easy way to describe the driver’s supported devices, but there’s a second step that goes through a .CAT file. A .CAT file is a “Security Catalog” that, well, provides a security check. So although the .INF file will match, you’ll get a security warning and Windows will refuse the install the driver.

So….the natural question is, how do you make that .CAT file match the .INF file? It’s pretty easy, actually. The Windows Driver Kit (WDK), that’s an extra download from MSDN, has a little tool called inf2cat.exe that does exactly this.

After waiting a while for the rather large WDK to download and install, I ran the tool, produced the right .CAT file, and tried again.

Damn. Windows doesn’t like it when you don’t have a properly signed .CAT file with an appropriate security certificate.

Fortunately, someone has blogged about this exact thing: http://tivadj-tech.blogspot.in/2012/09/certificate-check-error-when-installing.html. Let me summarize:

  • Go to PC Settings > Update and Recovery > Recovery > Advanced Startup and press the Restart Now button.
  • Oh, wait a minute—be sure that you have your Bitlocker key handy because you’ll be required to enter it when the machine reboots!
  • When the machine reboots, and you enter that Bitlocker key, select Troubleshoot > Advanced Options > Startup Settings and tap Restart.
  • When the machine reboots (again, did I mention you’ll need your Bitlocker key?), you’ll have a list of choices for tweaking the boot process. Select the one that says “Disable driver signature enforcement.”

Bwah-ha-ha! Now you have power. Well, at least you have the power to install a hacked driver, meaning that Windows will allow you (with another dire warning that you get the perverse pleasure of ignoring), to install a driver using.INF and .CAT files that you rebuilt yourself.

Once I did this, Windows was happy with the Asus Memo Pad 7, and so was ADB and Visual Studio. This allowed me to finally run that first Xamarin project on my device, and order the T-shirt that was, of course, the whole point of all this!

 

Postscript: the Universal ADB Driver

To be honest, I didn’t end up using the ASUS driver package itself. In the course of my investigations I came across a Universal ADB Driver that works for a whole host of devices, meaning you can use this one driver for any variety of Android  devices because all those devices are basically talking to the ADB daemon running on the device once you do that seven-tappy thingy to unlock it.

The source for the driver—which really amounts to an .INF file plus copies of the generic USB driver from the Windows Driver Kit, is on GitHub: https://github.com/koush/UniversalAdbDriver. This makes it easy, and less of a hack, to modify the .INF file, rebuild the .CAT, and sign it properly. This is what I have installed now.

To be honest again, I didn’t actually get the signing certificate in the project to work, so I used advanced boot and installed the unsigned driver. Maybe someday I’ll understand this business with certificates (and I'm happy to be educated through comments–send me some links!), but I was eager to get my T-shirt.


When I was writing the last chapter of Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition, I noticed that when you used the CurrentAppSimulator object for testing the Store APIs, that the default XML included a bit for consumable in-app purchases:

<ConsumableInformation>
  <Product ProductId="2" TransactionId="00000000-0000-0000-0000-000000000000"
      Status="Active" />
</ConsumableInformation>

Unfortunately, it wasn't documented, so I had to work it out with the program manager who owned it. Put simply, the ConsumableInformation is used to provision a default in-app offer similar to how durable offers are included in the LicenseInformation node.

The TransactionId attribute is required, and will match the value used when calling CurrentAppSimulator.ReportConsumableFulfillmentAsync(productId, transactionId).

Status is also required, and can be Active, PurchaseRevoked, PurchasePending, and ServerError. This allows a developer to emulate all the possible responses to the ReportConsumableFulfillmentAsync call.

There is an optional attribute OfferId on the <Product> element which can be used to set the same value that would normally be set at the time of purchase for the large catalog API: CurrentAppSimulator.RequestProductPurchaseAsync(productId, offerId, displayProperties).

Fortunately, we were able to get all this into the CurrentAppSimulator documentation, which you can find here: http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.store.currentappsimulator.aspx

 


When creating apps for both Windows 8.1 and Windows Phone 8.1, you typically want roaming data–as managed through the WinRT APIs–to work seamlessly across both.

The first requirement here is that both apps are using the WinRT APIs for this purpose, meaning that the Phone app project is not using Silverlight but rather the "Windows XAML" or WinRT flavor. Clearly this isn't an issue for apps written in JavaScript, where that's the only option, nor for universal Windows apps that focus on WinRT.

Note that it's not necessary to implement the app with a universal app project in Visual Studio. Those project structures are simply a way to simplify development processes, and isn't a requirement for providing the same app experience on both Windows and Windows Phone.

The second requirement, however, is that both apps–however you build them–must have the same identify in their respective stores, which means specifically the package family name. This is what's used to manage the roaming settings, and so long as those match, then both implementations will work with the same roaming data. This is again a given with a universal app project, but something you have to do manually if implementing the apps with separate (non-universal) projects.

A little guidance on this can be found here: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn630421.aspx

For some general Q&A on app data, which includes other aspects of roaming, see my post on the Building Apps for Windows blog: http://blogs.windows.com/buildingapps/2014/06/19/common-questions-and-answers-about-files-and-app-data-part-1-app-data/


Some Q&A I've collected recently. Enjoy.
 

Q: I'm trying to bind part of a ListView item template to the result of a method in a class, but the function text itself is appearing instead of the result. How can I make this work?

A. Here's the context for the question. Say we have a simple binding declaration as follows:

<div data-win-bind="textContext: FullName"></div>

And we're binding to a class that looks like this:

var _MyClass = WinJS.Class.define(
    function () {
        this.FirstName = "";
        this.LastName = "";
    },
    {
        FirstName: "",
        LastName: "",
        FullName: function () {
            return this.FirstName + ' ' + this.LastName;
        }
    }
);

The issue is that binding to FullName doesn't execute the function, but just binds to the function object. There aren't problems binding to FirstName and LastName as those are just properties.

The solution here is to make FullName a property as well, rather than a function, which can be done as follows:

FullName: {
    get: {
        return this.FirstName + “ “ + this.LastName;
    }
}

[Thanks to Dominic Hopton]

 

Q. Is it possible from JavaScript to bind to data in a WinRT component?

A. Yes. The trick is that you need to use WinJS.Binding.oneTime as the initializer in the binding syntax. For a full discussion, see Mike Taulty's blog: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2012/04/26/windows-8-metro-style-bits-of-binding.aspx

 

Q. Is it possible to use WinJS data binding on styles and other non-text elements?

A. Yes it is. In general you can use the syntax data-win-bind="style.<target_property>: <source_property>", and for styles like font-weight and text-decoration that don't work with dot notation you can use []'s as in data-win-bind="style[target-property]: <source_property>".

Phil Japiske has a good post on this subject on Telerik's blog: http://blogs.telerik.com/Windows8Team/posts/13-12-27/setting-html-styles-with-binding-in-windows-8-winjs-apps 


In a previous post I described how to realiably use Debug/Release build configurations in Visual Studio to selectively copy a debug or release file into your project at build time, offering a solution to JavaScript's lack of precomiler directives like #ifdef DEBUG as found in C# and C++. I wanted to expand on that post with additional options that I've seen discussed. [Thanks to Rob Paveza, Ginger Edighoffer, Howard Kapustein, Steve Bohlen, and Gearard Boland.]

In this context, people often suggest using the following structure for similar purposes:

if (Debug.debuggerEnabled) {
    // use debug settings
}
else {
    // use production
}

Although this works reasonably well, the downside is that having a debugger enabled says nothing about how the project was built. You can debug a Release build of a JavaScript app just fine, in which case debuggerEnabled will be true and you can still step through the code because JavaScript isn't compiled ahead of time. This means that stepping through the code above for a Release build will not hit the //use production block.

You can work around this, of course, by setting a breakpoint on the if statement and then setting the next statement to the //use production block. If you want to do this pervasively, then you can wrap a simple function around Debug.debuggerEnabled where you can set a single breakpoint:

function checkDebug() {
    if (Debug.debuggerEnabled) {
        return true;
    } else {
        return false;
    }
}

In here I've put in two return statements so there's an obvious place to set the next statement and control the return value.

Another suggestion I've seen for this matter is to create a simple C++ WinRT component that does something like this:

namespace WrcCpp
{
    public ref class ModeMonitor sealed
    {
        private:
            ModeMonitor() { };

        public:
            static property bool IsDebugMode {
                bool get() {
#ifdef _DEBUG
                    return true;
#else
                    return false;
#endif
                }
            }
    };
}

There's also a property in Windows.ApplicationModel.Package.current.isDevelopmentMode that you might come across but this reflects how the package was installed (that is, it was deployed from Visual Studio rather than the Store), and not how the package was built. That is, it describes the deployment mode, not the build target.

Here's another possibility: run your JavaScript code through a C++ preprocessor that can chew on the #ifdef statements to generate the JavaScript code you want to run. I imagine that this could be incorporated into a Visual Studio build process similar to my previous post. 

Along these same lines is the need to differentiate code in a universal Windows app project that's targeted specifically to Windows or Windows Phone when that code lives in the Shared folder. That is, although you can keep code for both targets separate in their own project structures, sometimes it's just easier to make a simple differentiation within some of the Shared code.

The compiled languages have the WINDOWS_APP and WINDOWS_PHONE_APP precompiler directives for this purpose, but not JavaScript. The options you have, then, are as follows [thanks to Steve Bohlen]. First is WinJS.Utilities.isPhone:

if (WinJS.Utilities.isPhone){
    // phone
}
else{
    // not phone
}

Second is using a feature detection pattern like you do with cross-browser JavaScript:

if (PhoneAPINamespace && PhoneAPINamespace.phoneAPI) {
   //  safely call phoneAPI()
}

The first option is more explicit, of course, whereas the second is more resiliant to changes in the available API (a consideration with continued convergence in WinRT).

 


I've seen a report where adding a Windows Phone 8.1 to an existing app project caused files added to the shared project to be dropped in the project root rather than the folder hierarchy of the shared project. (This doesn't happen with new projects, by the way.)

To be specific, say you have an existing Windows 8.1 app project. You right click on that and select the "Add Windows Phone 8.1" command, which creates a Phone project and a Shared folder in your solution.

If you encounter this, the workaround is to open the project files manually (unload and edit in VS, or edit in Notepad), and make sure the <Import> tags in the project put the shared project first. That is:

<Import Project="..App2.SharedApp2.Shared.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)MicrosoftVisualStudiov$(VisualStudioVersion)$(WMSJSProjectDirectory)Microsoft.VisualStudio.$(WMSJSProject).targets" />

 


In case you haven't noticed, a recent update to Windows 8.1 makes a Privacy Policy link recently appear autmatically for Windows Store apps. This link takes the user to the app's page in the Store where the privacy policy link is available.

This means that apps no longer need to include their own privacy link; however, I don't yet know how to detect whether this is happening for an app so you can suppress your own link.If anyone has investigated this, please post in comments. That said, I personally like having a cleaner Privacy Statement link in an app that can open a settings pane directly with that content, rather than navigate to the Store.

It's worth noting that with this change, all you have to do to meet requirement 4.1.1 of the Store Certification Policy is submit a link to your policy when you submit the app. Because the app cert testers will be using the latest 8.1 build, you should pass cert without having a distinct command in your own settings. 


I wanted to let you all know that starting September 2nd, I'll be taking on a new role as Senior Content Developer for Azure and Visual Studio, as part of the Developer Answers team in Microsoft's Cloud & Enterprise Division. This means that content production will be even more of my focus than it has been in the past, when having a Program Manager title often meant getting involved in a variety of other activities!

Blogging will certainly continue, both on Windows and also on Azure and other topics as I expand into those areas. In the meantime, I've been blessed to have a little break between this and my former job, which has provided lots of time for home projects and spending time with family before my son's school starts up again.


Thanks to Michael Scherotter for the details explained in this post.

Say you have an x-ms-webview element on a page in your app:

ms-webview id="webview" class="Content" src="ms-appx-web:///contenthost.html">
</x-ms-webview>    

and you want to print only the contents of the WebView. To do this, it seems at first that you need to get a DOM document object for the Webview to pass to MSApp.getHtmlPrintDocumentSource within a PrintTaskSourceRequested event. However, as noted in an earlier post, the Webview's DOM isn't accessible by the host app, for many good reasons, so it seems you're left with solutions like obtaining a bitmap of the Webview and printing that.

But there's another way that can work in a number of scenarios, especially when you know the content you're loading into the Webview and aren't wanting to print arbitrary pages. The trick is to load that content into a new document fragment and use that to obtain a source:

    //content is what you load in the Webview; printTask and printDeferral come from the WinRT print event

    var fragment = document.createDocumentFragment();
    var printSource;
    div = document.createElement("div");

    fragment.appendChild(div);
    WinJS.Utilities.setOuterHTMLUnsafe(div, content);

    source = MSApp.getHtmlPrintDocumentSource(fragment);
    printTask.setSource(source);
    printDeferral.complete();

You new methods like setOuterHTMLUnsafe had a use somewhere!