My experience with Ads in my Windows Phone apps

After some thought, I decided to share my experience with ads and to provide the revenue that my apps provided. If my details help you, then I’ll be happy.

The two apps that generates the most revenue are:

  • Ultimate Poker Hands & Timer
  • Ultimate Poker Manager Free

Those apps target a niche audience: the poker players that play home games. Although they are niche apps, these two apps are popular in the US Windows Store. If you enter “poker timer”, the apps will get the 1st and 4th places:

image

The advantage of adding an ad control into a “timer” app is you get a chance that you’ll get tons of ad requests. I was curious if the ad market can be good.

Smaato

Back in early 2011, there were few providers where a Canadian developer can be paid. Believe it or not, the PubCenter by Microsoft was not in the list. So, I ended up choosing Smaato. In 2011, if my memory is good I got three payments of ~$5 each. My user base was very low, so it was not that bad getting the $15.

I don’t look into the details of my ad revenue day to day, but at the end of 2012, I checked what was going on. I was quite disapointed to see that on 151 244 served ads for the last 6 months, that the generated revenue was $1.91. Unfortunately, Smaato does not provide data older that 6 months. I contacted the support on their website, but I never got any answer. I found a Twitter employee where he forwarded my question to the right team and it took more than a month before getting an answer. They did not seem to understand that the $1.91 of revenue on 150 000 ads was abnormal. At this point, I gave up and remove the Smaato ad control into my apps. It is not fair is only one company is making money.

image

Microsoft PubCenter

At the end of 2011, the PubCenter finally arrived in the Canadian market. I decide to make the PubCenter my primary ad provider and when an ad request cannot be fulfilled, the Smaato would try to request an ad. So, it doubles my chance to display an ad.

What you see is $32.06 for 135 205 ads. I’m not an ad guru, but those numbers seem fair to me.

I would like to point out that integrating the Smaato and PubCenter ad controls into a Windows Phone app is almost as easy to drag a button into a page.

image

Nokia NAX

In the autumn of 2012, Nokia released the NAX ad network that supports multiple platforms. As a big fan of Nokia, I decided to give a try. We always have a dream to become rich 🙂 I put the NAX as the primary ad provider and use PubCenter as the backup.

The NAX ad network is powered by the company inneractive.

When I first integrated the NAX ad control, it took me some time to figure out that the AdFailed/AdRequest events were static events and does not belong to the control. To use the NAX Ad Control it was not as easy as Smaato or PubCenter.

When I ported my two apps to Windows Phone 8, the NAX ad control was not even released despite having all other non-Windows Phone platforms. I was a bit surprise, but they told me that I can use the WP7 version.

The first surprise

After my apps were updated with the NAX Ad control, I received a couple of days later a crash report showing that the AdFailed event generated an exception because it was not returned in the UI thread. When you are using an ad control in an app, you expect that the ad control have been tested and you can have confidence in it. By definition, an ad control fetches an image and display it every 60 seconds, right? I immediately contacted the support. Without too much surprise, they confirmed the crash and told me to update my apps.

I updated my apps and waited for the certification time… That part is not fun to wait when you know your users can have random crash without even touching the timer page.

I gave them a chance…

Last week, I got another new crash report and I found out a 100% repro case in an app that I’m developing right now. I contacted the inneractive support and after two days, I got no answers. I reached out the NokiaDeveloperTeam Twitter account and they quickly asked for my info and forwarded it to the inneractive team. After a day, I still did not get any support. I found out the Twitter account of inneractive and I got a reply right away. Once again, they forwarded my info the the engineering team. I won’t go into details, but the inneractive engineers do not seem to understand the WP platform and I’m still waiting for an answer or an update for the current situation.

On top of that, I got another new crash report today.

Two person from Nokia are aware about my situation and they asked me my feedback and I’m keeping up to date. It is way more important for Nokia to know what’s going on with their contractor inneractive. Nokia thanked me for my feedback to them.

If I put aside the negative experience with the NAX ad control, the numbers are impressive so far (it is less than 40 days): $0.85 for 3853 served ads.

image

In conclusion, I would suggest to avoid the NAX Ad control for now, it is not ready for prime time yet. The PubCenter is my top suggestion. I know I won’t be rich with my two apps, however, the part where I’m the more happy with is over 320 000 ads that have been requested over the last 2 years and if one ad is requested every 60 seconds, it represents 5333 hours of usage of my apps.

Happy New Year of coding!

Review of Building Windows 8 Apps with C# and XAML

imageDuring the holiday season, I received the Building Windows 8 Apps with C# and XAML by Jeremy Likness. Holidays are the perfect time to read books! Before starting the book, I was curious to know if it would be useful to me, since I created my first Windows 8 app (Canadian Developer Connection) earlier this year where I included a lot of Windows 8 features. It turned out that I was very satisfied with the number of things I learned.

The reader should have extreme confidence in the content of the book, given the author’s solid experience and background.

The book starts with a simple app that is more than just a “Hello World” app. After the first app, a beginner would be happy to read and learn more.

The author took the time to explain some “under the cover” mechanisms of the new Windows 8 Store app world. Yes, the Registry is still present more than ever. This information is very much appreciated.

Reading about the controls, the application lifecycle, the way to save data, the charms, the packaging, the deploying and more, the reader will get a complete picture of how to take advantage of Windows 8 features.

One of the most important aspects about programming is testing. Even though this aspect is not only related to Windows 8 development, the author dedicates a whole chapter to testing and the high importance of doing unit tests. The experiences that he wrote about proved that even more. For all levels of developers, this chapter is a good reminder of one of the aspects we tend to push aside.

Throughout the book, there is code that is available open-source. The book is a great companion to the provided code and some of the code can even be used in your own apps.

As for the physical aspects of the book, the font size is easy on the eyes. The book could have been a bit better if there were colors in the diagrams, but undoubtedly the price would have then been higher. The current price of the book on Amazon USA is $28.99 and $32.59 on Amazon Canada. At this price, it is really worth buying.

In conclusion, the book covers all the new cool features of the Windows 8 Store apps. If you know C# and you want a quick start on Windows 8 App development, I recommend this excellent book.

How to avoid application settings corruption when a background agent is used

LIke most of my applications, I used to save all my application settings in the IsolatedStorageSettings.ApplicationSettings. It seems like a logical good choice. In my last application, I added a Background Agent to my project. When I was looking for best practices on how to exchange settings between the background agent and my application, I came across with this text from the MSDN library:

For Periodic and Resource-intensive Agents: Use LINQ 2 SQL or a file in isolated storage that is guarded with a Mutex. For one-direction communication where the foreground app writes and the agent only reads, we recommend using an isolated storage file with a Mutex. We recommend that you do not use IsolatedStorageSettings to communicate between processes because it is possible for the data to become corrupt.

After, I found someone who implemented a solution that uses a Mutex. While the solution is good, the only problem is that his personal settings are mixed with the IsolatedStorage operations.

To help the reuse of the solution in different projects, I created a IsolatedStorageHelper class. Also, instead of relying on the XmlSerializer in order to save an object, I based my solution using the powerful library of Json.NET.

Usage

The IsolatedStorageHelper has three methods:

  • WriteObjectToFileUsingJson
  • ReadObjectFromFileUsingJson
  • IsFileExists

Here is the example that uses all the methods:

Settings mySettings = new Settings();

IsolatedStorageHelper.WriteObjectToFileUsingJson("Settings.txt", mySettings, "MyMutexName");

if (IsolatedStorageHelper.IsFileExist(SettingsFileName))
{
    Settings = IsolatedStorageHelper.ReadObjectFromFileUsingJson<Settings>("Settings.txt", "MyMutexName");
}

To use the IsolatedStorageHelper in your project:

1- Add the IsolatedStorageHelper.cs file into your project.

2- Add the Nuget package Json.net.

If your project does not have a background agent, you can still use my utility class, you can omit the mutexName parameter of the WriteObjectoToFileUsingJson and ReadObjectFromFileUsingJson.


Download

XAML coding convention

Over the past year, I have built my own coding conventions for C#. I also always manage to convince my colleagues to follow my coding convention if they don’t already have one. I’m a real freak about following coding conventions; if I see someone modifying one of my files and not following my conventions, I might have trouble sleeping at night (ok, not that much, but…).

With the help of the great Visual Studio add-on ReSharper, it’s easy to format code with rules. You only need to press Ctrl-E/Ctrl-C to format a document. ReSharper is a must have tool for Visual Studio.

For the past two years, since the release of the Windows Phone platform, I have been using the XAML language to program my user interfaces. Finding coding conventions for C# is pretty easy, but for XAML, it was a bit more of a challenge. My first move was to check the default Microsoft projects, but I concluded that even they are a bit messy even for today.

Here is an example of a WIndows Store Grid App project:

<ListView.GroupStyle>
    <GroupStyle>
        <GroupStyle.HeaderTemplate>
            <DataTemplate>
                <Grid Margin="7,7,0,0">
                    <Button
                        AutomationProperties.Name="Group Title"
                        Click="Header_Click"
                        Style="{StaticResource TextPrimaryButtonStyle}">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Title}" Margin="3,-7,10,10" Style="{StaticResource GroupHeaderTextStyle}" />
                            <TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-7,0,10" Style="{StaticResource GroupHeaderTextStyle}"/>
                        </StackPanel>
                    </Button>
                </Grid>
            </DataTemplate>
        </GroupStyle.HeaderTemplate>
    </GroupStyle>
</ListView.GroupStyle>

First of all, there are not any empty lines, and secondly the button has attributes on separate lines, but for the TextBlock elements, the attributes are on the same lines without any order.

With time, I developed my own XAML coding convention that I would like to share. One of the reasons that I developed my own XAML coding convention is I don’t like to use the Properties window, because it is hard to have an overview of the properties that are not set to default.

image

My coding convention is resumed in 5 points:

1- Put empty lines between elements.

Don’t be afraid to put empty lines. It makes reading the code easier.

<Grid Height="250"
      VerticalAlignment="Top">

    <Image Source="{Binding FeatureArticle1.Thumbnail}"
           Style="{StaticResource ImageThumbnailStyle}" />

    <StackPanel Style="{StaticResource StackPanelSummaryStyle}">

    <TextBlock FontSize="22"
               Style="{StaticResource TextBlockAuthorStyle}"
               Text="{Binding FeatureArticle1.Author}" />

    <TextBlock FontSize="26"
               Height="70"
               Style="{StaticResource TextBlockSummaryStyle}"
               Text="{Binding FeatureArticle1.Title}" />

    </StackPanel>

</Grid>

My exceptions are the Grid.ColumnDefinition and Grid.RowDefinitions, because they only have one line attribute.

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="200" />
    <ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>

<Grid.RowDefinitions>
    <RowDefinition Height="200" />
    <RowDefinition Height="140" />
</Grid.RowDefinitions>

2- Put one attribute per line.

<TextBlock FontWeight="Bold"
           Foreground="White"
           HorizontalAlignment="Right"
           Margin="0,0,12,0"
           Text="{Binding ArticlesCountText}"
           TextWrapping="Wrap" />

3- Order the attributes alphabetically.

<Image Source="/Assets/Shares/NeutralImage.png"
       Height="125"
       HorizontalAlignment="Center"
       Width="125"
       Stretch="UniformToFill"
       VerticalAlignment="Center" />

Some will argue that Height and Width should be side by side or on the adjacent line, but I still prefer the alphabetical order, because it is much easier to read when you know what order your definitions are in. Also, if there is an element with many attributes, it is much easier to check whether an attribute is missing.

4- Put the attached properties at the beginning and in an alphabetic order.

<Button Grid.Column="1"
        Grid.Row="2"
        Command="{Binding ShowWriterCommand}"
        CommandParameter="{Binding WriterAshley}"
        Style="{StaticResource HubTileButtonStyle}" />

The Grid.Column / Grid.Row are the classic examples.

5- Definition of styles can be less strict.

When I’m creating styles with Expression Blend, I tend to leave them as-is when they are big. It is more about saving time than anything else. However, when a style is small, I don’t put empty lines and I put the properties in an alphabetic order like this:

<Style x:Key="GridFeatureStyle"
        TargetType="Grid">
    <Setter Property="Height"
            Value="194" />
    <Setter Property="VerticalAlignment"
            Value="Top" />
    <Setter Property="Width"
            Value="194" />
</Style>


Conclusion

It might not be the perfect solution for you, but if you do not have one, my convention is a good start especially if you are sharing code with colleagues.

My motto about coding convention is the following: it is better to have a coding convention than not having one!

Happy coding!

Canadian Developer Connection: Now available in the Windows Store

For the past few months, I have been working on my first Windows Store app for Windows 8 called Canadian Developer Connection. Since yesterday, my application is now available in the Windows Store. The Canadian Developer Connection includes all the articles, videos-on demand, events, resources and more from the Microsoft Canadian evangelist team. Even if you are not a Canadian, the application contains useful information for any developers interested in Microsoft technologies.

Here are some screenshots:

Screen shot 1

Screen shot 2

Screen shot 6

Screen shot 7

The application allows you to stream a video to any Play To devices like an Xbox 360.

At the same time, I updated the Windows Phone version to includes the videos on-demand series and the developer events.

1 of 8

Don’t miss anything from the Canadian Developer Connection and download both versions!

BUILD 2012: A dream come true!

A big thanks to my employer, Mirego, for letting me go to BUILD, and for paying for it too!

My BUILD journey started in August, on the day the tickets went on sale. I even had two computers all set up and ready to buy my ticket. When the registration confirmation came through, I was very happy. I started counting the days, like a child waiting for Christmas. I managed to convince a friend of mine from Switzerland, Marios, to come to the conference too.

One week before the conference started, Windows 8 and the Surface were both released. Now I was counting the hours…

I arrived in Seattle on Saturday the 27th of October, a few days before the conference was due to start. On Sunday the 28th, I visited the Museum of Flight. I highly recommend you visit this museum if you are in the Seattle area; it is one of the best museums I have ever seen. I spent more than an hour in the “Exploring Space” area alone. I even saw a lunar rock! I stepped inside one of JFK’s Air Force One jets, learned about aviation during both the first and second world wars, and took a tour of a Concorde. Three hours and 250 pictures later, I left to see some more of Seattle.

IMG_3434

IMG_3569

After the Flight Museum, I went to the Bellevue mall where I visited the first Microsoft store. The store was full, and there was a really good vibe, no doubt due to the just-released Surface. This was my first look at the Surface, and I fell in love very quickly!

IMG_3681

Day 0 – Monday

On Monday morning, Microsoft had an official press conference for Windows Phone 8 in San Francisco. I was looking forward to watching, but I was a bit concerned that I wouldn’t be able to watch it due to the unreliable Internet connection in my hotel. Luckily, Microsoft had reserved a meeting room where Build attendees could watch the event. To ensure I wouldn’t miss anything, I left my hotel an hour before the scheduled start time. Destination: Microsoft building #40… At the event, I was expecting to meet some of my Twitter friends in person for the first time. I was not disappointed; I met Gary, and half an hour later, my friend Marios and his wife Lia arrived. Marios and I have exchanged thousands of emails since meeting in Los Angeles (at another Microsoft event!) over a year ago, but it’s always better to see your friends in person!

The WP8 press conference ran very smoothly. I really like Joe Belfiore’s presentation style. Having Jessica Alba around didn’t hurt, either! There were few surprises for me, but the most important news was that WP8 devices are coming before long, and Steve Ballmer promised that we will soon be seeing Windows Phone ads worldwide.

Registration opened at 3pm on Monday. Marios and I got in line early, and were very thankful for that fact, since the lineup an hour later was very long! I went to the reception and got my first beer. They also had some amazing cupcakes. Of course I had to have two!

WP_000146

The week before Build, I received an invitation to attend a private event being held by Nokia and the Windows Phone relation team at a nice restaurant in Bellevue. I was also lucky enough to be able to invite my friend Marios along. Upon our arrival, we met Kevin Hague, who happens to be the Director of Tools and Technology at Nokia. We sat beside him at dinner, and I saw a Lumia 820 phone. Without him actually saying anything directly, I knew that there would be a nice surprise from Nokia the following day at the conference. The food was very good, but of course there was too much. After dinner there was a bowling party at the Lucky Strike, but by this point the jet lag and large amounts of food caught up to me, so I decided to go back to my hotel early.

Day 1 – Tuesday

This is when the real event starts! Microsoft had built a huge tent just for the conference. After a long wait in the lineup, we found our way inside, and watched Steve Ballmer give the keynote address. He delivered a solid performance, demonstrating the beauty of Windows 8 on many different devices. After his speech, I was even prouder than before to be a Microsoft developer! Some of my friends may say I’ve been brainwashed… oh, well, that’s OK!

WP_000148

IMG_3711

At the end of Steve Ballmer’s presentation, I could tell by the tone of his voice that he was about to give us something good. It started off with 100GB of SkyDrive space for everyone forever. Nice! Then came the “Free Surface” moment, although he did extract a promise from us that we’ll create applications for it. Sign me up! After that, there was “one more guest”, from Nokia, who announced that everyone would be receiving a Nokia Lumia 920. The feeling I had at the end of all this is hard to describe. Perhaps the “kid on Christmas morning” is the best way!

After the keynote address was over, I attended two sessions and visited the Microsoft employee store. Starting at 7pm, we could go and pick up our gifts, but the line up was just too crazy, so Marios and I decided to wait until the following morning. Besides, we had the Build Blogger Bash at the Lucky Strike to attend. I met two of my favourite bloggers there; Paul Thurrott and Mary Jo Foley.

Day 2 – Wednesday

Not wanting to go any more time without our gifts, Marios and I woke up early and went directly to the registration booth to get our devices. Instead of a two hour line up, it was only a two minute line up. At breakfast, I opened up the Lumia 920 and was instantly impressed by the device and the WP8 OS. Sadly, I had sessions to attend, so I had to put it away for a little while. The second keynote was all about Azure. It’s interesting, and definitely something I want to learn more about, but there are only so many hours in a day, and mine will be focused on Windows 8 and Windows Phone 8 for now.

WP_000165

I attended two more sessions during the day. I also registered to take certification exams in C# and Windows 8 Apps the next day. Normally, the exams cost $150 each, but Microsoft waived the cost for Build attendees for the week. That evening, I convinced Marios to participate in a hackathon with me (you know, because we weren’t busy enough already…). We coded all evening, and even skipped the beer fest! When I arrived back at the hotel, I finally had the opportunity to open the box containing my Surface. I played around a while, learning about it, then I went to bed.

Day 3 – Thursday

This was by far the busiest, craziest day of the week. After breakfast in the tent, I wrote my two exams. The C# exam went well and I passed, but the Windows 8 App one proved too much for me right now. I still have a few more things to learn. After that, I went back to work on our App for the hackathon, with Marios joining me an hour later. We finished our feature set with five minutes to spare before the 5:30pm deadline. It’s always a strange feeling, coding under pressure. The adrenaline is high, and it’s a joy when we finish.

That evening was the big Build party in Seattle. The party reminded me of the Ubisoft Christmas parties that I have attended. Hundreds of people show up, there’s lots of unhealthy food to eat, and some entertainment. Microsoft provided some old consoles like Atari and Sega to play with. At the end of the party, Marios and I found out that our hackathon App was not one of the finalists. I guess we should have added Azure, but it was fun to participate anyway.

WP_20121101_015

WP_20121101_016

Gorgeous picture from the Nokia Lumia 920 under low light condition:

WP_20121101_019

Day 4 – Friday

This being the last day, there were fewer sessions to attend, although I still attended all of them. One of the problems at big conventions like this is that there is usually more than one thing going on at a time that I want to see. Lucky for me, all the sessions are recorded. In the next few weeks, I plan on watching the ones that I missed. My favourite session on Friday was about portable libraries. From now on, I’m going to try to use this feature in my Windows 8 and Windows Phone 8 apps. I also had a chance to talk to Jean-Christophe Cimetiere, who is the Director of Windows Phone Developer and Partner Programs. It’s always good to have contacts at Microsoft.

At the end of the day, I caught up on my emails and enjoyed a dinner with Marios and Lia. It felt good to relax!

WP_20121101_001

Saturday the 3rd

Once again, I had a free day to spend in Seattle. I wandered around downtown in the afternoon, and for once, it didn’t rain. Despite the rain, the people in Seattle are nice and helpful.

Microsoft campus

For many years, I have wanted to visit the Microsoft campus. After spending a week there, I can say that I’ve visited some of it. It’s huge. There are more than 120 buildings, and most of them are really big. I would need my bike to visit the whole campus. It’s bigger than a lot of university campuses. It’s like a city-inside-a-city. There’s a Microsoft Commons building, with regular stores, where you can buy musical instruments, skis, etc. You can even book an appointment with an optician. And just like a city, it has its own transit system, called the Microsoft Connector. MC transports employees around in the morning and evening. The campus is surrounded by green areas and lots of trees.

Now

All good things must come to an end, but I’m returning home very satisfied and happy. I met some great people, great developers. I’m looking forward to creating Windows 8 and WP8 apps with all the new features available to us. There’s no better time than now to develop for the Microsoft platform.

Hope to see you again BUILD.

Let’s code!

Sébastien alias ArchieCoder

How to use the ButtonImage control that supports the Pressed and IsEnabled states

Introduction

There is a lot of examples in the Windows Phone community about creating a button with an image only. We can achieve this result with the following code:

<Button>
    <Image Source="MyImage.png"/>
</Button>

The problem with the previous code is the impossibility to set a different image when the button is disabled or pressed.


Solution

I created a ButtonImage class to set a different image for the disabled and the pressed states.

If you are not interested on the code of the ButtonImage class, you can skip this section and go directly to the Usage section.

The ButtonImage class has XML code and C# code.

XML code

<Button x:Class="DotNetApp.ButtonImage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    IsEnabledChanged="ButtonIsEnabledChanged"
    MouseEnter="ButtonMouseEnter"
    MouseLeave="ButtonMouseLeave">

    <Image Stretch="None"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        x:Name="image" />
</Button>

There is nothing fancy here, it is a button that has an image has content.

C# code

using System;
using System.Windows;
using System.Windows.Media.Imaging;

namespace DotNetApp
{
    public partial class ButtonImage
    {
        #region Fields

        public new static readonly DependencyProperty IsEnabledProperty = DependencyProperty.Register("IsEnabled", typeof (bool), typeof (ButtonImage), null);
        public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof (string), typeof (ButtonImage), null);
        public static readonly DependencyProperty ImagePressedSourceProperty = DependencyProperty.Register("ImagePressedSource", typeof (string), typeof (ButtonImage), null);
        public static readonly DependencyProperty ImageDisabledSourceProperty = DependencyProperty.Register("ImageDisabledSource", typeof (string), typeof (ButtonImage), null);

        private BitmapImage _image;
        private BitmapImage _imagePressed;
        private BitmapImage _imageDisabled;
        private bool _isPressed;

        #endregion

        #region Constructor

        public ButtonImage()
        {
            InitializeComponent();
        }

        #endregion

        #region Properties

        public new bool IsEnabled
        {
            get { return (bool)GetValue(IsEnabledProperty); }

            set
            {
                SetValue(IsEnabledProperty, value);

                SetImageFromState();
            }
        }

        public string ImageSource
        {
            get { return (string) GetValue(ImageSourceProperty); }

            set
            {
                SetValue(ImageSourceProperty, value);

                _image = SetImage(value);
                SetImageFromState();
            }
        }
        
        public string ImagePressedSource
        {
            get { return (string) GetValue(ImagePressedSourceProperty); }

            set
            {
                SetValue(ImagePressedSourceProperty, value);

                _imagePressed = SetImage(value);
                SetImageFromState();
            }
        }

        public string ImageDisabledSource
        {
            get { return (string) GetValue(ImageDisabledSourceProperty); }

            set
            {
                SetValue(ImageDisabledSourceProperty, value);

                _imageDisabled = SetImage(value);
                SetImageFromState();
            }
        }

        #endregion

        #region Event Handlers

        private void ButtonIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            SetImageFromState();
        }

        private void ButtonMouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            _isPressed = true;

            SetImageFromState();
        }

        private void ButtonMouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            _isPressed = false;

            SetImageFromState();
        }

        #endregion

        #region Private Methods

        private static BitmapImage SetImage(string imageSource)
        {
            BitmapImage bitmapImage = null;

            if (!string.IsNullOrEmpty(imageSource))
            {
                bitmapImage = new BitmapImage(new Uri(imageSource, UriKind.RelativeOrAbsolute));
            }

            return bitmapImage;
        }

        private void SetImageFromState()
        {
            if (!IsEnabled)
            {
                image.Source = _imageDisabled;
            }
            else if (_isPressed)
            {
                image.Source = _imagePressed;
            }
            else
            {
                image.Source = _image;
            }
        }

        #endregion
    }
}

Once again, there is nothing scientific here. I load the images and based on the event handlers (ButtonIsEnabledChanged, ButtonMouseEnter and ButtonMouseLeave), I set the right image.


Usage

ButtonImage.png

The button has an image for each state:

  • Normal

ImageNormal.png

  • Pressed

ImagePressed.png

  • Disabled

ImageDisabled.png

To use the ButtonImage control in your app, just follow those steps:

  1. Add the files ButtonImage.xaml and ButtonImage.xml.cs to your project.
  2. Add the normal image, the pressed image and the disabled image to your project. If your button does not need a pressed image or a disabled image, you don’t have to specify one.
  3. Add the XML code
<ButtonImageApp:ButtonImage ImageSource="/ImageNormal.png"
                                                    ImageDisabledSource="/ImageDisabled.png"
                                                    ImagePressedSource="/ImagePressed.png"
                                                    Style="{StaticResource ButtonImageStyle}"
                                                    Height="50"
                                                    Width="150" />

All the properties are important. The ImageSource, ImageDisabledSource, ImagePressedSource are the actual images that you want for each state. The Height and the Width need to be the same as the specified images.

The last piece of the puzzle is the Style property set to "{StaticResource ButtonImageStyle}". If you do not set this property, there will be an unwanted transparent area around the image and the image will be smaller. Your last step is to define the ButtonImageStyle into your project. You can add it into your page or in the App resources section. The code to copy is:

Page

<phone:PhoneApplicationPage.Resources>

    <Style x:Key="ButtonImageStyle"
            TargetType="ButtonImageApp:ButtonImage">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ButtonImageApp:ButtonImage">
                    <Grid Background="Transparent">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="MouseOver" />
                                <VisualState x:Name="Pressed" />
                                <VisualState x:Name="Disabled" />
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="ButtonBackground">
                            <ContentControl x:Name="ContentContainer"
                                            ContentTemplate="{TemplateBinding ContentTemplate}"
                                            Content="{TemplateBinding Content}" />
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</phone:PhoneApplicationPage.Resources>

or App

<Application.Resources>

    <Style x:Key="ButtonImageStyle"
        TargetType="ButtonImageApp:ButtonImage">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ButtonImageApp:ButtonImage">
                    <Grid Background="Transparent">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="MouseOver" />
                                <VisualState x:Name="Pressed" />
                                <VisualState x:Name="Disabled" />
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="ButtonBackground">
                            <ContentControl x:Name="ContentContainer"
                                        ContentTemplate="{TemplateBinding ContentTemplate}"
                                        Content="{TemplateBinding Content}" />
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</Application.Resources>


Conclusion

The ButtonImage derives from a Button so you can add a Command or the Click handler.


Download

My WinSource app is now open source on the Nokia developer website

Introduction

In the summer 2012, the ​WinSource website held a contest among the Windows Phone developers to create an official application for their website.

I was a participant in the contest and I can tell you that it was a really interesting and challenging contest. My application finished in third position.

You can download the application from the winner at ​here.

Important notice

Before I decided to put the full source code of my complete application. I asked the owners of the ​WinSource from the Neverstill company if I can publish the source code of my application. They accepted my idea, because it is a great way to help the Windows Phone community.

In the current form, the application has enough features that it can be an alternate ​WinSource application. The only restriction is a user cannot publish or use the ​WinSource’s logo, the assets or the content from the ​WinSource. NOTE, this project is ​licensed under a slightly modified MIT license which reflects the above restriction.

The purpose of having this open project is to help the community creating a professional news reader for any other websites that give the permissions. It also shows different concepts which can be applied in different type of applications.

The application

https://projects.developer.nokia.com/dav/newsreaderpro/WinSource.png

My application contains the following features:

  • The metro design is used throughout the app, while the main page is showcased using the panorama design.
  • Fast navigation between pages.
  • Articles classified by date.
  • Play YouTube videos.
  • A description of each team member, including a display of the author name & image on each author’s page. Also included is the option to send the author an email.
  • Article links can be shared on Twitter, Windows Live, Facebook, or by email.
  • The application bar contains shortcuts to the Facebook page and the Twitter page of the website.
  • The About page provides a way to send an email and to write a review of the app.
  • Option to automatically refresh articles when the application launches.

The following list contains advanced features:

  • Offline mode. Articles can be read even when no internet connection is available.
  • Unlimited space for saving articles, which can then be accessed using the Saved Articles page.
  • Articles can be periodically downloaded (every ~4 hours) in the background, even when the app is not running. This feature does not require server support.
  • Toast notification will display the number of new articles available, and a badge count in the application live tile will also display this number.
  • The back of the live tile will display the latest article title.

https://projects.developer.nokia.com/dav/newsreaderpro/LiveTileAndToastNotification.png

The application uses the Pivot control for the team members:
https://projects.developer.nokia.com/dav/newsreaderpro/Pivot.png
And a standard page for an article:
https://projects.developer.nokia.com/dav/newsreaderpro/Article.png

Open source libraries

I used three open source libraries that are well known in the developer community:

Architecture

I use the Model View-Model View (MVVM) pattern in my solution. The solution is separated in five assemblies:

  • DotNetApp.Toolkit: It includes utility classes that can be reused in any Windows Phone projects. There is also my Request class that helps calling web resources.
  • WinSource: This is the main project that includes the views, the data service, the view models and many more things.
  • WinSource.Agent: It is the project that includes the schedule background service which permits to periodically download articles in the background.
  • WinSource.Client: It contains all the web requests.
  • WinSource.Model: It contains only the data structure.

You won’t find a lot of comment in my code, but I’m an heavy user on code convention and I tend use write small methods so the code should be self-explanatory.

How to build the application

All the required files are built-in in the solution. Make sure that the selected project is “WinSource” then press F5 to launch the application.

  • The application has been tested with the Windows Phone SDK 7.1.

Future of the application

The application in its current form contains more features then some published news applications in the Windows Phone Store. That’s been said, the application is in a release state. As all software, it is always possible to polish and add features. You are welcome to add and suggest features.

What can you do with the source files of the application?

Simple answer: create your own news application! The source files provided are the best starting point to get your news application ready. The mechanism is ready and your tasks are:

  • Replace the assets in the Assets folder of the WinSource assembly.
  • Modify the classes in the WinSource.Client assembly in order to fetch the article descriptions and videos from your news source.
  • Remove or add sections in the Panorama.
Learning

Also, if you read the code you can learn a lot about the Windows Phone SDK and about some best practices. The application is more complete than the ones in the MSDN samples.

Conclusion

You can contribute directly to the project on the Nokia developer website or you can download the source code.

Happy coding!

Contribute on the Nokia developer website
Download Sample project

How to create simple animation in your Windows Phone app

Creating animations in your Windows Phone application is easier than you think.

I created a simple application that shows how to create a static animation and a dynamic animation. Both animations fill the following red rectangle from the bottom to the top.

image

Static animation

An animation uses a Storyboard object. It is usually created in the XAML file, because it is easier this way. Here is the XAML code:

<phone:PhoneApplicationPage x:Class="SimpleAnimationApp.StaticAnimationPage"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone">

    <phone:PhoneApplicationPage.Resources>

        <Storyboard x:Name="staticAnimation">

            <DoubleAnimation Duration="0:0:5"
                             To="700"
                             Storyboard.TargetProperty="Height"
                             Storyboard.TargetName="rectangleRed" />

        </Storyboard>

    </phone:PhoneApplicationPage.Resources>
    
    <Grid>

    <Rectangle Fill="Blue"
               Height="700"
               Width="100"
               VerticalAlignment="Bottom"/>

    <Rectangle Fill="Red"
               Height="0"
               Width="100"
               VerticalAlignment="Bottom"
               x:Name="rectangleRed"/>

    </Grid>

</phone:PhoneApplicationPage>

The DoubleAnimation is the simplest animation available, it animates a property that uses a double value. The above double animation is defined like this: Animate the Height property of the rectangleRed object from the current Height value to 700 in 5 seconds.

To start the animation, you need to call the Begin method on the animation:

using System.Windows.Navigation;

namespace SimpleAnimationApp
{
    public partial class StaticAnimationPage
    {
        public StaticAnimationPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            staticAnimation.Begin();
        }
    }
}

It is not used in the sample app, but if you want to stop an animation at any time, you just have to call the Stop method on the animation.


Dynamic animation

For the dynamic animation, let’s pretend that the properties Duration and To are specified in the code behind. We have the similar XAML code:

<phone:PhoneApplicationPage x:Class="SimpleAnimationApp.DynamicAnimationPage"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone">

    <phone:PhoneApplicationPage.Resources>

        <Storyboard x:Name="dynamicAnimation">

            <DoubleAnimation Storyboard.TargetProperty="Height"
                             Storyboard.TargetName="rectangleRed"
                             x:Name="doubleAnimation" />

        </Storyboard>

    </phone:PhoneApplicationPage.Resources>
    
    <Grid>

    <Rectangle Fill="Blue"
               Height="700"
               Width="100"
               VerticalAlignment="Bottom"/>

    <Rectangle Fill="Red"
               Height="0"
               Width="100"
               VerticalAlignment="Bottom"
               x:Name="rectangleRed"/>

    </Grid>

</phone:PhoneApplicationPage>

There is one addition of the x:Name=”doubleAnimation” which will help to control the animation in the code behind:

using System;
using System.Windows.Navigation;

namespace SimpleAnimationApp
{
    public partial class DynamicAnimationPage
    {
        public DynamicAnimationPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            doubleAnimation.Duration = new TimeSpan(0, 0, 0, 10);
            doubleAnimation.To = 350;

            dynamicAnimation.Begin();
        }
    }
}

Before starting the animation, I set the Duration to 5 seconds and the To to 350 which is half the size of the blue rectangle.

It is not complicated to create an animation. Those were simple animations, but if you want to create more complex animations and even combine animations, you can find more information on the web.

Put some life in your control!

Download Sample project

Windows Phone 8 SDK new features for developers

I dug in the Windows Phone 8 object browser and I found some interesting classes:

Microsoft.Phone.Controls.WebBrowserExtensions

In WP7, there is only the GetCookies method.
In WP8, there are the new ClearCookiesAsync and ClearInternetCacheAsync methods.

Windows.Phone.Networking.NetworkOperators.SmsInterceptor

There is a event called SmsReceived which could be really interesting to use. However, there is a little note saying: “This API is not intended to be used directly from your code”.

Windows.UI.Input.EdgeGesture, Windows.Devices.Input.MouseCapabilities and Windows.Devices.Input.KeyboardCapabilities

They all seem interesting, but I was not able to instantiate them. I get this exception: Requested Windows Runtime type ‘Windows.Devices.Input.MouseCapabilities’ is not registered.

Windows.ApplicationModel.Store

This namespace contains a lot of cool classes:

  • LicenseInformation (ExpirationDate, IsActive, IsTrial, ProductLicences).
  • ListingInformation (AgeRating, CurrentMarket, Description, FormattedPrice, Name, ProductListings)
  • ProductLicense (ExpirationDate, IsActive, IsConsumable, ProductId)
  • ProductListing (Description, FormattedPrice, ImageUri, Keywords, Name, ProductId, ProductType, Tag)
  • CurrentApp (GetAppReceiptAsync, LoadListingInformationAsync, LoadListingInformationByKeywordsAsync, RequestProductPurchageAsync)

I hope these classes will be available to use in applications. They could be useful in making marketplace apps!

Windows.System.Launcher

The Launcher class has LaunchFileAsync and LaunchUriAsync. The summary of LaunchUriAsync is: Starts the default app associated with the specified file or protocol.

I tried it with the protocol mailto:email@company.com and it launched the mail application! It will be cool if applications can register file type. Please note that I did not see a way to do that.

There are a lot more, but because I’m not sure if they will be available in the release version, it will better to wait for the final bits of the SDK.