DCSIMG
Anger Oriented Programming

Anger Oriented Programming

Software development blog about .NET, Windows Phone, Silverlight, WCF and Zen.

Passing Windows Phone Certification – The Back Button

Tip #2: How not to break Windows Phone certification rule No. 5.2.4 – Use of Back Button.


So this is a rather common one, mostly because developers don’t take the hardware keys into consideration when developing an application, or on the contrast use them incorrectly. 

Basically what it means is: Make sure the Back Button does what it’s supposed to do: Navigate Back. No matter what your application does, no matter how many transitions occur, the back navigation needs to be fluid, logical and uniform with all other application on the platform.

 

Windows Phonw Hardware Buttons

 

Getting back to scratch:
At any point during the lifecycle of your application the user might press one of the phone’s three Hardware Buttons: The Start Button, The Search Button and The Back Button.
Every device will have them as depicted in the Hardware Specifications Microsoft has set for manufacturers.

This means that when contemplating use cases for your application, these three possible events should be at the top of the list. 
It’s not as complex as it might sound, The Start and Search Buttons currently act quite the same on the developer’s side, by that I mean that you can not override their behavior (Rightfully for the Start Button, not so rightfully for the Search Button). So for these two you only need to handle the phone navigating away from your app, which for you means: Tombstoning, but more on that on another time.

The Back Button on the other hand, that fella can take a bit of abuse.
As I hinted before, the Back Button is the only hardware key out of the three that can have it’s behavior overridden.
And that’s where you meet The Good, The Bad and The Ugly.


The Good:
Overriding the Back Button is easy, it only takes 2 simple steps.
 
Step #1: On your application page register to BackKeyPress event.
You can do that from code behind, or the way I prefer to do it, in XAML.

Registering to BackKeyPress in XAML

Step #2: In code behind implement the said event handler.
In a fashion similar to this:

private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
{
   // Override the back press, actually canceling it
    e.Cancel = true;

   /*                                                     *
     *  Things to do instead of navigating  *
     *                                                    */
}

We cancel the back navigation command and execute our own logic.
Obviously implementing this event handler is purely optional, and should be avoided if not needed.

A good example for where you should use it would be to control dialogs, popups and custom messages boxes. Which leads me to…


The Bad:

Let’s say your application page presents at one point or another some sort of Popup, Dialog, Context Menu, or any other type of partial window which lays on top of the page, and will stay there until the user interacts with it.

According to Certification rule 5.2.4.3 – Back Button: Context Menus and Dialogs -If said control is presented on the page, the Back Button should close it instead of navigating back to the previous page.
How good this is considering UX is arguable, but the rules are the rules.

The way to fix this would be creating an event handler, just as we saw before, and in it checking if we have our dialog control open. If it is, cancel the back navigation and close the dialog, if it isn’t leave the back navigation to do it’s thing.
Translated into code, it will look like this:

private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)

            if (dialog.Visibility == Visibility.Visible)
            {
                // Override the back press
                e.Cancel = true;

                // Close the dialog
                dialog.Visibility = Visibility.Collapsed;
            }
}



The Ugly:

So now you know how to override the back button.
This means you can use it to do what ever you like, right?
Wrong!

To explain this, imagine the next scenario:
You’re a Facebook user right? Of Course you are. 
Now let’s say that one day the good developers at Facebook find a way to override the the browser’s navigation buttons (this by the way is very feasible using some rather simple Javascript).
So from now on whenever you’re on Facebook, clicking on the Back browser button will open the chat window, and clicking on the Forward browser button will “Like” the last post you’ve watched.  

How long do you think it will take before Mark Zuckerberg’s mail account will reach it’s storage limit after being flooded by hate-mail?
And for a good reason, this makes for a very confusing, non intuitive, user experience.

The same happens when the Back Button on the phone does something that isn’t some sort of navigating back.
As I said on my first post about Windows Phone Certification, most of the rules were made to maintain UX across the board, and this also means that all hardware buttons should more or less act the same on all applications.

Or to sum it up in Microsoft’s words:
“To maintain a consistent user experience, the Back button must only be used for backwards navigation in the application. ”

That’s it for now.
More Windows Phone Certification Tips coming. Please tell me in the comment section about certification rejections you’ve got so I’ll know what you want me to write about next.


Josef.
   

Designing Windows Phone Applications With Photoshop

AKA: How to design your own Windows Phone Application UI, using Photoshop, Expression Blend and a little touch of Magic.

Photoshop Loves Windows Phone


When it comes to being an indie-app-developer, you usually find yourself being the Jack of All Trades. You are the developer, designer, tester and marketer.
This really isn’t easy, besides being good in each of these fields,
and usually you are not, you need to familiarize yourself with various tools, each for it’s own role in creating the application.

The most confusing of all to the common developer is usually designing the application UI.
If it works well, why the heck does it also need to look good!?” Is a common thing to be heard from frustrated software developers, when given a UI design assignment.

But here is the thing, when it comes to Applications built for a mobile platform, Great UI is key for the success of an application.
It doesn’t matter how amazingly fast your app algorithms run, if they don’t come in a pretty package, No one will download it!

The good news are that together with Visual Studio and Expression Blend, Microsoft provides you with a fairly good suite for easily creating your very own beautiful Windows Phone Applications. And best of all, these tools play beautifully well with Adobe Photoshop and Illustrator.
No, they will not magically turn you into an amazing UI Designer, I’ll give you that, but they will make your life much easier.

 

So lately I have been working on a small project I call “Vintage Booth”.
Basically it’s a very simple Windows Phone Application that will enable you to take vintage looking pictures and share them with your friends.
Yes I know, it’s an amazingly original idea, patent pending.

The thing is, I’ve started this project mostly as an experiment in application UI design. I wanted to see if I could create exceptionally great application design, while not necessarily sticking to the Metro UX Concepts, and most importantly, do it all by myself.
This is the story of how I did it.
 

Creating the page design using Adobe Photoshop

The first step was creating the Application Pages (4 of them ) using Adobe Photoshop.

The native resolution of a Silverlight Windows Phone Application Page is 480x800, so I started by creating a new canvas of that size and worked my way from there on my Main Menu Page.
Ending up with this design:

Designing the Main Menu Page in Photoshop

 

Several things you should consider when designing the page:

1) Use folders to group layers that relate to the same control or part of the screen.
    As you will later see, these folders will turn into Canvas Controls in XAML.

2) Prefer using Vector Graphics and Text Layers as oppose to just using plain images.
    They will turn into Paths and Labels later, and will enable you resizing and manipulation
    without losing quality.

3) Some layer blending modes and layer styles are not supported in Expression Blend.
    You will be notified upon importing as you will later see, but you might need to merge
    and flatten some of these layers to maintain the same look.

4) If you are using 3rd party fonts, make sure you have the rights to use them.
    The same goes for all source images you are using.

 

 

Importing The Design To Expression Blend

Next I opened my already existing project that I’ve created in Visual Studio. If you don’t have one you can simply create a new project from within Expression Blend.

Next I went ahead and opened my MainPage.xaml, removed all existing controls in it, and proceeded to import my PSD file.
In the menu simply select File –> Import Adobe Photoshop File…

Expression Blend Menu For Importing Photoshop File

Next the importing window will open up displaying all the layers in the PSD file.

Photoshop Importing Window  click the image to enlarge.

Here there are several things you need to notice.
Each layer has a check box enabling you to add or remove it from the list of layers that will be imported.

In case you wish to merge several layers you can select them and use the “Merge layers” button. It is preferred to merge layers that have no reason being separated, for example in this design, the layer of the album and the layer of the images over the album.
The reason for this is that each layer will turn into an element in the Visual Tree, and this can dramatically affect performance. So basically the less layers and effects you eventually import the better.

As I said before, not all the features in Photoshop are supported in Blend.
You will be notified for this by an exclamation mark icon near the layer or folder. When hovered over, a tooltip will present the unsupported feature.

Unsupported Supported Feature Message

For now you can handle this and still maintain the looks by choosing to import the layer as a flattened bitmap.

Eventually I ended up like this:

vintage-booth-imported-in-blend  click the image to enlarge.

As you can see, all my layers have translated into images and all the folders into canvases.
Should I have imported the text layers as text and not as a flattened bitmap, I would have been able to see the text as an editable label, basically enabling me to change it in runtime.

 

Making The Design Interactive

So now you have your design and you can display it as a pretty image on the phone. Time to make it Interactive.

This can mean various things, depending on your application.
In my case I needed to make the Menu Items reactive, and this meant two things: Converting them into buttons and adding animations.

You can convert images into buttons in several ways. You can create an Image Button Control and replace the image that was created with it, while maintaining all properties. You can catch the touch events from the image control itself, or do the lazy, yet affective, thing that I did and simply place an invisible button on top of the image.

Next I added the click animations. I won’t go into details on How to create animations using Expression Blend, you can check out the link for that. But all I did was simply creating a scale change animation so that the images will create the feeling of being pressed, and attached that to the button press event.
Obviously you can do much more complex stuff, do cool animations for when the page loads, animations that run continuously in the background making it dynamic, whatever you wish.

Eventually what you will end up with is a fully functioning interactive design, that mostly does nothing. You can “Test” your design by pressing F5 to run the project.

Building the Application Using Visual Studio

Now came the inevitable part of actually creating the application.
After saving what I created in Blend I opened the Solution in Visual Studio.
At any time you can go back to Expression Blend and change the design while developing, just make sure you save your changes.
 

 

Vintage Booth in Visual Studio

I really can not stress enough the Save part.
Visual Studio and Expression Blend play beautifully together, even with source control in the middle. But if you don’t save your changes in one of them, they will not update in the other.
Not paying attention to this can cause you to override unsaved changes, and in the process lose an hour worth of work, leading to RAGE AND DESTRUCTION!
So learn from my mistakes and save often.

Besides that, this is the point where you add your code or link the pages to existing code you already have.
As you can see, if you work with other people you can actually have the code written simultaneously to creating the design, integrating the two in the end.
For doing it properly you can look at more advanced Design Patterns such as MVVM.

That’s it for now.
For questions, pointers and incoherent jibber-jabber,
please leave a message in the comment section bellow.

And until next time, don’t forget:
Beauty is only skin deep, but ugly goes clear to the bone .

Josef.  

Code Tips That Will Save Your Life #2 – Part I

Tip #2: Proper Exception Handling in .Net and in General.



I like to dissect programmers. Did you know I'm utterly insane?

Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.

You can never know when this phrase will turn into horrible reality, so you’d better be prepared!


Tip #2: Proper Exception Handling – Part 1


This time on “Code Tips That Will Save Your Life” – Exceptions.
We all know them and sadly we all have to deal with them, but are you doing it right?

To most it seems like a very straightforward thing – Try, Catch maybe Finally, that’s it.  But code with incorrectly written Exception handling can be frustrating to maintain and hard to debug on a good day, but downright dangerous on a bad one. 
  
On this two part post I will share 8 Tips that will make your code amazingly easier to maintain, not to mention log and debug, and might even make it more stable.


1. Getting Up to Scratch

As I already said on a previous post about Application Stability:
Most Software Developers Are Lazy

I still stand behind this phrase, which is the only reason I’m not skipping this tip. So lets just make sure we are all on the same page here.

Think about a piece of code you wrote lately, an algorithm, a method or a class.
Now look at this snippet:

try

       // Do amazing things
}
catch

       // Things didn't go as planned, time for plan B
}
finally
{
       // Release resources and other awesome stuff
}


Does your code follow this pattern? 
If your answer was yes, than kudos, +2 Points.
If your answer was no.. well you better have a good reason for it.

There are very few cases in which you would not want to catch rising exceptions.
Even if you don’t really have anything to do with the exception at that place in the application flow, it’s usually good practice to catch it for logging purposes, resource management and for enriching it with information about the cause of the exception.

Obviously as with any rule, there are exceptions (pun not intended).
If there really is nothing to log, and no information to add, there is no reason to catch an exception for the sole purpose of throwing it again. But make sure that is the case.

What ever you do, the most important rule for you to remember is:
Never, ever swallow Exceptions without doing anything!

Bubble them, write to log, do anything.
But make sure your catch clause is not empty, or someday, some poor sap that will need to maintain your code will have a very, very bad day.

2. Being Specific With Exceptions

Let’s put exceptions aside for a second.

Imagine yourself at the office. You are working on that very very important project your boss expected you to finish yesterday.

When suddenly your IDE crashes, leaving you with the following message:

More or less, you have nothing to grab on to. You have no idea what went wrong. More important, you have no idea how to recover all your lost work.
You are left with nothing to do but contemplate your unplanned sudden career change.

Now with that in mind, imagine yourself using or maintaining someone else's code, or maybe even code you wrote a long time ago.
Then while Debugging it you get this:

The exception’s type is System.Exception, the exception message is “An error occurred”. No inner-exception, no relevant stack-trace.

What now?
If you are lucky you have the source code or PDB files, so you can spend anything between 15 minutes to several days debugging for an answer.
If you are unlucky, and you don’t have a way to debug that code.. well good luck guessing the reason.

When writing exception handling you should always have this example in mind. You need to make sure the exceptions your code throws can be easily understood, and this is done by being specific.

Being specific means two things:

1. Always make sure the exception message is clear. 
If you can predict the reason for an exception in the code, make sure the exception you throw includes that information, and even a suggestion on how to fix it.
For example: If a specific parameter you received for a method is null, make sure you specify the exact parameter that was sent as null, don’t just throw a “Null reference exception”.

2. Use the correct type of exceptions, and use custom exceptions if needed.
Exceptions come in many flavors:
NullRefrenceException, InvalidOperationException, IOException.. and the list goes on.
Usually you will find one that is relevant for you, or at least one you can derive from. But please use the basic
System.Exception only as a last resort.


On the flip side, you should also separate different exception types when catching exceptions, using several catch clauses. Separating exceptions by type will enable you handle different exceptions differently and log them appropriately.

For example:

try
{
    RunLogicOfGreatImportance(argument);
}
catch (TimeoutException timeoutExcpetion)
{
    // Action timed out, perform retry policy
}
catch (ArgumentException argException)
{
   // Argument sent was invalid, prompt the argument creator
}
/* etc. */
catch (Exception ex)
{
    // Something else that I didn't expect went wrong, log and handle
}

 

As you can see it’s always important to finally catch System.Exception. This is in case an exception of a type you didn’t expect was thrown.

P.S: I heard some people talk about performance implications of using multiple catch blocks. That’s simply wrong and in no way an excuse to skip this good practice. For more information check out this
Benchmark on try/catch Performance.  


3. Custom Exceptions

O.K so here is the deal.
Sometimes the exceptions that are part of the .Net framework are not specific enough, or not relevant to the type of exceptions you need to throw from your code.

This is where the concept of Custom Exceptions comes into play.
Basically what it means is that you create your own Exception types by deriving from the exception types that are already in the framework.

The simplest way of doing this is using the exception snippet.
Simply click CTRL + Space and start writing the word “Exception”
 

Costume Exception Snippet for C# on Visual Studio

Select Exception from the list and press TAB twice.
What you will get is this lovely snippet of code:

[Serializable]
public class MyException : Exception
{
    public MyException() { }
    public MyException(string message) : base(message) { }
    public MyException(string message, Exception inner) : base(message, inner) { }
    protected MyException(
      System.Runtime.Serialization.SerializationInfo info,
      System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }
}

The snippet basicaly lets you select the type name prefix (leaving the word “Exception” at the end as a standard) and the Exception type it derives from (System.Exception the being default).

Now you can add whatever you want to this class.
Usually it’s good practice to add properties with more information about the exception reason, and maybe a GUID or some other type of ID for a log record regarding the exception.

To the question of “What exception type should I derive from?” there are two possible approaches:

Approach #1: Derive from the exception type that most closely matches the one you wish to create. Basically what this means is taking existing framework exceptions and making them more specific.

For example, you are writing a piece of code which needs to read a given configuration file and load it. In case the given file does not exist you want to raise an exception more specific than
FileNotFoundException, so you derive from it and create your own exception type :  ConfigFileNotFoundException.

The advantage here is that even if the person using your code doesn’t know that it throws your custom exception, he will still catch it if handling the derived types.


Approach #2: Make one main exception type for your system/application or for the current application module (for larger projects) and have it derive from System.Exception (Not from ApplicationException!).
Now have every new Custom Exception you create derive from that type.

The advantage here, is that unlike the previous approach you have all your custom exceptions deriving from one application wide custom exception type, and you can even manage them all under the same namespace.

It’s a matter of preference, I personally prefer the second approach. When working on large projects especially ones involving several developers it’s a good standard to maintain among each other. It’s also generally a good method to separate internally, exceptions that were risen by the CLR from ones that where risen by the application code. This is good both for maintenance and logging.

4. Correctly Bubbling Exceptions


Here is a little test.
Read the following 4 lines of code performing exception bubbling, that  you would usually find inside a catch block, and see if you can spot the differences (for the sake of this test “ex” is the exception instance caught):

  1. throw;
  2. throw ex;
  3. throw new MyCustomException("Exception Message");
  4. throw new MyCustomException("Exception Message", ex);


So obviously syntax-vise they are all different from each other, but what actually is the difference in what happens when they excute?

If your explanation included “Inner Exception” that’s +1 Point.
If your explanation included “Call Stack” or “Stack-Trace” that’s +3 Points.
And if you have no idea, well there is nothing to be ashamed of, but stay tuned.

These fine differences are the kind of things that even seasoned .Net developers are just not familiar with. There is little to no documentation about this, especially on MSDN, where you’d think it should be under Exception Handling Fundamentals

So let’s go over each one and understand what it does and when we would like to use it.

1. throw;

What it does: Re-Throwing the just caught exception, Preserving the Call Stack leading to the exception being caught.

When will I use it: When you wish to catch the exception only to log it or do some kind or rollback logic, but bubble the original exception with the full Stack-Trace.

2. throw ex;

What it does: Same as the last one, only this time Not Preserving the Call Stack, actually cleaning it and starting it from the current place in the code.

When will I use it: Possibly never. The only good reason I see to do this is if you want to actually hide the Call Trace leading to the exception from the person using your code.
This could be because you already logged the full trace and don’t want to have it written again to the log. Another reason is that you provide a third party DLL and don’t want the exception to reveal all your calling trace. On both cases I find the next example a better option.

 

3. throw new MyCustomException("Exception Message"); 

What it does: Creates a new exception instance, with your own exception message. In the process tossing away the call stack gathered up to this point and creating a new one. Therefore Not Preserving the Call Stack.

When will I use it: On same instances described on the previous example. Only this time you have the added benefit of having the newly thrown exception be the one you created with your own exception message.


4. throw new MyCustomException("Exception Message", ex);

What it does: Creates a new exception instance same as the last time, but this time using the caught exception as the Inner Exception.
What it means is that all the information gathered in the exception that was caught is maintained inside the newly created exception, and in the process Preserving the Call Stack.

When will I use it: Probably this is the most useful one of the lot. It gives you both the ability to maintain the gathered trace, but also add to it your own information, and if you wish, have the new exception take the form of your own custom exception type.


In any case, you should not catch an exception just so you can re-throw it, unless you have a good reason.
Among these good reasons are: Enriching or Editing the exception details, Logging, Performing rollback and resource cleanup logic and so on.


That’s it for Part I.
Part II of this post will cover: Resource Management, Multithreading, Documentation and Design Decisions regarding Exceptions.
So stay tuned.

I Hope this post helped you.
If you have any comments, questions and other relevant or irrelevant things to say, please leave a message on the comment section bellow.

Josef.

 

Previously on “Code Tips That Will Save Your Life” :
Tip #1- Code Documentation

Passing Windows Phone Certification - Correctly Working with Media

Tip #1: How not to break Windows Phone certification rule No. 6.5 – Correctly working with the Media Player.



Oh this is a fun one…
The first certification rejection I ever got was because of this one. It's a very simple rule, but not knowing of it's existence or how to abide it in code can make things tricky when you try to fix it later.

The idea is fairly basic, if the user has music playing while entering your application (via Zune or whatnot), you can't hijack the Media Player and play what you want without asking for permission first.
This is fairly logical for several reasons. For one, if you build a game, the user might want to play it while having his own music in the background.
Another scenario is this one: The user, whilst having music playing, enters your application, suddenly the music stops and the user doesn't know why, enraged with confusion the user throws his phone to the ground and breaks it.
All in all this rule is pretty effective in maintaining UX in all that regards playing music in the background, a very common use case.

What does it mean for you as a developer?
Before using any class that plays music using the media player (
Song, SongCollection, MediaElement, etc.), you must check if music is already playing, and if so you must ask the user for permission before playing anything.

 

But how do I know if the user is playing music?
Well this is where it gets a bit ugly; The only way you can know for sure is using the
Microsoft.Xna.Framework.Media.MediaPlayer class.

Yes, XNA. Sorry all you Silverlight purists, but like in a lot of things on the WP developer’s platform, you have to use XNA libraries for certain things.

The MediaPlayer class contains a property called GameHasControl, this kinda confusingly named property actually indicates whether someone else is already using the media player, like the Zune player for example. If no one is using the media player, this means your application has "control" over it and consequently the property will be True, otherwise it will be False.

What this means is that before doing anything related to the media player you must first check this property, and if it is False (meaning you don't have control) ask the user for permission.
Translated into simple code, it will look like this:


    HasPermission = true;

 

    if (!MediaPlayer.GameHasControl)

    {

        if (MessageBox.Show("Can I please stop the music?", "Music Already  Playing", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)

         {

             HasPermission = false;

         }

     }

 

     if (HasPermission)

     {

        // Load and play music or navigate to a page that will

     }

When do you ask for permission and what you do if you don't get it is obviously up to you. This decision should be made considering the design and flow of your application.

Just keep in mind these few things:

1) Never prompt the user before the first page has loaded. It's just not user friendly.

2) Consider what happens if the user doesn't want to stop his music at the moment, but later he does.

3) If you are building a game or even an application, if the music is not essential don't make the user give his permission to stop the playing music in order to continue. He might want to play while having his own music playing, so give him the option.

4) If you are creating a
MediaElement from XAML, note that assigning it a source, will cause loading the page to stop the currently playing music (because you load a new song to the media player, your MediaElement's song).

5) If your application or game plays background music throughout it's usage, you must include an option to mute and/or change the volume of the playing music (requirement 6.5.2).


More posts about passing certification coming soon.
If you have specific trouble with certification you wish me to write about, please leave a comment bellow.

Josef.

Passing Windows Phone Certification and Staying Alive

AKA: What are Windows Phone 7 certification rules and how not to break them



The rules. Usually they look like this.

 
It's just so heart breaking. You've worked tirelessly on your new app, to you it's perfect, more than perfect, it’s the consummation of all your goals in life!
But alas a few days after you've uploaded it to the
App Hub, you find an update in your notifications panel.. You didn't pass certification.

More or less, it's Microsoft's polite way of saying "It's not me it's you". And the best way to avoid this heartache is to know what "It" means.

Basically "It" is a not-so-long set of
application guidelines (rules) set by Microsoft that your Windows Phone 7 applications must answer to in order to be incorporated in the Marketplace.

The reasons for these rules are the following:
1) User Experience.
2) User Experience.
3) User Experience.
4) … you get the point …

The whole idea behind the making of the new Windows Phone 7 platform was to create a mobile platform for people, this means one thing: give the user the best experience possible, and maintain it throughout the platform.
What this means is that the only way to maintain the same great experience on every little thing you do on the device, is to make sure third party apps like the ones you and I develop, abide to the same user experience (UX) guidelines, hence the certification rules.

But like a lot of things, what makes a great experience for the user, can sometimes end up making a great pain in the #@&! for the developer. And not knowing the rules or how to abide them beforehand can cause you disappointment on a good day, or make you re-write big chunks of your code on a bad one. 

In my next few posts I will go over some of the key rules developers usually stumble over, and what are good practices for writing code that follows them.

And until next time don’t forget:
Rules might have been made to be broken, but the same can also be said about bones.

Josef.


Tip #1: Correctly Working With Media

Microsoft Announcing: Idea of the Week for Students

Student? Feeling creative?
Microsoft is looking For You!

This week we are launching a new promotion for students called “Idea of the Week”. 
The purpose is to encourage students to start experimenting with our developer tools and to begin taking action on their app ideas. 
We will select one winner per week and will award a $50 gift card to Amazon.com.

 

 

How Students Enter

 

Students must be registered for Dreamspark.  Then they create a Sketchflow* prototype of their app idea, post it online, and tweet the URL using the hashtag “#WPAppItUp

 

Each week, we will select one winner of the $50 gift card and will judge all entries based on:

 

•Innovation (40%): How innovative is the idea? It does something new or does it accomplish something in a new way?

•Experience (40%): Since this is a prototype, we don’t expect the UX to be polished. However, we are looking for a quality experience in the flow of the app. Does it feel seamless and like a native experience on Windows Phone?

 

•Potential (20%): Does the app idea have potential in the market (lots of users, making money, both) or not?

 

Started:   10/17/2011

Ends:       12/25/2011

 

Official Rules:http://www.microsoft.com/student/en/us/ideaoftheweek/officialrules.aspx

 


*No Purchase Necessary.  Open only to students 18+.  Game ends 12/25/2011.


Cheers,
Microsoft Student Partners Israel.

Code Tips That Will Save Your Life #1

Tip #1 : Document & Comment Your Code.

   
mmmm… liver, fava beans and bad code, my favorite.
"Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live."

 

You can never know when this phrase will turn into reality, so you'd better be prepared.
This is the beginning of what I expect to be a long series of coding tips and best practices that will help you write better code and might even save your life one day!

 

Tip #1 : Document & Comment Your Code


I really wanted to call this "Document & Comment Your Code Properly" but then I realized that you can't do properly something that you don't do at all.

I have seen code written by so many developers, and about 4 out of 5 had the same thing in common: They did not document their code.
Some didn't even write a single comment throughout several thousand lines of code, and some would write maybe a comment futilely explaining in 5 words the monstrosity of a recursive method they just wrote some 200 lines of code later.

This has to stop!
You may think your code is so clear that it does not need comments, but that’s because you just wrote it and it's fresh in your mind. Even the most well-written code can't be instantly clear to someone who isn't you, that is because it is written in code and will never match an actual language.

And if you think to yourself "If it was hard to write, it should be hard to understand", you might want to look for advise elsewhere.  

The good news for all you other .NET developers are that it's not that hard and part of the heavy lifting is done for you, saving you about half of the work.
Don't believe me? Go ahead, open a new project on Visual Studio, yes I will wait…


It's open? Good.
Create a new class; name it to your liking like so:

  public class CookieMonster

  {

      // A whole lotta nothing.

  }


Now for the cool part, put your text marker one line above the class declaration and type the character '/'  three times (yes Three).

  /// <summary>

  ///

  /// </summary>

  public class CookieMonster

  {

      // A whole lotta nothing.

  }

 

It’s a miracle you say? No, this is not some kind of witchcraft, this is XML Documentation, and it will be the only way you are going to document your code from here on.
Go ahead write some class description, don't be shy. You will see that you can add some more tags, like remarks, code usage examples and so on.

 /// <summary>

 /// The <c>CookieMonster</c> class is responsible for all

 /// cookie disposing (a.k.a: eating) in the system.

 /// </summary>

 /// <remarks>

 /// Beware:

 /// The <c>CookieMonster</c> may dispose of your cookies without a warning.

 /// Disabling cookies may result in exceptions and rage.

 /// </remarks>

 public class CookieMonster

 {

     // A whole lotta nothing.

 }

 

 

Let's try something new, add a method, maybe a property, you can do it, you do it all the time.

  public class CookieMonster

  {

      public bool IsFull { get; set; }

 

      public bool Eat(System.Net.Cookie cookie)

      {

          if (!IsFull)

          {

              cookie.BeEaten();

          }

 

          return false;

      }

  }

 

Now, do the same trick with the triple '/' above the property and the method.

 public class CookieMonster

 {

     /// <summary>

     ///

     /// </summary>

     public bool IsFull { get; set; }

 

     /// <summary>

     ///

     /// </summary>

     /// <param name="cookie"></param>

     /// <returns></returns>

     public bool Eat(System.Net.Cookie cookie)

     {

         if (!IsFull)

         {

             cookie.BeEaten();

         }

 

         return true;

     }

 }

 

Yes it also works for methods, properties and members!
And if you fill it up it will look like this:

 public class CookieMonster

 {

     /// <summary>

     /// Indication whether the <see cref="CookieMonster"/> is full

     /// </summary>

     /// <remarks>

     /// The <see cref="CookieMonster"/> is NEVER full

     /// </remarks>

     public bool IsFull { get; set; }

 

     /// <summary>

     /// Eats a single cookie, disposing it.

      /// </summary>

      /// <param name="cookie">

      /// The <see cref="System.Net.Cookie"/> to be eaten

      /// </param>

      /// <returns>

      /// Indication whether the cookie was eaten or not.

      /// <remarks>

      /// Note: the cookie is always eaten!

      /// </remarks>

      /// </returns>

      public bool Eat(System.Net.Cookie cookie)

      {

          // Checks whether the CookieMonster is full

          if (!IsFull)

          {

              cookie.BeEaten();

          }

 

          return true;

      }

  }

 

So this is nice and all, but why bother you ask?
Well try to write some code that uses this class, see anything different?



 

 

Indeed your eyes do not lie to you, that's full Intellisense right there.
But that’s not all, now comes the really cool part.


One of the nastiest jobs a developer can get is making a program documentation document. These are usually very long, very boring, very incoherent Word files that supposedly have all the information needed to maintain the said program. Usually they end up unread for months until someone new needs to update them, but never the less at one point or another your boss will ask you to write one.

Now let's say that the day came, the boss knocks on your door and says: "Hey there Johnny boy. We are a bit ahead of schedule so we have some spare time, how about writing a Word file documenting that module you have been working on for the past 6 months?  Great, send it to me on Monday, cheers."

And now let's say that you read this post 6 months ago,  thought XML Documentation is indeed a good idea, and commented all your code with it.

You just go to your project Properties -> Build -> And set the XML Documentation File field.  

 

 
Now build. You will find that in your bin folder appeared a new XML file containing all the documentation that was in your code.
Now you can do whatever you like with it, use your own XSL transformer to convert it into an html page, index and search on it, or use a third party application to convert it into the document type you desire, and these come in many flavors.

A very commonly used open source tool is Sandcastle, together with Sandcastle Help File Builder they create a very powerful tool that enables you to create MSDN like documentation or chm files from your XML Documentation.
So now you can go back to slacking off in peace while your boss thinks you are working hard on that document.

 

That’s it for now, this post has turned out to be much longer than I expected.
I hope you've found this helpful, and if not, well… you have the comment section for that.

For more info on XML Documentation check out the MSDN page.

And don't forget:
Code is usually easy to write, but rarely easy to read.

Josef.

5 Ways Improve Your Windows Phone 7 Application Stability

A.K.A: Critical But Stable Condition

Probably the least user friendly experience one can have in a Windows Phone App, not including the "screen freeze" horror, is having the application crash back to start screen.
No one tells you what happened, no one warned you that it is coming, and you are left with the horrifying feeling of assuming the worst.

Now I know that you know, that when an application crashes it's just an  unhandled exception, nothing big, no scary monsters there.
But the common user doesn't, for all he knows a pack of wild tumbeasts have just been unleashed inside his phone, nibbling on his contacts.

Tumbeasts ravaging a Windows Phone. Cuter than you'd think..

Credit for The oatmeal for these awesome tumbeasts illustrations.


It’s a situation you need to avoid as much as possible, both for the user's sake and for yours if you want your application to be successful.

So here are 5 tips for making your application more stable:

1) Duh.

Fact: Most people are lazy.
Ergo: Most program developers are lazy.

The following lines will look very basic to some of you, so basic you might just stare at the screen and go "Duh". But for a good part of you this will be an eye opener, or at least a wake-up call.


  try
  {
      // Do stuff
  }
  catch
  {
      // Oh noes things failed
  }
  finally
  {
     // This part has to be done any way
  }
 

If a good part of your code does not match this pattern, than sorry to tell you, you are part of Most program developers, and by that I mean that You are lazy!

It's both good practice and common sense to extensively use Try&Catch in your code, for about a gazillion reasons (O.K. that’s not a real number, but you get my point). The most important one being: Not letting exceptions bubble up all the way to the top and crash your application.

So wrapping your code with Try&Catch is the first step, what's the next?
Well that is up to your application design. You might want to notify the user that something failed, maybe send an error report to your server, or maybe just try again.

 

2) Control your workers  

If you have ever created a complex Windows Phone 7 application, or any application with UI for that matter, you probably found yourself using Worker Threads, Background Workers, and other asynchronous goodies. These cool tools allow your application to do all its dirty work away from the precious UI thread, keeping it powerful and complex yet still responsive.

But as a great comic book hero once said:
"With great power there must also come great responsibility"

Slightly over dramatic for a software development blog. But what the heck...

A common misconception about threads is that they magically do their things and then just as magically disappear. Well the thing is they don't, they don't stop or disappear unless you close the application, or you tell them to.

Always make sure your main thread (the UI thread) knows which threads are alive and what is their status so in case of navigation it will be able to stop them gracefully, or make sure they are alive if that is what needed.

Threads that are killed abruptly can throw nasty exceptions that you can’t always catch.
Also in general, exception that is thrown and not caught within a background thread will make your application crash!

For example, run this code on a new Windows Phone 7 project:


Thread thread;

public MainPage()
 {
     InitializeComponent(); 

     thread = new Thread(new ThreadStart(() => 
     {
         Thread.Sleep(1000);

         throw new NotImplementedException();
     })); 

     thread.Start();
 }

The application will start, the background thread will start too, and after a second an exception will be thrown, not being caught by anything it will reach to the top and.. bye bye application, hello start window.

Now let's try that again, this time with a BackgroundWorker:


 

BackgroundWorker bw;

 public MainPage()
 {
     InitializeComponent(); 

     bw = new BackgroundWorker();
     bw.DoWork += new DoWorkEventHandler(bw_DoWork);

     bw.RunWorkerAsync();
 }
 

 void bw_DoWork(object sender, DoWorkEventArgs e)
 {
     Thread.Sleep(1000);

     throw new NotImplementedException();
 }


The application will start, the background worker will start too, and.. well nothing happens.
Why? Well nothing happens because BackgroundWorker is a bit more complex than a Thread. What actually happens is that the BackgroundWorker catches the exception for you, and sends it to you in the RunWorkerCompleted callback method.
If you wanted to get it, you would do so like this:

 void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     if (e.Error != null)
     {
         MessageBox.Show(e.Error.ToString());
     }
}

 

So watch your background workers and threads, make sure they handle exceptions correctly and don't throw them all over the place. And in general if you can, prefer to use BackgroundWorkers instead of Threads.   

 

3) Watch your senses

This is a short one.
Not all phones were made equal, and even though Microsoft works hard on keeping a high standard in all that is related to the phone's hardware, not all phones have the same feature. So before using any of the phone's sensors and relying on them, make sure they are even there. Even the ones that look obvious and all the phones should have them, future phones might not, so take that into consideration.

For example:



 if (Accelerometer.State != SensorState.NotSupported &&
     Accelerometer.State != SensorState.NoPermissions &&
     Accelerometer.State != SensorState.Disabled)
 {
     this.Accelerometer = new Accelerometer();

     this.Accelerometer.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(Accelerometer_ReadingChanged); 

     this.Accelerometer.Start();
 }

4) Learn To Work Solo 

I love applications that use the web. They almost always have more content in them, they are dynamic, they allow you to share, they are fun.
But what happens when I'm sitting on the train and suddenly I go into an area with no coverage?  I leave the café and now I'm out on the street, suddenly there is no Wi-Fi only Cellular internet connection, what happens now?

These are very important questions that sadly not all developers ask themselves.
You cannot assume that your user is connected at all times. Even if you say in advanced that the application is useless offline, it needs to handle itself gracefully on all occasions.
Gracefully means to at least not crash, notify the user about what happens, and if you want to be really user friendly, how about some cashed offline content?

I can say for myself that this is one of the bigger issues a WP7 developer can stumble upon.
Connection flakiness can vary, and even if you have a live connection it doesn't always mean that things will work. You have remote servers to worry about, proxies, local Wi-Fi login pages that always show up at the worst time, and all of that change from one country to the other.

So what are good practices?
That very much depends on what you are trying to achieve.  For most cases I found "The best defense is a strong offense" a good tactic. And by that I mean, that it is better to monitor the connectivity and "attack" accordingly, than just to wait for exceptions to fly willy-nilly and handle them. 

Attack #1: Before doing anything, show the user some pretty colors and while he is distracted check for connectivity.

Ooooh pretty colors!




IsConnected
= NetworkInterface.GetIsNetworkAvailable();


if
(IsConnected)
{
    // Do awesome stuff
}


 





You could also identify the connection type while at it:


   switch (NetworkInterface.NetworkInterfaceType)
   {
        case NetworkInterfaceType.Wireless80211:
           // This Wi-Fi
           break;
        case NetworkInterfaceType.Ethernet:
           // This Ethernet
           break;
        case NetworkInterfaceType.MobileBroadbandGsm:
           // This Gsm
           break;
        case NetworkInterfaceType.MobileBroadbandCdma:
           // This Cdma
           break;
   }


Watch yourself, both these pieces of code can take a while to compute (yes even getting the NetworkInterfaceType property actually operates some logic behind the scenes).
I never witnessed that for myself, but some people say this can take up to 20 seconds. So if you don't want your user watching a static (yet colorful) screen for too long consider doing this with a BackgroundWorker.


Note: when working with the network interface you will find yourself confused by 2 similar namespaces:
- Microsoft.Phone.Net.NetworkInformation
- System.Net.NetworkInformation

These namespaces are different and have different capabilities, and you will probably need to use both.
The above example uses  Microsoft.Phone.Net.NetworkInformation
the next one uses the other.


Attacks #2 and #3: While the user is having fun, monitor the connectivity. If the connection is lost, inform the user and stop web requests. If the connection is found get back to work.

 private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
 {
     NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);

 }


 void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
 {
     IsConnected = NetworkInterface.GetIsNetworkAvailable();

     if (IsConnected)
     {
         // Do stuff
     }
     else
     {
         // Stop doing stuff
     }
 }
 

Basically all we did is to register to the event of the IP address changing, which will fire every time some sort of change will happen, including losing connection. That way we will know about the changes and act accordingly.

Attacks #4: Same as attack #1 only after Tombstoning. (Because I know some of you didn’t think about it).

There is still a lot more that can be done, most of it is more application specific.
For some more interesting input on this subject you can check out
this presentation from Tech-Ed 2010.

 

5) When All Fails
Disclaimer: O.K. so this tip will not make your application not crash.
But it will help you understand when, where and why your applications do.

"In god we trust, the rest we monitor"

Yes sometimes you did almost everything right and still it crashed for a few users. It happens. Some bugs are just so hard to reproduce that there is no way you could have found them.

The best thing you can do is to document, research, and try to figure out what caused the crash. For that, you need a black box.

A black box can be anything, it can be a file on isolated storage, it can be a spool of text sent to a logging service, it can even be a mail sent to you, the developer.

My personal preference is saving a file on isolated storage and checking it whenever opening the application. That way the next time the user opens the application, if the last time it crashed, I will find the file and prompt him to send the crash details to me.

Here is how you do it: 

First you must register to the UnhandledException event in the App class.
You will find that the event handler is already there and it will look like this:

 private void Application_UnhandledException(object sender,  ApplicationUnhandledExceptionEventArgs e)
 {
    if (System.Diagnostics.Debugger.IsAttached)
    {
       // An unhandled exception has occurred; break into the debugger
       System.Diagnostics.Debugger.Break();
    }
 }


I wouldn't recommend removing the code that is already there, it's for debug purposes.
Now all we need is to add the part that will save a crash report, something like this:



   private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
   {
       SaveCrashReport(e);

       if (System.Diagnostics.Debugger.IsAttached)
       {
           // An unhandled exception has occurred; break into the debugger
           System.Diagnostics.Debugger.Break();
       }
   }


 
 private static void SaveCrashReport(ApplicationUnhandledExceptionEventArgs e)
   {
       try
       {
           string crashReportFileName = "CrashReport.txt"; 

           // Get the isolated storage
           IsolatedStorageFile isoStore = 
                 IsolatedStorageFile
.GetUserStoreForApplication
();

           // Check if file exists and if so delete it
           if (isoStore.FileExists(crashReportFileName))
           {
               isoStore.DeleteFile(crashReportFileName);
           } 

           // Create the file and write the exception content to it
           using (IsolatedStorageFileStream fileStream =
                             isoStore.CreateFile(crashReportFileName))
           {
               using (StreamWriter sw = new StreamWriter(fileStream))
               {
                   sw.WriteLine(e.ExceptionObject.Message);
                   sw.WriteLine(e.ExceptionObject.StackTrace);
               }
           }
       }
       catch{}
   }
 

All we did is create a text file and write to it the crash report.
If we wanted we could make it fancy: Serialize the report object using XmlSerializer or DataContractSerializer, add a time stamp, etc.

Now all we need is that when the application loads we will look for this file to indicate a crash.
We put this code in the MainWindow loaded event handler


  private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
  {
      try
      {
          string crashReportFileName = "CrashReport.txt"; 

          // Get the isolated storage
          IsolatedStorageFile isoStore =
                      IsolatedStorageFile.GetUserStoreForApplication();

          // Check if file exists this means we crashed last time
          if (isoStore.FileExists(crashReportFileName))
          {
              string report = string.Empty; 

              // Open the file and read the crash report
              using (IsolatedStorageFileStream fileStream =
                      isoStore.OpenFile
(crashReportFileName, FileMode.Open))
              {
                  using (StreamReader sr = new StreamReader(fileStream))
                  {
                      report = sr.ReadToEnd();
                  }
              } 

              // We are done with the file, we can delete it
 
             isoStore.DeleteFile(crashReportFileName); 

              // Ask the user to send a crash report
 
             PromptCrashReport(report);
          }
      }
      catch {}

      // Do other stuff
  }

Also here all we do is to look for the file, if it exists, this means that last time we crashed.
We read the report, and ask the user to send it for analysis.
Obviously this could also have been done asynchronously with a BackgroundWorker, to not slow down the loading time.

That’s about it.
I hope this helped you or will help you in your future endeavors, and if not… Well you have the comments bellow to complain about that.


And until next time, don't forget:
“If you don't have a good application, make sure you get good users.”

Josef.

The birth of a narcissist

A.K.A: Why on earth would you start a blog?



I hate first impressions, never was good at them.
I find it easier to grow on people rather than dazzle them with a witty opening line.
So also this time I will not make an exception:

Hello my name is Josef Goldstein.

I'm a .NET software developer and architect; Born and raised in the good ol' holy land (Israel for all you other 50% of the earth).
When I'm not at the office I'm working on my B.Sc. degree in CS, while filling the role of a Microsoft Student Partner in my faculty.
I like long walks on the beach, IntelliSense, and corny humor.

So why am I here?
That’s a damn good question.
Mainly because I was asked to, but also because of curiosity.

I like software development related blogs. I'm the kind of guy that not only goes to them when in need for a code snippet to fix a problem, but also follow the good ones on a regular basis.  My hope is that with time I will be able to fill this blog with the kind of posts that make people keep reading even if they don't have to. And who knows maybe even learn for myself a thing or two while doing it.

What should you expect to see here?
Hopefully text, maybe some code. I believe that teaching people how to fish is much better than giving them a fish, and usually giving code snippets is the equivalent of  giving fish away.
Currently I'm most passionate about Windows phone 7, WCF, WPF and Windows Azure. So expect to see a lot about them in the near future (especially the first).
Beside these awesome buzzwords, I also believe in writing good code, a thing which sadly is rarer than I would wish. So expect to see a lot of posts about good practices, and writing code that will not make your co-workers hate you.

Also as a good Hebrew, I will translate some of my posts to my native language, but not all of them. Mostly because translating can sometimes take longer than actually writing a post.

That’s it for now.
And until next time, don't forget:
Trying is the first step towards failure. But failure is the first step towards success.

Josef.

Posted: Sep 16 2011, 07:44 PM by iummydd | with no comments
תגים:

Tradition

 Hello World