LA.NET [EN]

Windows8Archive

May 31

The “your developer lic has expired problem”

Posted in Windows8       Comments Off on The “your developer lic has expired problem”

Today, I’ve started getting another license error. I’ve tried to open a project I’ve built a few weeks ago and when I’ve hit F5, it simply redirected me to the store and shown me the following message:

image

Wtf? Another lic problem? why me??

Fortunately, I wasn’t alone in this one and I’ve found this post in the stackoverflow forums which did help me solve this problem. Instead of adding a string to the GUID, I’ve resorted to the Create GUID tool (VS->Tools->Create GUID) and replaced the GUID that was being used in the package name with a new one. And that was all it took to solve my problem.

May 07

Can’t renew your Metro developer license? Then this is for you!

Posted in Trivia, Windows8       Comments Off on Can’t renew your Metro developer license? Then this is for you!

As you know if you read this blog, I’ve been unable to write any Metro JavaScript code for a few days because I couldn’t renew my developer license. Well, after complaining in the forums, I had the good fortunate to receive some attention from Mike Wong, who was kind enough to take this problem with the developer team. I must say that I wasn’t pleased with the initial solution and that I really unleashed all my rage on pour Mike. Fortunately, he redirected it to the team and come back with a solution which *doesn’t* involve reinstalling windows (this is really important to me because all my machines are only running Windows 8). So, here is what you need to do if you face the dreaded Metro license renew error:

  1. Remove all the Metro apps  you’ve installed which were built with your license. This typically means uninstalling all the apps you’ve opened in VS and hit F5 or CTRL+F5;
  2. Wait two days. I know it looks like a joke, but I’m serious: you need to wait for two days;
  3. After the those 2 days wait, you’re ready to rock-n-roll: it’s renewal time!

And that it’s. After the weekend, I was finally able to renew my license. Once again, special thanks to Mike Wong! Now, it’s time to code Smile

May 03

The unbelievable Metro dev lic renewing problem!

Posted in Trivia, Windows8       Comments Off on The unbelievable Metro dev lic renewing problem!

This is simply unbelievable! As an early “Win 8 dev adopter”, I’m really stumped with the error I’m getting for the last couple of days. Being an early adopter means getting all sort of problems and being subject to changes which breaks everything you’ve written with the previous release. Sometimes, it’s not fun, but I can live with that.

What I can’t really understand is why I’m unable to deploy any app since Tuesday because my initial license is no longer valid and I’m always getting an error while trying to renew it. In order words, even though I want to write Metro code and provide feedback and ask questions in the forums, I’m simply unable to do (for 2 days now!) that because I can’t renew my license. This is not the way to bring more people to the platform! Want to use a lic system? Fine, but make sure that it works!!!

Did I mentioned that I’m pissed??

Mar 09

It took me some time, but I finally managed to get the concepts of local vs. web contexts. It took some time not because they’re that difficult, but because the Windows 8 Metro docs are still a mess (which is understandable, since we’re still at beta – pardon me, I mean Consumer Preview) and finding someone with the time to explain it to me was not really as easy as I thought it would be. Anyways, that’s past, so lets get started.

WinJS app’s code can only be run in one of two contexts: local or Web. The need for having two contexts is motivated by the need to run code coming from different origins. For instance, you might need to embed a map in your app to enhance the way you present data to your users. In fact, you’ll probably need to interact with that map through code. Now, currently this might mean embedding a script reference to Google or Bing maps, and that really means we’ll have code written by others being executed in our app. Another good example of running external code is advertising. Typically, this also means adding a reference to an external script

If all the resources would run with the same privileges, then we might get into trouble because we can’t really know what all the 3rd party libraries do and we can’t really guarantee that all of them don’t have any malicious code (I’m sorry, but that’s just life!). And that’s why we have the concept of local vs. web context. The execution context under which a resource runs is responsible for granting features and imposing restrictions. For instance, all pages running in the local context can have full access to the WinRT and to the WinJS (some of those features depend on configuring the manifest to ask them to the final user) or even make cross domain calls (through XHR), but can’t reference any external scripts nor execute code by using the “javascript:code” scheme in an URI. Now, when code runs in the web context, some of these restrictions go away (ex.: external script references are allowed), but you’ll have new ones. For instance, you won’t be able to access the WinRT and you’ll only be able to access part of the WinJS features (for a list of these limitations, please read this).

Now, the important question: when does a resource gets executed in the local context and when does it get executed in the web context? Generally, people say that local content (i.e., content maintained inside the app’s package) runs in the local context and all external resources run in the web context. Even though this is correct in most cases, this definition is not really accurate. In fact, the platform will resort to the http scheme of a resource’s URI to see if it should be executed in the local or in the web context. All the resources using the ms-appx, run the in the local context and everything using the http, https or ms-appx-web scheme will be run in the web context. Now, ms-appx is used by default to reference resources maintained inside the app’s package (and you won’t be seeing them often unless you’re getting stuff from an external package). We all know what http and https are used for, so there’s not much to say here. What about ms-appx-web? Well, that’s the interesting one…You can use it to make a local resource run in the web context. When will you want to do this? Well, it might be a good option when you’re building mashups. For instance, suppose you want to add a map and need to write some JS code to interact with it. Since maps are added through external references, then you can’t insert them in your top page because that page will always run in local context. In that case, you can always build another local page which references the external map and has JS code to interact with it. Then, you can add an iframe to your top page which references that auxiliary local page through the ms-appx-web scheme (instead of using the default ms-appx scheme).

Btw, if you’re writing code and you need to know if you’re currently running in the local or in the web context, the easiest way to perform that check is to see if the Windows object exists or not (Windows, not window, ok?)

Now that we know the difference between both contexts and how resources are executed in one or the other, we still need to take a look at the ApplicationContentUriRules section (if you’re using the UI manifest editor, then I’m talking about the Content URIs tab). If you look at the docs, you’ll notice that this element “specifies the boundary of an app in terms of internet domain and URLs that the system hosting the app considers part of the app”. In other words, you can use this section to grant some extra privileges to external content which is going to be loaded in the web context. If I’m not mistaken, you’ll need to add an include rule to this section for any external content that tries to access the clipboard or get geo info from the geolocation object. Notice that you still won’t be getting any access to the WinRT. You can also add exclude rules and these should be useful when you want to allow a domain to access these features, while at the same time preventing a specific URI from being able to access them (this is possible because the URI specified can use a pattern for matching).

And I think this should make things clearer, right? Bottom line: a resource can only run in the local or in the web context and you can use the ApplicationContentUriRules section to allow external resources to access to the clipboard and geolocation objects.

And that it’s for now. Stay tuned for more.

Jan 27

If you’ve been doing Web development from some time now and you’ve looked at several of the Windows 8 samples, you’re probably wondering which event you should handle if you’re interested in doing work as soon as you can. The first option you have is to handle the DOMContentLoaded event. As you probably know, this event will be fired when the current document has been parsed (but might not have been totally loaded – ex.: images might still being downloaded, but you can interact with all the DOM elements).

Since you’re writing a Windows 8 application, them you should also know that the WinJS library will handle this event. Internally, the library does some housekeeping, which lead to the generation of several WinJS custom events. Currently, you’ll end up with the following sequence of events: loaded (fired right after the DOMContentLoaded event), mainwindowactivated (similar to activated; in fact, it’s generated from the internal WinJS activated event handler), activated (occurs after WinRT activation has occurred), ready (occurs when the application is ready and all the housekeeping has been done).

Since we’re talking about events, then  don’t forget that you must always call the WinJS.Application.start method or you won’t get any of the WinJS events. This happens because, under the hood,  WinJS queues events and it will only start processing them after you call that method.

And that’s it for now. Stay tuned for more.

Jan 20

Windows 8 adventures: error handling and the async pattern

Posted in Windows8       Comments Off on Windows 8 adventures: error handling and the async pattern

In the previous post, we’ve started looking at the async pattern in Windows 8 Metro apps developed with JavaScript. By now, you know that all async operations are wrapped in Promise objects which you can use to be notified when that operation has ended (besides other interesting things!). We’ve also seen how we can “improve” the code readability associated with several async operations which are executed in chain.

What I didn’t mention at the time is that the then method expects three parameters (all functions). Besides the success function, you can also pass two other functions which will be called, respectively, for reporting an error and for reporting progress. If you follow my previous advice and return new Promises from the then method, then you can get “global” error handling by adding a final then method which defines the global method function. Here’s an improved version of the createFolderAndFile function:

function createFolderAndFile() {
    //create new folder inside temp folder
    var tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
    tempFolder.createFolderAsync("testFolder",
    Windows.Storage.CreationCollisionOption.openIfExists)
    .then(function (folder) {
        return folder.createFileAsync("testFile.txt")
    })
    .then( function (file) {
        return file.openAsync( Windows.Storage.FileAccessMode.readWrite);
    })
    .then( function (dataStream) {
        var stream = dataStream.getOutputStreamAt(0);
        var writer = new Windows.Storage.Streams.DataWriter(stream);
        writer.writeString("Howdy, there!");
        return writer.storeAsync()
        .then(function () {
            return stream.flushAsync()
            .then(function () {}, function () { }); }); })
    .then(null, function (err) { //handle error here! });;
    }

Notice that there’s a slight change and we’re returning the result of the storeAsync().then call so that all eventual errors can be handled in the error function passed to the last then method call. You can test this behaviour by adding throw statements in several places in the previous code and by setting a breakpoint inside that anonymous error function.

And that’s all for now. Stay tuned for more.

Jan 19

Windows 8 adventures: the async pattern in JavaScript

Posted in Windows8       Comments Off on Windows 8 adventures: the async pattern in JavaScript

After a small detour into ASP.NET MVC, I’m back into my “Windows 8 application development study”. One of the things you’ll notice when writing Windows 8 Metro applications is that most APIs don’t expose any synchronous methods. If an operation takes more than 15ms to be executed, then you’ll be getting an asynchronous call. And notice that asynchronous is not an option here! It’s simply the only way to go.

If you’re developing Windows 8 Metro apps with JavaScript, then it won’t be long until you meet the WinJS.Promise object (which I’ll be calling Promise from now on). Most (if not all) of the asynchronous method you’ll be using end up returning a Promise. For instance, if you’re trying to create a new file, you’ll probably be using the createFileAsync method. This method returns a Promise which you can then use for being called back when that operation is performed. To illustrate this point, lets see some code which creates a new file inside a new folder. Here’s our first try:

function createFolderAndFile() {
    //create new folder inside temp folder
    var tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
    tempFolder.createFolderAsync("testFolder",
    Windows.Storage.CreationCollisionOption.openIfExists)
    .then(function (folder) {
        folder.createFileAsync("testFile.txt")
        .then(function (file) {
            file.openAsync(Windows.Storage.FileAccessMode.readWrite)
            .then(function (dataStream) {
                var stream = dataStream.getOutputStreamAt(0);
                var writer = new Windows.Storage.Streams.DataWriter(stream);
                writer.writeString("Howdy, there!");
                writer.storeAsync()
                .then(function () {
                    //don't do anything in callbacks
                    stream.flushAsync()
                    .then(function () { }, function (err) { var r = ""; });
                });
            });
        });
    });
}

Wow!!! I’ve written the code and I’m already lost here! Fortunately, you can improve this code by returning promises from your .then methods. By doing that, you can write code which is a little bit more linear. Here’s our initial example rewritten:

 
function createFolderAndFile() {
    //create new folder inside temp folder
    var tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
    tempFolder.createFolderAsync("testFolder", Windows.Storage.CreationCollisionOption.openIfExists)
        .then(function(folder) {
                return folder.createFileAsync("testFile.txt")
        }).then(function(file) {
                return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
        }).then(function(dataStream) {
            var stream = dataStream.getOutputStreamAt(0);
            var writer = new Windows.Storage.Streams.DataWriter(stream);
            writer.writeString("Howdy, there!");
            return writer.storeAsync()
                .then(function() {
                    return stream.flushAsync();
                });
        });
}

I’d say that this is better (at least, from a readability point of view). What do you think?

Btw, I’m almost positive that you’ve notice the empty then calls on the flishAsync method? Well, I’m still not sure why, but the thing is that “empty” call is needed in order for the bytes to be saved to the file. If you remove the .then call, you’ll end up with an empty file (no, are we talking about a bug here?? )

And that’s it for now. Stay tuned for more.

Jan 12

Windows 8 adventures: getting to know context menus

Posted in Windows8       Comments Off on Windows 8 adventures: getting to know context menus

In the previous post, I’ve talked about the new Flyout control. Today, we’ll take a quick look at the context menu. In practice, you’ll show a context menu when you need to show a menu which gives the user immediate access to actions on text or UI objects.

By default, there are predefined context menus for text and hyperlinks. For text, the default context menu ends up showing the traditional cut, copy and paste commands. For hyperlinks, you end up with commands which allow you to copy the link or to open the link in a new window. For instance, suppose you’ve got a textarea in your default landing page:

<p>
    <textarea rows="4" cols="50"></textarea>
</p>

After writing texto and right clicking over any text selection, you’ll end up with the following default context menu:

contextmenu

Now, it’s important to notice that the options shown may vary. For instance, if the text is read only, you’ll only see the copy option. To illustrate this option, lets add a new paragraph to our landing page:

<p id="paragraph1"  data-win-selectable="true">
    Some demo text just for testing purposes...
</p>

Now, you’ve probably noticed the use of the data-win-selectable attribute. You need to resort to this attribute when you want to make p’s content selectable. The next image shows the results:

contextmenu2 

If you’ve been paying attention to the HTML evolution, then you know that the HTML5 spec introduces the contenteditable attribute which can be used to make the content of an element editable. Even though the docs say that setting this attribute to true is enough for making the element selectable (and it is!), there’s a bug in the current preview release associated with the context menu: whenever you apply the contenteditable attribute to an element, you can select text, but right clicking over that selection will not show you the context menu. Since we’re talking about bugs, it’s also important to notice that right clicking over selected text will also end up showing the appbar (if there’s one). I expect to see both these problems solved until we get a final release.

Now that we’ve already discussed some of the basics, you might be wondering about the code needed to show a context menu. The strategy is rather simple:

  1. we start by setting up an event handler for the context menu event;
  2. we prevent the default behaviour from within that handler;
  3. we create a new PopupMenu control and populate it with the required UICommand entries;
  4. we show the menu in the appropriate place by using the showAsync or showForSelectionAsync method.

To illustrate these points, we’ll replace the default context menu shown when the user right clicks over the selected text of the paragraph presented in the beginning of this post. As I’ve said, the first thing we need to do is set up an event handler for the context menu event of our paragraph. This can be done from within an initialization function which, for instance, is called from within the DOMContentLoaded event handler:

document.getElementById("paragraph1").addEventListener(
    "context menu", showContextMenu, false);

Lets take a look at the code used inside the showContextMenu function:

function showContextMenu(evt) {
    evt.preventDefault();
    var menu = new Windows.UI.Popups.PopupMenu();
    menu.commands.append(
      new Windows.UI.Popups.UICommand("Copy", null, 1));
    menu.commands.append(
      new Windows.UI.Popups.UICommandSeparator());
    menu.commands.append(
      new Windows.UI.Popups.UICommand("Search", null, 1));    
    menu.showAsync({ x: evt.screenX, y: evt.screenY }, "above")
        .then(function (cmd) {
                //handle command
        });
}

After preventing the default context menu from being shown, we start by creating the PopupMenu which will replace the default  context menu. This new context menu is populated with two UICommand instances and one separator (represented programmatically by a UICommandSeparator instance). All UICommand instances expect at least two parameters: a string which will be displayed in the menu and a callback function which will be invoked when that option is selection (which you can set to null!). Optionally, you can also pass a third parameter, which is used for setting the command identifier (in the previous example, I’ve resorted to an integer, but you can pass any object you want).

In this example, I’ve opted for using the showAsync method and for placing the menu according to the screen coordinates of the event object. Notice also that I’m passing a success callback to the then method, which will be called when the context menu is dismissed. The cmd parameter will only hold a valid value when you pick a command from the menu. When that happens, you’ll end up receiving the UICommand that has been selected by the user. You can then inspect that object and decide what you should do. The next image shows our new context menu in action:

contextmenu3

And that’s it for now. Stay tuned for more about Windows 8 Metro dev.

Jan 11

According to the docs, the Flyout control allows us to add lightweight popups which relate to what the user is currently doing. Creating a flyout is a simple operation which evolves a couple of steps:

  1. create the HTML snippet shown by the flyout;
  2. create the Flyout control and associate it with the HTML snippet created in step 1;
  3. control the dismissal of the flyout and perform a specific operation when the flyout is dismissed (if required).

To illustrate its use, let’s build a simple app which shows a flyout in response to a button click.  Here’s the HTML snippet responsible for the button and for the contents presented by the flyout:

<p> 
 <input type="button" value="show Flyout" id="showFlyout" /> 
</p> 
<div id="flyout" data-win-control="WinJS.UI.Flyout">
 <div>Your account will be charged!</div>
 <input type="button" id="confirmFlyout" value="Confirm" />
 </div>
<div id="info"></div>

The info div is used for showing a message which explains how the flyout was dismissed (since flyouts can be dismissed by just clicking outside them, we’ll be using this div to show a message which says how the flyout was dismissed). Notice that we don’t need to hide the flyout by setting its display to none because it will be automatically hidden from the display when we associate it with the Flyout control that is created during the ready event:

WinJS.Utilities.ready(initializeSample, true);
var _flyout = null;
function initializeSample() {
 WinJS.UI.processAll()
 .then(function () {
 _flyout = WinJS.UI.getControl( document.getElementById("flyout")); 
_flyout.addEventListener(
 "afterhide", performFlyoutAction, false);
 });
 document.getElementById("confirmFlyout").addEventListener(
  "click", confirmFlyoutDlg, false); 
 document.getElementById("showFlyout").addEventListener(
 "click", showFlyout, false); 
}

The initializeSample function will only be called after the DOMContentLoaded event has been fired. Internally, the ready method will resort to a Promise in order to execute the initializeSample callback. If you prefer, you can still rely on the DOMContentLoaded event to run your initialization logic.

After initializing all the controls defined in the HTML document (notice the WinJS.UI.processAll method call), we initialize a global variable with a reference to our Flyout control and set up an event handler which will be called in response to the afterhide event (this event is raised by the flyout after is has been fully hidden). You’ve probably noticed that we’ve hooked up the click events raised by the showFlyout and confirmFlyout buttons.

In the showFlyout button click’s event, we’re just showing the flyout:

function showFlyout(evt) {
 _flyout.show(evt.target, "top");
}

Showing the flyout requires us to pass an anchor control (in this case, we’re passing it the object responsible for raising the event) and specify it’s relative position to the anchor control (in this case, we’re showing it over the button). The relative position is used as a hint and the flyout position will also be influenced by the current available space (for instance, if our button is placed at the top of the screen, then you shouldn’t really be surprised to see the flyout shown below it, event though you’ve passed top as the flyout’s relative position).

The confirmFlyout’s click event handler will only be called when the user clicks over the button shown by the flyout. Since flyouts can also be dismissed by just clicking outside of them, then we’ll use this event handler to change the value of another global variable (_flyoutConfirmed) before closing the flyout:

var _flyoutConfirmed = false;
function confirmFlyoutDlg() {
 _flyoutConfirmed = true; _flyout.hide(); 
}

We’ll be using this global variable from within the flyout’s afterhide event handler to see if the flyout was dismissed because the user clicked outside of the flyout or because the user clicked in the confirmFlyout button:

function performFlyoutAction() {
 document.getElementById("info").innerHTML = 
 _flyoutConfirmed ? "YES" : "NO"; _flyoutConfirmed = false; 
}

In this example, we’re just writing yes or no to a div, but you can easily adapt the code to start some action in response to a flyout’s button click. Notice that we’re also reseting the _flyoutConfirmed variable so that future flyout dismissals are correctly processed

Besides the methods and events shown in this small example, the Flyout control exposes others properties, methods and events. You can find more info about them in the online docs.

And that’s all for now. Stay tuned for more.

Jan 09

Windows 8 adventures: playing with the Tooltip control

Posted in Windows8       Comments Off on Windows 8 adventures: playing with the Tooltip control

The Tooltip control is one of the new controls introduced by WinRT JavaScript API. After looking at the docs, I’ve decided to see how I could use it in a real world scenario. Since it’s a Windows 8 control, I knew that I could instantiate it by applying the win-data-control attribute to a div (and, of course, don’t Forget to initialize the controls by calling WinJS.UI.process/All method):

<div data-win-control="WinJS.UI.Tooltip" 
data-win-options="{placement: 'right'}"> 
 Testing another tooltip 
</div>

The placement property is used to hint the place where the tooltip should be set (it accepts the strings top, left, right and bottom). Now, the next step is understanding how we can associate the tooltip with an existing control. After checking the property list, I didn’t find any property which would let me associate the tooltip with an existing control. I did, however, find an innerHTML property, that can be used for setting the HTML shown by the control. And that’s when I thought about putting the Tooltip’s associated control inside the Tooltip’s div:

<div data-win-control="WinJS.UI.Tooltip" 
 data-win-options= 
 "{placement: 'right', innerHTML: 'Testing another tooltip'}"> 
 <input type="button" value="This is a simple button" /> 
</div>

And sure enough, it worked: putting the mouse over the button is all that it takes to see the custom tooltip:

simpletooltip

Well, the tooltip is shown, but the results aren’t probably the one you’d expect since you’re probably expecting to see the tooltip being presented besides the button. If you think about it for a minute, then the problema is rather obvious. By default, div’s display is set to block and that means it’ll occupy a whole line, relegating the tooltip’s text to the next line. One possible solution is chaning the div’s display CSS property by using a CSS class rule:

.tooltip { display: inline-block; }

And then, we need to apply the class to the tooltip’s div:

<div data-win-control="WinJS.UI.Tooltip" 
 class="tooltip" 
 data-win-options=
 "{placement: 'right', innerHTML: 'Testing another tooltip'}"> 
 <input type="button" value="This is a simple button" /> 
</div>

And then, everything works as expected:

toolti

If you want, you can also define the HTML shown by the tooltip in another HTML element. In order to do that, you need to set the contentElement property. Here’s how you can do that:

<div data-win-control="WinJS.UI.Tooltip" 
 data-win-options= 
 "{placement: 'right', innerHTML: 'Testing another tooltip'}"> 
 <input type="button" value="This is a simple button" /> 
</div> 
<div id="contentTooltipContainer"> 
 <div id="contentTooltip"> Just a simple toggle button... </div> 
</div>

Notice that I’m wrapping the HTML element which is used by the Tooltip in a another div so that I can hide it from the UI (by applying a CSS rule which targets the contentTooltipContainer ID). If you don’t do that, the div’s content will be shown in the UI. Looking at the docs, there’s another important property which needs some explaining: I’m talking about the infotip property. When you set it to true, you’re saying that the tooltip should be displayed for a little bit more time than usual. This is a good option when you have more than one line of text or when you need to worry about the finger occlusion problem (setting infotip to true requires a longer holding time before it appears, and once it’s opened, the underlying item will not be activated when the user lifts his or her finger). Here’s the result I’ve ended up with:adjustingtooltip

Before ending, there’s still time to mention the existence of the HTML title attribute. If you’ve been doing Web development, you probably know that you can add a tooltip by setting the title attribute. However, creating a tooltip by setting the title attribute is a rather limited approach. For instance, you can only pass it text and you have no multi-touch support. Whenever you need any of these options, you should rely on the Tooltip control.

And that’s it for now. Stay tuned for more.

Jan 05

Windows 8 adventures: getting external data from a local server might not be as easy as you expect…

Posted in Windows8       Comments Off on Windows 8 adventures: getting external data from a local server might not be as easy as you expect…

After a couple of days playing with the Windows 8 controls (more about them in future post), I’ve decided that it was time to see how to get remote data through the WinJS.xhr helper. To make things really simple, I’ve decided to create an HTML page on the server which would be obtained through WinJS.xhr helper. I’ve ended up with the following code on my WinRT page’s DOMContentLoaded event:

document.addEventListener("DOMContentLoaded",
 function (e) {
  WinJS.xhr({ url: http://localhost/samplepage.html })
 .then(handleResponse, handleError); },
 false);

The WinJS.xhr method expects an anonymous object which you can use to set several of the parameters associated with remote call (notice that his call ends up being performed by the XMLHttpRequest object). In our simple example, we’re only setting the URLfor the call (according to the docs, you can also set several other parameters)

The WinJS.xhr method returns, once again, a Promise objet. In this case, the handleReponse method will be called when everything runs without any glitches. If there are any problems, the WinRT runtime ends up calling our handleError method. In this case, both methods end up receiving an instance of the XMLHttpRequest object used for performing the call.

The first time I’ve ran my demo app, it took a while until… my error handler got called. Initially, I thought that the URL was wrong, so I’ve copied it and pasted it into the URL address of Chrome. Nop, there was nothing wrong with the HTML. So, I’ve went ahead and I’ve searched the forums and started emailing some guys. After some time, I got lucky and I’ve found this post. Tiago also gave me a hand by explaining that there was a difference between the local vs. Web context difference. It was only a matter of time until finding the checknetisolation tool.

According to the docs, localhost access is forbidden for security reasons and that means you’re into trouble when you’re developing apps which access local services. And that’s where this tool comes in: you can use it to create a rule which relaxes the WinRT localhost loopback restriction. To create a new rule, you must run the following command:

checknetisolation loopbackexempt –a –n=your_app_name

Alternatively, you can pass your app’s SID (in that case, you –p instead of –n), but I think that using your app’s name is easier. This brings us to the next question: what’s the name of my app? It turns out that the easiest way to get your app’s name is to open the manifest and copy the value of the Package Family Name entry in the Packaging tab:

manifest

Now, running the following instruction is all that you need to get that loopback restriction removed for our win8tests app:

checknetisolation loopbackexempt –a –n=win8tests_t2ggmrgk4m9fg

Before going on, we should always use the –s option to see if everything went well:

checking

As you can see, our rule is in place and everything should work out just fine…say again? are you sure? Unfortunately, it wasn’t working out fine…I was still getting the timeout and the error function that I’ve passed to the Promise object was still being called.

In despair, I’ve went back to the initial post and asked if there was anything I was missing. And the answer was yes, there was: I hadn’t opened port 80 on my firewall. It seems like WinRT xhr calls are always “served” as remote calls and they were being blocked by the firewall. After opening the HTTP 80 port (inbound rules), everything started running smoothly!

firewall

Btw, one extra note: if you’re trying to get a resource from an intranet machine, then you’ll probably need to require Home/work Networking capability in your manifest.

And that’s it for now. Stay tuned for more.

Jan 04

Windows 8 Adventures: Oh my god, it’s so easy to debug JavaScript apps!

Posted in Windows8       Comments Off on Windows 8 Adventures: Oh my god, it’s so easy to debug JavaScript apps!

After installing the Windows 8 Developer Preview With Developer Tools, I’ve finally managed to debug my JavaScript applications. Hurray and hurrah!!! And I must confess that the experience is really good!

Even though I’ve been using Windows 8 for some time now, the truth is that the Widows 8 Developer Preview version I’ve decided to install at the time didn’t allow me to build Metro Style apps nor to debug existing applications (btw, I’ve decided to go with that version because it was the only one which allowed me to upgrade from Windows 7 and, at the time, the page didn’t mention that you could only only build Metro style apps from the Developer Tools version).

Back to business: so, what do we get when we debug a Windows 8 Metro JavaScript app? We get *all* the goodies we’re used to when debugging HTML+JS pages. Ok, here’s a screen capture which shows VS2011 running a debug session:

debugging

As you’d expect, you can add breakpoints to your JavaScript code and you can check the values of your objects by looking at the traditional watch and locals windows. You can also navigate through the current stack trace (and this means you inspect the Win RT JS code which ends up calling your functions). JavaScript developers will also notice the existence of the console window, which allows you to inspect your code or run JavaScript code.

Even more interesting is the DOM Explorer window (which you can see in the first tab). The next image shows that window in detail:

domexplorer

Yep, you have total access to the DOM used by your Win 8 Metro JavaScript! You can see the styles which have been applied to an element and you can even change them. If you’ve got a dual monitor system, you can even see where each HTML element is on your app’s UI:

all

This should be a really huge help for building those nasty layouts. Btw, if you’re building an app for several devices, then you’ll probably be happy to know that you can use the simulator. To use the simulator, you must change the default properties of your project (to access the dialog, right click your project in Solution Explorer and choose the properties option):

simulator

After setting the debugger to launch dropdown to Simulator, you can simply hit F5 and you’ll end up with the simulator. Even though the simulator takes some time to start, it’s well worth it because you’ll end up with an environment where you can change the current screen resolution, change the way you interact with the app (mouse vs. touch) or even change the current orientation of your screen:

simulator2

This should be really useful for everyone who needs to build an app for several devices and is stuck with a PC (like me!).

And that’s it for now. Stay tuned for more.

Jan 03

Windows 8 Adventures: setting properties from the HTML

Posted in Windows8       Comments Off on Windows 8 Adventures: setting properties from the HTML

Yesterday I’ve started playing with the Windows 8 developer bits and I’ve decided to follow the JavaScript online docs. Windows 8 introduces lots of new things, but I’ve decided to start simple. It didn’t take long until I got into trouble though…One of the first controls that got me into trouble was the TimePicker control. The quick start docs are enough to start working with most of its features. And everything was fine, until I’ve tried running this code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Win8Tests</title>
    <!-- WinJS references -->
    <link rel="stylesheet" href="/winjs/css/ui-dark.css" />
    <script type="text/javascript" src="/WinJS/js/base.js">
</
script> <script type="text/javascript" src="/WinJS/js/ui.js">
</
script> <script type="text/javascript" src="/WinJS/js/binding.js">
</
script> <script type="text/javascript" src="/WinJS/js/controls.js">
</
script> <script type="text/javascript" src="/WinJS/js/res.js">
</
script> <script type="text/javascript" src="/WinJS/js/animations.js">
</
script> <script type="text/javascript" src="/WinJS/js/uicollections.js">
</
script> <script type="text/javascript" src="/WinJS/js/wwaapp.js">
</
script> <!-- Win8Tests references --> <link rel="stylesheet" href="/css/default.css" /> <script src="/js/default.js"></script> </head> <body> <div id="timer" data-win-options="{current: '12:15', disabled: true}" data-win-control="WinJS.UI.TimePicker"> </div> </body> </html>

Before talking about the problem, lets try to understand what’s going on here…

I’ve started by adding several (probably all?) of the client JavaScript libraries which will let me use the Win RT API from JavaScript (notice that I’ve included more libraries than needed for this small demo, but at least I know that all the required libraries have been included and I’m not missing any script reference). If you’ve just started looking at Windows 8 HTML code, then you’re probably wondering why we have all those data-XXX attributes applied to the div.

In the previous example, they’re used for transforming a simple div into a Windows 8 TimePicker control. You see, if you choose to build an Win RT app with HTML and JavaScript, you can reuse most (if not all!) of the traditional HTML controls. But there’s more: you can also use the new Windows 8 controls. One of the options for instantiating these controls is to apply the data-win-control attribute to a div and specify the type of control that should be created (in the previous example, we’ve used the WinJs.UI.TimePicker control). Notice that opting for this strategy means that you’ll need to call the process or the processAll method from your JavaScript code. I’ve decided to call the processAll method from the DOMContentLoaded event:

document.addEventListener("DOMContentLoaded", function (e) {
    WinJS.UI.processAll();
});

Alternatively, you can instantiate a control from your JavaScript code, but we’ll leave that for a future post. Going back to our HTML code, it shouldn’t be surprising to discover that the data-win-options attribute is used for initializing the properties of the control from the HTML markup. In our example, I’m trying to disable the control and set the time to 12h15. The problem is that I was always getting the default 12h00 time (btw, if you don’t set any value, you’ll end up with the current time):

timepicker

hum…what’s going on here? Shouldn’t this work? According to the docs, string properties can be wrapped in ‘ ‘ and it should work without any glitches. Unfortunately, the problem was rather simple: it’s a limitation of the current build and “You can always use the standard American English in this release”. And yes, changing the way date, time and number are formatted (in the regional settings of the control panel) solved the problem. Anyways, I’m living in Madeira (still part of Portugal, I believe – sorry, local joke :)), so I really want to see my data formatted in Portuguese. So, how can I solve this problem without changing the locale? Well, one solution to the problem is to work with the Promise object that processAll returns. Here’s a modified version of the JavaScript I’ve used initially:

document.addEventListener("DOMContentLoaded", function (e) {
    WinJS.UI.processAll()
                .then(initializePicker, Error);
});
function initializePicker() {
    var picker = WinJS.UI.getControl(document.getElementById("timer"));
    picker.current = new Date(2012, 3, 1, 12, 15);
}

One of the interesting concepts of Win RT is that most operations that “take time” are asynchronous. processAll must go through all the DOM and initialize all the Windows 8 controls it finds. That’s why it’s an async operation and, like all asynchronous operations, it ends up returning a Promise object. After getting a Promise object, we can configure it to invoke a callback method when the encapsulated operation is done. In our case, we’re also passing an error function that should be invoked if the “encapsulated” operation generates an error (notice that we can still pass one additional function, that would be called for progress feedback). Our initializePicker function is rather simple: we’re getting a reference to the Windows 8 control (notice the WinJS.UI.getControl method) and creating a new Date object (with the correct time) that is used for initializing the TimePicker’s current property.

And that’s it for now. Stay tuned for more!

Sep 15

More thoughts about the new UI user experience

Posted in Windows8       Comments Off on More thoughts about the new UI user experience

After playing a little bit more with the new Windows 8 preview, I’m a little more used to the new metro UI. I’ve already removed all the default crap (oops, applications…that’s what I meant) and I’ve added shortcuts for most of the apps I use daily. I’m still trying to figure out how to place a shortcut for a folder or an application which works in “xcopy mode”…I’ll probably have to write some code for that, but I’ll need to dig a little more before being sure.

I do like the new Windows taskbar. It’s really great to be able to see the app icon in the correct screen. Another thing which I like is the new explorer window. Now it comes with a ribon…I’ve heard several complaints about it, but the truth is that I like it. btw, it brings some new things out of the box. For instance, now you can open the cmd from the folder you’re viewing (check the next image). To be honest, I’m a little surprised there’s no power Shell shortcut (come on, this is 2011 and we all love power shell, right? Smile).

explorer

The task manager is another app which has seen several improvements. When you activate the more details window, you’ll end up getting a fair ammount of info presented in a very useful way. For instance, there’s a users tab where you can see the apps associated to each user that is logged in to the machine. Another nice detail is the new copy dialog.

taskmanager

Another interesting improvemente is the new copy file dialog. As you can see in the next image, now we are faced with a graphic which show the corrente throughput. Even better: we can pause the current copy operation (notice the small icons on the top right corner of the dialog windows).

copydialog

Another good news: there’s an out of the box mount option for ISO images (almost sure it wasn’t here before)…There surely more, but I’ll leave it for future posts. Stay tuned for more.

Sep 14

Windows 8 first impressions

Posted in Windows8       Comments Off on Windows 8 first impressions

I’ve decided to use it in my home machine…couldn’t resist it, you know Smile

The first impressions are positive, though I’m not sure if this metro thingy is something I want to use in my day to day work. I would really be glad to end up with slick and fast UI + tools. After all, I’m a  dev, not a game player. So, how do I turn it off? If there’s a way, please share it with me Smile

There’s one thing that pissed me: no more Windows menu (you know, the one that was shown when you hit the windows key…). So how do I hibernate my pc now? I’ve already changed the default power plan and I’ve added the hibernate option to the shut down options menu…but that menu is no longer available and the window key will redirect you between the desktop and the metro UI. The only way I managed to see this shut down options was when I hit ctrl+alt+del and stumbled upon a power off icon…oh well, let’s see how things go after using it for another day…