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.

Windows Phone 8 shared core with Windows 8 – File IO

For developers, the biggest news for Windows Phone 8 is that it shares a core with Windows 8. It means that your code has more chances than ever before to be compatible on both platforms.

One of the easier components and surely the most used in applications is the File IO component. In this post, I’ll also cover the Windows Phone 7 code compatibility.

In Windows Phone 7

To write a file, you use the IsolatedStorageFile:

private void WriteFile(string fileName, string content)
{
    using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.CreateFile(fileName))
        {
            using (StreamWriter streamWriter = new StreamWriter(isolatedStorageFileStream))
            {
                streamWriter.Write(content);
            }
        }
    }
}

To read a file:

private string ReadFile(string fileName)
{
    string text;

    using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.OpenFile(fileName, FileMode.Open))
        {
            using (StreamReader streamReader = new StreamReader(isolatedStorageFileStream))
            {
                text = streamReader.ReadToEnd();
            }
        }
    }

    return text;
}

In Windows Phone 8

To write a file, you use the Windows.Storage component. The file and folder objects are respectively IStorageFile and IStorageFolder. The usage of the await and async keywords come in.

To write a file:

public async Task WriteFile(string fileName, string text)
{
    IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;

    IStorageFile storageFile = await applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

    using (Stream stream = await storageFile.OpenStreamForWriteAsync())
    {
        byte[] content = Encoding.UTF8.GetBytes(text);
        await stream.WriteAsync(content, 0, content.Length);
    }
}

To read a file:

public async Task<string> ReadFile(string fileName)
{
    string text;
    IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;

    IStorageFile storageFile = await applicationFolder.GetFileAsync(fileName);

    IRandomAccessStream accessStream = await storageFile.OpenReadAsync();

    using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
    {
        byte[] content = new byte[stream.Length];
        await stream.ReadAsync(content, 0, (int) stream.Length);

        text = Encoding.UTF8.GetString(content, 0, content.Length);
    }

    return text;
}

You can use these methods this way:

await WriteFile("Dummy.txt", "I love the Windows Phone");
string text = await ReadFile("Dummy.txt");

You can see that the code between Windows Phone 7 and Windows Phone 8 is quite different.

Compatibility

As we know already, Microsoft announced that the Windows Phone 7 applications will run on Windows Phone 8. This is great news. What is even better is that your Windows Phone 7 code that uses the IsolatedStorage will compile without any changes in Windows Phone 8. You can take the Windows Phone 7 code above and it will work.

You might be wondering if the internal folder structure is different between WP7 and WP8… The difference is minor.

In WP7, if you create a file at the root, the file will point to:

C:DataUsersDefaultAppAccountAppData{9679D8C4-24B4-41DF-85C5-5E099947F109}LocalIsolatedStoreDummy.txt

In WP8, the same file created at the root will be in:

C:DataUsersDefaultAppAccountAppData{9679D8C4-24B4-41DF-85C5-5E099947F109}LocalDummy.txt

The difference is the IsolatedStore folder added in WP7. It means that if you have old WP7 code that you would like to use with new WP8 code, you just have to get the IsolatedStore folder:

IStorageFolder applicationFolder = 
    await ApplicationData.Current.LocalFolder.GetFolderAsync("IsolatedStore");

In the end, you can mix both WP7 and WP8 code in your next Windows Phone 8 application. However, I would encourage you to use only the Windows Phone 8 version, as it will then be easier for you to use the same code in Windows 8.

Windows Phone 8 Battery API

The Battery API makes a nice addition to the WP8 SDK.

I can see in the near future that some applications will display the battery metrics on a Live Tile or in the application that hides the System Tray.

The Battery API is pretty easy to use:
1- Get the Battery instance with Battery.GetDefault().
2- Bind to the event RemainingChargePercentChanged.

The battery properties are:
RemainingChargePercent: gets a value that indicates the percentage of the charge remaining on the phone’s battery.
RemainingDischargeTime: gets a value that estimates how much time is left until the phone’s battery is fully discharged. 

With the following code:

using Windows.Phone.Devices.Power;

namespace BatteryApp
{
    public partial class MainPage
    {
        private readonly Battery _battery;

        public MainPage()
        {
            InitializeComponent();

            _battery = Battery.GetDefault();

            _battery.RemainingChargePercentChanged += OnRemainingChargePercentChanged;

            UpdateUI();
        }

        private void OnRemainingChargePercentChanged(object sender, object e)
        {
            UpdateUI();
        }

        private void UpdateUI()
        {
            textBlockRemainingCharge.Text = string.Format("{0} %", _battery.RemainingChargePercent);
            textBlockDischargeTime.Text = string.Format("{0} minutes", _battery.RemainingDischargeTime.TotalMinutes);
        }
    }
}

You get:

image


Please note that when running this on the emulator, it will show 100% and an infinite discharge time. The above values are fake.

Get ready to code!

Windows Phone 8 upcoming Live Tile feature

With all the buzz this week about the Windows Phone 8 SDK leak, I couldn’t resist installing it.

The title of the SDK is Windows Phone 8 Developer Preview. There are so many cool new features that initially, I didn’t know where to start. I decided to start with one of the new features of the live tiles, since this is the Windows Phone’s biggest strength.

I don’t know the exact feature name, but it’s about cycling images in a live tile. Here is a little video that will help to describe the feature.

Cycling images in a Live Tile

Have you spotted the difference between the Windows Phone 7 badge count and the new OS? It is now in a square instead of a circle!

What I love about Microsoft is that they make it easy for developers to use their APIs.

Follow these two steps to accomplish what you see in the video:
1- Add up to 9 images to the project and set the Build Action to Content. The images need to be local only.
2- Append the following code

ShellTile appTile = ShellTile.ActiveTiles.First();

if (appTile != null)
{
    Uri uri1 = new Uri("/Assets/UltimatePokerManager.png", UriKind.Relative);
    Uri uri2 = new Uri("/Assets/YourShape.png", UriKind.Relative);

    CycleTileData cycleTileData = new CycleTileData
                                        {
                                            Count = 3, 
                                            CycleImages = new[] {uri1, uri2}
                                        };

    appTile.Update(cycleTileData);
}

The UtimatePokerManger.png and YourShape.png have the size 173×173. When you watched the video, the images were expanded.

Please note that the SDK is in preview and there is no guarantee that the APIs will be the same in the released version, but I bet this feature will stay as it is.

This was my first Windows Phone 8 blog post and is surely not the last!

How to backup your Windows Phone app data to a server such as GoDaddy

Here is a complete step-by-step guide to create a WCF backup service for your Windows Phone applications.

You can implement your own hosting service with a cheap hosting server like GoDaddy. You can find deal at $5/month. Personally, I find it more professional saving your application data to a private server or in a cloud solution instead of relaying on SkyDrive.

To accomplish this, two things are required:
A- Implementing the service on your server.
B- Implementing the client code to send your data.

Alternatively, you can download the complete solution at the end of the article.

A) Server side

1- Let’s start with the hardest part. After you find a hosting server that supports the framework .NET 4.0, you create the WCF Service Application:

image

2- Rename the file IService1.cs to IFileUploader.cs

3- Replace the content of the IFileUploader.cs with:

using System.Runtime.Serialization;
using System.ServiceModel;

namespace FileUploadService
{
    [ServiceContract]
    public interface IFileUploader
    {
        // Returns null when there is no error, otherwise it is the exception message.
        [OperationContract]
        string Upload(UploadFile uploadFile);
    }

    [DataContract]
    public class UploadFile
    {
        // Don't forget to set the variable FileUploadDirectoryWithReadWritePermission in your Web.config and set read/write permission in your web hosting.
        // RelativeDirectory should be in the form as /Path1/Path2/ or null for the root directory.
        [DataMember]
        public string RelativeDirectory { get; set; }

        [DataMember]
        public string FileName { get; set; }

        [DataMember]
        public byte[] Content { get; set; }
    }
}

This interface contains only the Upload method. The Upload needs a UploadFile which contains only 3 properties: RelativeDirectory, FileName and Content.

4- Rename the file Service1.svc to FileUploader.svc.

5- Replace the content of FileUploader.svc with:

using System;
using System.Configuration;
using System.IO;
using System.Web.Hosting;

namespace FileUploadService
{
    public class FileUploader : IFileUploader
    {
        #region IFileUploader Members

        public string Upload(UploadFile uploadFile)
        {
            string message = null;

            try
            {
                string path = HostingEnvironment.MapPath(string.Format("~/{0}",ConfigurationManager.AppSettings["FileUploadDirectoryWithReadWritePermission"]));
                
                if (path != null)
                {
                    if (uploadFile.RelativeDirectory != null && uploadFile.RelativeDirectory.StartsWith("/"))
                    {
                        path = string.Concat(path, uploadFile.RelativeDirectory);
                    }

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    if (!string.IsNullOrEmpty(uploadFile.FileName))
                    {
                        using (FileStream fileStream = File.Open(Path.Combine(path, uploadFile.FileName), FileMode.Create))
                        {
                            using (var binaryWriter = new BinaryWriter(fileStream))
                            {
                                binaryWriter.Write(uploadFile.Content);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                message = exception.Message;
            }

            return message;
        }

        #endregion
    }
}

6- Replace the content of the Web.config with:

<?xml version="1.0"?>

<configuration>

  <appSettings>
    <add key="FileUploadDirectoryWithReadWritePermission" value="/backup/" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off" />
  </system.web>

  <system.serviceModel>

    <behaviors>
      <serviceBehaviors>
        <behavior name="FileUploadBehavior">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <services>
      <service behaviorConfiguration="FileUploadBehavior" name="FileUploadService.FileUploader">
        <endpoint address="" name="basicHttpStream" binding="basicHttpBinding"
                  bindingConfiguration="httpLargeMessageStream" contract="FileUploadService.IFileUploader" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>

    <bindings>
      <basicHttpBinding>
        <binding receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00"
                 name="httpLargeMessageStream" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
          <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />
        </binding>
      </basicHttpBinding>
    </bindings>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>

</configuration>

This file has two important sections:

– The parameter FileUploadDirectoryWithReadWritePermission is used by the file FileUploader.svc and it will be used in your public folder later.

  <appSettings>
    <add key="FileUploadDirectoryWithReadWritePermission" value="/backup/" />
  </appSettings>

– The section about the length of the service parameters: You don’t need to understand everything here. It just works as is. If you are curious, I invite you to read the documentation on MSDN.

<bindings>
      <basicHttpBinding>
        <binding receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00"
                 name="httpLargeMessageStream" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
          <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />
        </binding>
      </basicHttpBinding>
    </bindings>

7- The service is ready to be published. Right-click on the FileUploadService project and choose Publish. Depending on your web hosting service, you need to set the info.

For GoDaddy:

– Use the FTP method.

– Set the target location. For me, I used ftp://ftp.ultimatepokermanager.com/upm/ServerTest

– Set the credentials 

image

8- The trickiest part is to configure the application settings for the WCF service in the hosting service. In GoDaddy, it’s in the IIS Management in the Tools section. You need to check Anonymous Access and Set Application Root.

The upmservertest points to http://www.ultimatepokermanager.com/upm/servertest

image

8- To check if your service is running, open your browser and put the address of the web service. With my web service, the address is:

http://www.ultimatepokermanager.com/upm/servertest/FileUploader.svc

If you see something like the following image, you’re good to go!

image

B) Client side

I created a simple application that sends a string into a file in the server.

image

1- Create a Windows Phone Application. I assume that you know how to do this step.

2- The WCF service client FileUploader needs to be added to the project. Right-click on the Windows Phone project and click on Add Service Reference.

image

– Put the address of your WCF service. In this example, it is http://www.ultimatepokermanager.com/upm/servertest/FileUploader.svc 
– Rename the namespace to FileUploader.

– Click OK.

3- Replace the content of the MainPage.xaml with:

<phone:PhoneApplicationPage x:Class="SendFileApp.MainPage"
                            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"
                            xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
                            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                            mc:Ignorable="d"
                            d:DesignWidth="480"
                            d:DesignHeight="800"
                            FontFamily="{StaticResource PhoneFontFamilyNormal}"
                            FontSize="{StaticResource PhoneFontSizeNormal}"
                            Foreground="{StaticResource PhoneForegroundBrush}">

    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <StackPanel Margin="12,17,0,28">

            <TextBlock Text="SEND FILE"
                       Style="{StaticResource PhoneTextNormalStyle}" />

            <TextBlock Text="dashboard"
                       Margin="9,-7,0,0"
                       Style="{StaticResource PhoneTextTitle1Style}" />

        </StackPanel>

        <StackPanel Grid.Row="1"
                    Margin="12,0,12,0">

            <TextBlock Margin="12,0,0,0"
                       Text="Content" />

            <TextBox Text="abcdefg"
                     x:Name="textBoxContent" />

            <TextBlock Margin="12,0,0,0"
                       Text="File name" />

            <TextBox Text="Sample.txt"
                     x:Name="textBoxFileName" />

            <Button Content="Send File"
                    Click="ButtonSendFile" />

            <Button Content="Download File"
                    Click="ButtonDownloadFile"
                    IsEnabled="False"
                    x:Name="buttonDownloadFile"/>

        </StackPanel>

    </Grid>

</phone:PhoneApplicationPage>

This content uses only standard controls.

4- Replace the content of MainPage.xaml.cs with:

using System;
using System.Net;
using System.Text;
using System.Windows;
using SendFileApp.FileUploader;

namespace SendFileApp
{
    public partial class MainPage
    {
        #region Constants

        // For this sample, the uploaded file can be access from my public folder
        private const string PublicServer = "http://www.ultimatepokermanager.com/upm/ServerTest/backup";

        #endregion

        #region Fields

        private string _directory;

        #endregion

        #region Constructor

        public MainPage()
        {
            InitializeComponent();
        }

        #endregion

        #region Event Handlers

        private void ButtonSendFile(object sender, RoutedEventArgs e)
        {
            byte[] content = Encoding.UTF8.GetBytes(textBoxContent.Text);
            _directory = Guid.NewGuid().ToString();

            FileUploaderClient fileUploaderClient = new FileUploaderClient();
            fileUploaderClient.UploadCompleted += UploadCompleted;
            
            fileUploaderClient.UploadAsync(new UploadFile { RelativeDirectory = string.Format("/{0}", _directory), FileName = textBoxFileName.Text, Content = content });
        }

        private void UploadCompleted(object sender, UploadCompletedEventArgs uploadCompletedEventArgs)
        {
            buttonDownloadFile.IsEnabled = true;

            if (uploadCompletedEventArgs.Result == null)
            {
                MessageBox.Show("The file has been successfully uploaded.", "Success!", MessageBoxButton.OK);
            }
            else
            {
                MessageBox.Show(string.Format("An error occured:nn{0}", uploadCompletedEventArgs.Result), "Error", MessageBoxButton.OK);
            }
        }

        private void ButtonDownloadFile(object sender, RoutedEventArgs e)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += WebClientDownloadStringCompleted;

            webClient.DownloadStringAsync(new Uri(string.Format("{0}/{1}/{2}", PublicServer, _directory, textBoxFileName.Text)));
        }

        private void WebClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs downloadStringCompletedEventArgs)
        {
            if (downloadStringCompletedEventArgs.Error == null)
            {
                MessageBox.Show(string.Format("The content of your file is:nn{0}", downloadStringCompletedEventArgs.Result), "Success!", MessageBoxButton.OK);
            }
            else
            {
                MessageBox.Show(string.Format("An error occured:n{0}", downloadStringCompletedEventArgs.Error), "Error", MessageBoxButton.OK);
            }
        }

        #endregion
    }
}

The interesting part in the previous code is:

private void ButtonSendFile(object sender, RoutedEventArgs e)
{
    byte[] content = Encoding.UTF8.GetBytes(textBoxContent.Text);
    _directory = Guid.NewGuid().ToString();

    FileUploaderClient fileUploaderClient = new FileUploaderClient();
    fileUploaderClient.UploadCompleted += UploadCompleted;
    
    fileUploaderClient.UploadAsync(new UploadFile { RelativeDirectory = string.Format("/{0}", _directory), FileName = textBoxFileName.Text, Content = content });
}

The usage of the FileUploaderClient is really simple:

1- Create the instance FileUploaderClient.

2- Listen to the UploadCompleted event.

3- Upload the file asynchronously.

Please note that the UploadFile needs the properties RelativeDirectory (which starts with a “/”), a FileName and the Content in an array of bytes.

An example of an uploaded file address is: http://www.ultimatepokermanager.com/upm/ServerTest/backup/a5a8ae0b-50f0-4d16-90da-e83d6e1d30a3/Sample.txt. You can see the backup directory previously set in the Web.config file.

In the sample, I generated a GUID for the directory name. Also, the uploaded files are public as long as the user (or the application) knows about the directory name and the file name. If you want to add a layer of privacy, you just have to implement a DownloadFile method into your service. It should not be difficult if you read the code of the Upload method.

I guarantee you that you’ll be happy to see when your web service is working!

Download Sample project

Book Review: Windows Phone 7.5 Unleashed

In the past year and a half, I have read a lot of Windows Phone books. The first book I read was the excellent 101 Windows Phone 7 apps. At that time, I was recommended that book, but ever since Microsoft released the Mango update, 101 is a bit out of date.

At the end of 2011, I read Essential Windows Phone 7.5 by Shawn Wildermuth. I recommend this book for someone who has never owned a Windows Phone and who wants to start programming for the Windows Phone. It is an excellent book for beginners, as the author spends time about on basic Windows Phone concepts.

Now to my review of the latest Windows Phone book I have read: Windows Phone 7.5 Unleashed by Daniel Vaughan.

WP7U

This book is huge with 1120 pages, and all of them are worth it. Here are some of the things that I like about the book:

  • Most of the code samples are done with the MVVM pattern. Nowadays, this pattern is the most popular one used when creating Windows Phone applications. The author even shares his known Calcium SDK that includes the MVVM philosophy. For a beginner who wants to start Windows Phone programming, starting off with the best pattern is a great idea, and this book will help you do that.
  • There is a lot of free code given. There are a lot of utility classes that can be used in many types of Windows Phone applications. Honestly, the book is worth buying for the free code alone, and it will save you a lot of time.
  • If you are new to use the SQL Compact Server database, this book will help you to learn the technology; the author has a large helpful section on this topic.
  • The author introduced the usage of Reactive Extensions. This technology is not for beginners, but I’m pretty sure it will intrigue you, as it did me. The author presents the benefits of Reactive Extensions. The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. You can find the rest of the definition at the official website.
  • The author knows the platform well and describes many useful hints and caveats in Windows Phone programming.

In conclusion, this excellent book is one that I recommend right now if you want to dive into Windows Phone programming or to learn more about the recent features added with Mango.

Happy reading!