Aug
27
2013

Windows Phone Emulator: Hyper-V isn’t on

I attribute this entire blog post to Scott Kerfoot who provided these instructions to me Smile

If you should stumble upon this dialog box…

clip_image001

…  you should then click the ‘Turn on Hyper-V’ link.  The Windows Features dialog box will then appear as seen here:

clip_image001[6]

Notice that Hyper-V is not selected. To enable it, select the box next to it, and click OK. You will now be required to re-boot.  After rebooting, attempt to run the emulator again. Hopefully this was successful for you.  However, you may encounter the following dialog box:

clip_image001[8]

If you get this error, select the ‘Join the Hyper-V Administrators security group’ option and click Retry.  You will now need to log off and log back on again for security permissions to take effect.  Try running the emulator again.  Hopefully you have success and are ready to develop!  One way or another, please leave a comment here if this information was helpful, or if you have additional information to provide.

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Sep
27
2012

JavaScript for Windows Store Apps: Error Handling

Are you confident you are writing your JavaScript code error free?  Do you wonder if traditional JavaScript error handling techniques still apply when developing for Windows Store apps?  Does the Windows Library for JavaScript provide additional support for error handling?  Do you deal with errors differently when writing asynchronous code?  This entire post is dedicated to addressing these questions!

To Err is Human

Let’s be clear – if you were perfect and could write code that never fails, you would not need to read any further. For the rest of us (which is all of us), we must acknowledge that errors very often creep into code.  Furthermore when developing with a language that is not strongly-typed such as JavaScript, there is potential for even more errors.  Why? Consider the following code:

var x = 4;

// somewhere else in code...
x = "four";

The above code is valid.  It showcases the dynamic nature of the language. However, it also illustrates the potential confusion as to what the variable x is. Any misuse of x based on assumptions could lead to buggy behaviors.  One way to minimize these kind of issues is to be consistent with variable assignments with regard to inferred type. In other words, if a variable is assigned to a string, keep it a string.

Syntax errors are typically reported through Visual Studio when running the application in debug mode.  However, the error message may not clearly state what is needed for correction.  For example, observe the following syntax error:

varr x = 4;

Isolated from all other lines of code, it is easy to see that the keyword var was misspelled. Yet the IDE reports the error at runtime this way:

javascript critical error

An entry level scripter could debate that there is a ‘;’ at the end of the line, and rationalize the error message itself is erroneous.  The moral of the story here is to examine the complete line of code and surrounding context for discrepancies when the reported error message is not clear.

For web developers who are bringing their JavaScript skills over to Windows Store app development, the use of try…catch…finally statements are fully supported and should be used when attempting to execute any line of code that is conditional to a successful outcome – such as accessing external resources.

Mistrust is a Virtue

I find it a little humorous that the uninitialized use of WinJS.log (a method for logging error information among other things) will cause an error to be thrown at runtime.  The log method can be initialized with WinJS.Utilities.startLog (for logging to the JavaScript console) or assigned to a custom method with logging behaviors defined by the developer.  A straight call to the log method without initializing will cause following:

JavaScript runtime error: Object doesn't support property or method 'log'

Of course, when the log method is initialized - no errors are reported.  However, consider a scenario where settings in the application determine whether the log method will be initialized or not.  In that case, what is a safe way to call the log method?  Some might create a global variable that could be used in an if statement to see if logging is enabled before every call.  That will work, but there is another way.  Consider the following code:

WinJS.log("Risky", "demo", "info");
WinJS.log && WinJS.log("Safer", "demo", "info");

The second line of code is “safer” because it starts with a check to see if the log exists.  The term “safer” is used instead of “safe” because by saying log “exists” what that really equates to is that it is not one of the following: null, undefined, an empty string, or a numeric value of zero.  Even so, it is still safer to use the logical && operator (no if statements needed) because it will exit the statement immediately when a false value is returned.

There is another technique using the || operator which can help reduce errors by producing a default value if one is not provided.  In the following code, the name parameter is given a value if none were already assigned:

function echoName(name) {
    name = name || "John Doe";
    return name.toUpperCase();
}

The above code will produce the following output:

echoName();             // JOHN DOE
echoName("M Palermo");  // M PALERMO

So far so good, but what if the following call is made:

echoName(4);

Passing in a non-string value causes the following error:

JavaScript runtime error: Object doesn't support property or method 'toUpperCase'

To prevent unwanted errors like this, there needs to be a guarantee that the method is safe to call. One way to do so is by using an approach mentioned previously - as seen here:

if (name && name.toUpperCase) {
    // safely call name.toUpperCase();
}

At other times it may be more preferable to simply confirm what type it is.  A common way to accomplish this is to use the typeof operator which returns a string declaring what the underlying type is as seen here:

var x;
(typeof x === 'undefined') // true

x = 4;
(typeof x === 'number')    // true

While typeof performs as expected in most cases, there are other times it may resolve types different than we could, as seen here:

(typeof 'abc' === 'string')             // true
(typeof new String("abc") === 'string') // false – type is object

In order to determine the actual type value, consider implementing a helper function like the one demonstrated here:

function isTypeOf(o,t) {
    if (t && t.charAt && t.charAt(0)) {
        return (Object.prototype.toString.call(o) === "[object " + t + "]");
    } else {
        throw new WinJS.ErrorFromName("args", 
            "'t' required and must be a string.");
    }
}


isTypeOf("abc", "String");             // true
isTypeOf(new String("abc"), "String"); // true
isTypeOf(4);                           // error thrown

The isTypeOf function first checks to see if the t parameter has a value, that the value has a charAt method, and that a call to charAt(0) will not return an empty string. If all conditions are true, the function returns a value based on the comparison of t and the type exposed from Object.prototype.toString.call.  Note that if the t parameter is not provided or not a string, an error is thrown using the WinJS.ErrorFromName factory method which is an easy way to create an error object based on name (error type or category) and message.

So why throw an error?  Doesn’t that defeat the purpose of preventing problems in the first place?  In the above example, the error is thrown from inside a helper function. Because this function could end up in a reusable library, it is a methodology for communicating it is being misused to application level code.  With that understanding, you will likely spend far more time handling errors in the application level code vs. throwing them.

The main message up to this point is to take preemptive strikes in your code to minimize errors as much as possible.  Now what about the errors that went unhandled?

Leave Nothing Unhandled

For all the unknown errors that could happen in your application, there is a simple way to catch them all in one place. The WinJS.Application object has an onerror event that traps all unhandled errors in one place.  Because error could happen at any time, this should be hooked to an event handler as soon as possible in the application lifetime.  Most of the JavaScript project templates for the Windows Store contain a default.js file where application initializing occurs.  Near the top of that file, you can add an event listener for unhandled application errors like seen here:

(function () {
    "use strict";
    
    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var nav = WinJS.Navigation;

    app.addEventListener("error", function (err) {
        var md = Windows.UI.Popups.MessageDialog;
        var msg = new md(err.detail.message, "Ooops!");
        msg.showAsync();
        // return true; // only if error is handled
    });

    [remaining code...]

})();

If an unhandled error happens anywhere in the application, the above listener function gets called.  A message is displayed to the user indicating the details of what has occurred, and then the app stops. The app terminates because the error is still considered unhandled. Returning true from the error handler communicates to the system that the error has been handled and is ok to continue.

Unhandled errors can also be caught at the page level while the page is processing.  This is especially easy to do when using WinJS.UI.Pages.  The following code is an example of how to add an error event listener for the PageControl instance within the define method:

WinJS.UI.Pages.define("/pages/errors/errors.html", {
 
    error: function (err) {
        WinJS.log && WinJS.log(err.message, "demo", "error");
    },

    [remaining code...]

});

It is worth repeating that this event only fires if an unhandled error occurs during the initial processing of the page. Therefore, unhandled errors that occur in after the processing of a page (in a click event for example) will be directed up to the application level for inspection.

When Promises are Broken

Promises allow for asynchronous code, and because this introduces it’s own level of complexity, it is important to know how to handle errors when using them. In order to appreciate the different options available, consider the following example of a custom promise:

function doAsync(msg, limit) {
    return new WinJS.Promise(
        // c complete, e error, p progress
        function (c, e, p) {
        msg = msg || "no-msg";
        limit = limit || 3;
        var seconds = 0; 
        var iId = window.setInterval(function () {
            try {
                seconds++;
                if (msg === "fail") {
                    throw new WinJS.ErrorFromName(
                        "promise", "Muhahaha!");
                }
                p && p(msg + ": " + seconds.toString());
                if (seconds > limit) {
                    window.clearInterval(iId);
                    c && c(msg);
                }
            } catch (ex) {
                window.clearInterval(iId);
                e && e(ex);
            }

        }, 1000); // repeat every second, stop at limit
    });
}

The doAsync function defined above is a custom promise.  When called, it allows a message (provided into the function via the msg parameter)  to be used after a number of seconds (determined by the limit parameter) passes by.  When the time limit is reached, the “complete” function(represented by c parameter) is called.  A “progress” function (represented by p parameter) is called every second, allowing the application to potentially update the UI.  And if any errors occur, the catch block passes the error into an “error” function (represented by e parameter).  If the value of msg equals “fail”, an error is thrown.

The following code demonstrates all the helper methods that will be used when calling the doAsync function:

function doComplete(msg) {
    WinJS.log && WinJS.log(msg + ": complete", "demo", "info");
}

function doProgress(msg) {
    WinJS.log && WinJS.log(msg, "demo", "info");
}

function doError(err) {
    var msg = "undefined error";
    if (err) {
        msg = err.detail;
        if (!(msg && msg.message))
            msg = err.message || "err type unknown";
    }
    WinJS.log && WinJS.log(msg, "demo", "error");
}

Each function calls on WinJS.log  to display data. Now here is the code that brings them all together:

doAsync("promise", 4) // doError not called
    .then(doComplete, doError, doProgress);
    // final call was to doComplete function

doAsync("fail", 4) // doComplete not called
    .then(doComplete, doError, doProgress);
    // final call was to doError function

In each call to doAsync above, a message is passed in, and the duration of the asynchronous call will be limited to 4 seconds.  Each second that ticks by will cause the doProgress function to be called. If all goes well when the 4 seconds are up, the doComplete function is called.  However, if the promise encounters an error, the doError function is called instead.

Promises can be chained together to allow one asynchronous call to invoke the next when completed.  When chaining promises together, put the error handler only in the final link of the chain – the done method.  Here is an example of chaining promises using the doAsync function:

doAsync("chain(1)", 4)
    .then(function (msg) {
        doComplete(msg);
        return doAsync("fail", 4);
    }, null, doProgress)// null passed in for error
    .then(function (msg) {
        doComplete(msg);
        return doAsync("chain(2)");
    }, null, doProgress)// null passed in for error
    .done(null, doError);
    // doError only needed in done method

In the promise chain above, when “chain(1)” is complete it calls on “fail”.  Since “fail” will cause an error to be thrown, “chain(2)” is never called, and processing is directed to the doError function passed into the done method of the chain. 

Promises can also be joined together too.  This allows multiple asynchronous calls simultaneously, but allowing a method to be called when all the joined promises complete.  When handling errors in this scenario, do the following:

var promises = [];
var i = 0;
// each promise has an error handler
promises[i++] = doAsync("2seconds", 2)
    .then(doComplete, doError);
promises[i++] = doAsync("fail", 8)
    .then(doComplete, doError);
promises[i++] = doAsync("3seconds", 3)
    .then(doComplete, doError);
// join promises
WinJS.Promise.join(promises)
    .done(function () {
        doProgress("all promises completed");
    }, doError);

Unlike chaining, joined promises should have their own error handlers.  If a failure happens in one of the promises, it will not stop the others in the join.

On a final note regarding promises, an error handler can be attached to WinJS.Promise.onerror. Do this as a safety net in addition to the methodologies covered so far.

End Gracefully

In summary, remember these useful guidelines and tips while you are writing your Windows Store app with JavaScript:

  • Errors happen – even in your code.
  • Error messages can be vague, so examine the context of suspicious code!
  • Trusting that your code should work is a bad idea.
  • Avoid common pitfalls by implementing a good type-checking strategy.
  • Handle the unhandled at the application level and page level.
  • Use error handlers appropriately when dealing with promises.

If you have not done so already, make sure you are getting all the latest resources by creating a profile at Generation App!!!

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Mar
29
2012

Unable to Activate Windows Metro Style Application

If you receive the following error in Visual Studio…

“Unable to activate Windows Metro style application”

… or a similar error in Blend…

“Unable to activate application --- on the Local Machine”

… the quickest fix is to delete the contents of the bin directory and rebuild the project.

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Jan
12
2012

How to Start in Safe Mode using BitLocker

Here are the steps you need to take if you need to start your Windows OS in "Safe Mode" when the drive is protected with BitLocker.
  • First, be sure you have your BitLocker recovery key handy. This is NOT your PIN. This is a LONG series of numbers.
  • Before the screen appears prompting for the BitLocker PIN, press [F8] (maybe repeatedly).
  • If you pressed [F8] early enough, you will get a warning message as seen here:
  • After supplying the BitLocker recovery key, you will be prompted with booting options, including the various safe modes.
    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Jun
27
2011

PowerPoint Crashes When Typing in Windows 7 BootCamp

If you have searched the internet looking for a reason why PowerPoint crashes when you start typing anything, and you happen to be running in Windows 7 via BootCamp on the Mac, the fix is simple:

In Control Panel, click on “Change keyboards or other input methods”:

changekeyboardinput

In the Region and Language dialog box, click on the Change keyboards… button:

regionlanguage

Finally, add the English US Keyboard by pressing the Add button:

USKeyboard

That’s it!  Seems odd, but it works!

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Mar
30
2011

How to Fix/Repair iPhone With Water Damage

iphone3A certain person I know recently washed her iPhone in the washer machine.  I love this person, but I will preserve her dignity and not mention her name.  That said, despite how smokin’ hot she is, she does occasionally do things that reflect a slip in judgment.  Of course, washing the iPhone was a mistake, and she realized it when it dropped to the floor moving items from the washer to the dryer.

I was travelling at the time I heard about the ‘tragedy’, so when she called from the home phone to explain what happened, I was worried if she already did the big “No! No!” – attempting to turn the phone on to see if it was working.  It was no surprise that she did, so I asked her not to do that anymore.  I recommended to her to store the iPhone in a bowl of rice until I returned to Phoenix to see it for myself.

When I finally got my hands on the phone (one day after the ‘incident’), I took the sim card.  I got a blow dryer out and kept hot air on the phone while I gently shook it.  About 5-10 minutes later, a few drops of water started seeping from the speakers on the lower part of the iPhone.  I did the drying process for about 30 minutes, then put the iPhone into a zip-lock bag of rice.  I left it in there overnight.  The next day, I repeated the drying process again and about 10 more drops of water came out.  This amazed me because now it was 2 days after the ‘incident’.  After about 30 minutes, I put the iPhone in a fresh zip-locked bag of rice and left it in there for 12 hours.

By the time I pulled the iPhone out again, the drying process yielded no drops of water.  I put the sim card back into the phone and plugged it into the wall charger.  Keep in mind I have yet to press any buttons since the owner first tried to turn it on when it fell out of the washer machine.  To my delight, the faint glow of the charge screen appeared.  I left it charged in for several hours.  Finally, I turned the phone on.

The phone was barely functional.  The screen was extraordinarily dim.  After continued use over a day, the phone began to switch back and forth between a dim screen to a bright screen.  All the apps are working, and the phone worked as well.  Although an odd “smudgy” haze appears over 25% of the screen, the iPhone has come back to life.  It is my first recorded miracle :-)

Steps I recommend if you have water damage to your iPhone:

  • Upon discovering your iPhone has water damage, DO NOT TURN IT ON.
  • Remove the sim card and its little plastic holder (at top of iPhone) and keep in a safe, dry place.
  • Immediately dry the iPhone of all external water with a dry cloth.
  • Get a blow dryer and keep a steady low heat on the iPhone while gently shaking the iPhone to and fro.  Keep an eye out for any drops of water that seep out – possibly at the bottom of the iPhone near the speakers.  Do this process for at least 20-30 minutes.  This step is known as the DRYING PROCESS.
  • When finished, exercise self-control and put the iPhone that you believe to be completely dry from the previous step in a zip-lock bag of dry rice.  Leave in the bag for at least 12 hours.  This step is known as RICE STORAGE.
  • Every 12 hours do the DRYING PROCESS.  If *ANY* water seeps from the iPhone during this process, continue to RICE STORAGE when finished drying.
  • If during the DRYING PROCESS no water comes out (after 20 minutes or so), you can put the sim card back into the iPhone and plug the phone into a charger.  DO NOT PRESS THE POWER BUTTON to turn it on, just plug it in.
  • After a few hours of plugging in the iPhone, disconnect and attempt to use the phone.  If the screen is so dim you can barely see it, at least take a moment to congratulate yourself that there is a dim screen at all.  You have accomplished a mini-miracle.
  • Over time, your phone may behave oddly.  You just resurrected it, so cut it some slack.  As in the case of the beautiful woman in the story above, the bright screen may return and flicker out from time to time. 

I hope this post helps someone out there.  As for the cute little lady I helped in this post, she at least has her phone until she gets out of contract – a new Windows Phone 7 in her future perhaps?  After all, she is married to a Microsoft Developer Evangelist.  But I dare not reveal who she is.

Anyway, if this post was helpful, please post your story!

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).

Resources

Archives

Team Blogs

Download OPML file OPML