Running Zune and WP7 on VirtualBox

I have a fairly unique machine I develop on. I run Ubuntu as my host environment, and run development and office work off of virtual machines through VirtualBox with Windows 7. You may thinks it is a bit crazy but it has some real advantages if you have the patience to work through some of the nuances.

Ubuntu runs around 400 megs of RAM for the host, which compared to Windows 7 is insanely low; it’s quick, light, and stable. My virtual machines perform extremely well on the excess RAM (4 to 8 gigs) per VM and I readily create snapshots whenever installing new software or backing up my system(s). Additionally, I can run dedicated servers as VM’s to test enterprise applications without involving our internal networking resources until we’re ready to deploy to a test/staging environment.

With all of this being said, there are a few things that can drive you crazy; namely, Windows Phone 7 and Zune.

WP7 in VirtualBox

There are several articles on the Internet which discuss how VirtualBox and USB devices work, but here is the cliff-notes version:

USB devices can only be used by either the host or a client VM at any one time. Therefore, to use a USB device (such as WP7), you need to enable it from the VirtualBox Devices drop down (Devices > USB Devices > Unknown Device). Most likely, your device will be displayed as an Unknown Device.

Go ahead and select the device so that it now displays a checkbox next to the device. This should be enough to auto-start the Windows device driver installation which will most likely fail. You can open Device Manager to view the driver which should now be labeled USB Composite Device.

Windows Device Manager Screenshot

The reason this has failed is because by default, VirtualBox does not enable USB 2.0 (EHCI) Controller. You can enable this by opening the Settings for the VM you would like to connect your WP7 to, and selecting the USB tab on the left side. This will allow you to check the appropriate checkbox as seen in the following screenshot:

VirtualBox Enable USB 2.0 Screenshot

If you start the VM from this point you will most likely see the following error:

Oracle VM VirtualBox Extension Pack Required Screenshot

No worries, we simply need to install the Oracle VM VirtualBox Extension Pack to enable USB 2.0 support. I did pause to wonder why you have the ability to select Enable 2.0 USB within the out of the box application, yet it fails at the point of running the VM. It seems this warning could occur as soon as you select the checkbox or simply include the extension pack installation when selecting the checkbox to begin with. Regardless, you can download the extension pack from Oracle (http://www.oracle.com/technetwork/server-storage/virtualbox/downloads/index.html which should look similar to the following screenshot.)

Download VirtualBox Extension Pack Screenshot

After downloading, simply double click the file and you should receive the following prompt:

Install VirtualBox Extension Pack Screenshot

Once you have finished installing, run the VM and select the USB device again. This time, Windows will auto-install the device driver properly and you should receive the following success screen:

Windows Device Auto-Installation Success Screenshot

This may also auto-load Zune and attempt to sync your data for this VM. After completion you should be able to manage content on your phone just as you would a physical installation. Have fun, even busy coders need a bit of music to get through the day!

PhotoMemory WP7 App

The Basic Outline of Functionality

  1. Choose the difficulty mode to play in.
  2. Clear default picture values used in development.
  3. Set the board up based on the difficulty mode.
  4. Get personal photos from the phone.
  5. Shuffle photos and select appropriate number based on difficulty mode.
  6. Create pairs and shuffle all cards/photos.
  7. Display unturned cards and any already matched photos.
  8. Choose card and determine matches.
  9. Track number of moves and time.
  10. Display winner once all cards are matched.

PhotoMemory WP7 App

The Game Board (XAML)

The game board is basically a grid with several cells to hold the gradient cards or overturned photos. At the bottom, I keep track of number of moves and time expired.

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

        <toolkit:WrapPanel Grid.Row="0" x:Name="LayoutPanel" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <Image Source="Images/1.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/2.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/3.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/6.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/4.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/1.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/2.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/7.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/8.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/5.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/9.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/3.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/4.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/6.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/7.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/8.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/9.jpg" Width="150" Margin="5"></Image>
            <Image Source="Images/5.jpg" Width="150" Margin="5"></Image>
        </toolkit:WrapPanel>

        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <TextBlock Text="Moves:"></TextBlock>
            <TextBlock x:Name="MovesLabel" Foreground="Yellow" Text="0" Margin="10,0,0,0"></TextBlock>
            <TextBlock Text="Time:" Margin="50,0,0,0"></TextBlock>
            <TextBlock x:Name="TimeLabel" Foreground="Yellow" Text="0 seconds" Margin="10,0,0,0"></TextBlock>
        </StackPanel>
    </Grid>

PhotoMemory WP7 App

Highlighting a Few Areas of Development

Get Photos

A large part of the charm in this simple application is that it uses your own photos as the cards to match. I had pictures of my daughter and some wildlife we had taken while on a hiking trip (as well as some stock images that came with Windows 7) in my phone when I developed this app. Below is code to retrieve the photos from your phone – stored in MediaLibrary.

private List GetPhotos()
        {
            //Get photos from phone
            List photos = new List();
            var library = new MediaLibrary();
            var pics = library.Pictures.ToArray();

            //Shuffle user pics
            pics.Shuffle();

            //Loop through photos and add to game collection
            foreach (var pic in pics)
            {
                BitmapImage bmp = new BitmapImage();
                bmp.SetSource(pic.GetThumbnail());
                photos.Add(bmp);
            }

            //Check if enough photos are available
            if (photos.Count < _tileCount / 2)
            {
                //Setting default images if user does not have enough pictures of their own
                photos.Add(new BitmapImage(new Uri("Images/1.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/2.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/3.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/4.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/5.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/6.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/7.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/8.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/9.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/10.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/11.jpg", UriKind.Relative)));
                photos.Add(new BitmapImage(new Uri("Images/12.jpg", UriKind.Relative)));

                //Shuffle newly added photos as well
                photos.Shuffle();
            }
            
            return photos;
        }

Display Cards

This is the initial generation of the cards (gradients) and their corresponding actions once a user clicks on them.

private void DisplayCards()
        {
            foreach (var card in _collection.Cards)
            {
                var rect = new System.Windows.Shapes.Rectangle()
                {
                    Fill = new LinearGradientBrush(new GradientStopCollection()
                        {
                            new GradientStop()
                            {
                                Color = "#FF003366".ToColor(),
                                Offset = 0                                
                            },
                            new GradientStop()
                            {
                                Color = "#FF208FFF".ToColor(),
                                Offset = 1
                            },
                        }, 45
                    )
                    {
                        MappingMode = BrushMappingMode.RelativeToBoundingBox
                    },
                    Height = _cardHeight,
                    Margin = new Thickness(_margin),
                    Name = string.Format("rect_{0}", card.ID),
                    Stroke = new SolidColorBrush(Colors.White),
                    StrokeThickness = 2,
                    Width = _cardWidth,
                    Visibility = System.Windows.Visibility.Visible
                };

                rect.MouseLeftButtonUp += new MouseButtonEventHandler(ChooseCard);
                LayoutPanel.Children.Add(rect);

                var img = new Image()
                {
                    Height = _cardHeight,
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
                    Margin = new Thickness(_margin),
                    Name = string.Format("card_{0}", card.ID),
                    Source = card.Bitmap,
                    Width = _cardWidth,
                    VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
                    Visibility = System.Windows.Visibility.Collapsed
                };
                
                LayoutPanel.Children.Add(img);
            }
        }

Play a SoundEffect

This code snippet is all over the place on the internet and WP7 forums, but I thought I would include it here for completeness. In PhotoMemory, I play sound effects both in match and non-match scenarios and at the end when all cards are matched for a fun little “triumph”.

//Play failure sound
                            var snd = SoundEffect.FromStream(TitleContainer.OpenStream("Sounds/failed.wav"));
                            snd.Play();

Navigate to Another Page

Again, another simple snippet but this simply shows a way to navigate to another page within WP7 Silverlight.

this.NavigationService.Navigate(new Uri("/Game.xaml?mode=" + mode, UriKind.Relative));

Create and Use a DispatchTimer

Timers are very important in game/mobile development and using a DispatchTimer appears to be the simplest way to do it. Here I create a timer, set some variables such as the duration and what eventhandler to call, and then start the timer. After the timer has expired, the event is raised and I reset the flipped cards.

DispatcherTimer _cardTimer;

//Need to pause for 1 second before flipping back
                            _cardTimer = new DispatcherTimer();
                            _cardTimer.Interval = TimeSpan.FromSeconds(1);
                            _cardTimer.Tick += new EventHandler(FinishStudyingCards);
                            _cardTimer.Start();

void FinishStudyingCards(object sender, EventArgs e)
        {
            //Stop timer
            _cardTimer.Stop();

            //Flip cards back down after finished viewing
            FlipCard(_firstCard, FlipDirection.Down);
            FlipCard(_secondCard, FlipDirection.Down);

            //Allow user to try again
            _firstCard = null;
            _secondCard = null;
            _lock = false;
        }

PhotoMemory WP7 App

Submission

I would like to have a link to the application on Zune, however, because of complications with Microsoft my submission is still pending after more than a month. You can bet I will be writing a post on the submission process as well. Good luck, and have fun developing WP7 apps of your own!

My Windows Phone 7 Christmas Story

Windows Phone 7

Rushing To Check Under the Tree

Finally the day had come; a neat little package arrived at my wife’s office containing my new Samsung Focus WP7. My wife had been away in Chicago for a few snowy days and after missing three flights due to bad weather she finally arrived home. I said hello, hugged her tightly, and promptly asked for her office keys so I could speed over to her office at 8:30PM to leave her and get my phone. Thankfully, she was pretty accepting of this.

I pulled into the parking lot, slightly bumping the parking spot cement block and rushed inside. The weather was cold, Christmas lights decorated nearby buildings, and this was my Geek Christmas. The drive home – a tedious fifteen minutes – was clearly too long to wait, so I opened the little brown package on the spot, swapped out my current SIM card and started it up. The dark room glowed green with the crystal clear picture of the default lock screen. With a graceful flick up of a finger, the endless possibilities of mobile development officially began…

Playing With My New Toy

So a couple of things about the Windows Phone 7; first, setup was so painless I barely remember it. I entered my Windows Live ID and password and all of a sudden my phone just started coming alive. Images, calendars, and contacts that I didn’t even know I had wired up to Windows Live started appearing.

I installed Netflix, a wireless connection, my work Exchange account, and Yelp. At this point, I would be pretty happy with the phone just as is, but of course, I had to dive a bit deeper. I synced with Zune and pulled down Music, Pictures, and Podcasts. As a side note, I really do find the auto-copy to SkyDrive every time you take a picture from the phone a very smart feature.

Of course, not everything was rosy, I did take a silly picture that was immediately placed into my background for the picture hub which I could not change even when deleting the picture from the phone. It turns out that holding the touch while on the background of the picture hub is how to do this and it must make a separate copy not bound to the original picture. It seems trivial at the time, but I can see how discovery of when to use long touches may be a slight usability issue when developing applications.

All and all, I am very excited about the phone and have been showing it off to many of my dev-buddies. The real excitement comes in the next few posts where I will be discussing the creation and deployment of my first WP7 application.

Stay tuned.

WP7 U.S. Launch

Windows Phone 7

Monday, November 8th, 2010 came and went, the release of Windows Phone 7 has occurred. I’m sure many of you piled into a car at lunch time with your work buddies, drove down to the phone store, fought for a parking space, pushed through the throngs of people pounding at the doors trying to get a mere glimpse of the glory that is Windows Phone 7, let alone purchase one… Right, the events didn’t quite unfold that way for me either on the big release date of WP7.

The first part of that recount is true however, we did pile into a car at lunch time and drive down to the local phone store, but instead of thongs of people, we were greeted with two cardboard signs for iPhone 4 and the iPad. After milling about for almost five minutes we finally asked someone if they had a display for WP7, which we were directed to and left without much ado. I had the odd feeling we were the only four people in Naples which had any insight to this historic day when Microsoft finally does mobile right. The Samsung Focus didn’t disappoint with its’ sleek display, lightweight frame, and zippy feel, but the fanfare was lacking even from the experts at the store. There were no other phones on display to try out unfortunately.

I checked with a store rep to ask if they had any in stock and he announced they had sold out. Somewhat good news I thought to myself, but then learned that they had only received a single phone which was sold earlier that morning. I don’t know if that quite counts as “selling out” their initial launch, at least in my neck of the woods. Regardless of the lackluster personal experience during the WP7 launch, I do predict the following: Microsoft WP7 will share a similar release as Xbox originally did when Playstation 2 was deeply entrenched in the market. I believe WP7 will slowly gain adoption in the mainstream and eventually overtake Apple (and other phone OS’s) by enabling developers and phone manufacturers to create purposeful, consistent, quality products – both apps and physical devices.

Hopefully, I’ll have a phone in my hands to help spread the word soon!

P.S. – Blog postings on the two apps I have created coming as soon as I’ve tested on a real phone and deployed to the marketplace, stay tuned!