Any developers looking for a free phone? I got ‘em.

Yesterday, Microsoft announced the future of Windows Phone, and it looks amazing.  Multicore devices, multiple resolutions, native code, NFC (near-field communication), and a remarkable digital wallet solution that I’ve been begging for from ANY mobile platform for 10 years now.

In the meantime, yesterday was an announcement. Devices aren’t available yet, and the SDK won’t be available until later this summer.  So how do you get on this bandwagon today?

By building apps for Windows Phone 7.5.

Any apps you’ve built today will run on Windows Phone 8.  Heck, they’re even going to compile them in the cloud for you, so that they start and run even faster.  You’ll be able to take advantage of the new features of Windows Phone 8 in your v2.0 app.  You’ll have all of the fundamentals you need to build apps for Windows Phone AND Windows 8 at that point.

I know what you’re thinking:  “Jeff, why would I build an app today, when the Windows Phone 8 SDK will be available this summer?”  Because you’ve waited this long already.  The Windows Phone 7 SDK was available 2 years ago, and you haven’t gotten started.  What suddenly changed your mind?

Oh, and I’ll give you a free Nokia Lumia 710.  That’s unlikely to happen for Windows Phone 8.

Before you jump the gun, there are a couple of restrictions on who I can give these phones to.

  1. You must live in one of the following states: Arkansas, Iowa, Illinois, Indiana, Kansas, Kentucky, Louisiana, Michigan, Minnesota, Missouri, Montana, Nebraska, North Dakota, Ohio, Oklahoma, South Dakota, Tennessee, Texas, and Wisconsin
  2. You must be willing and able to build 2 real apps for Windows Phone before October 1, and get them published in the Windows Phone Marketplace.   (If you miss the deadline, you will have to send it back to me.)
  3. You can’t have already received a free phone from Microsoft.  (Yes, I have the list.)

If my list of requirements doesn’t seem overwhelming, and you’re interested in getting a free device, email me at jeblank [at] microsoft [dotcom] and I’ll be happy to discuss it.

Finally, I’d had many people ask me what “qualifies” as an app.  My quality bar is simple:

If you truly believe that people you’ve never met would use it, it qualifies.

So what are you waiting for?  Send me an email, and we’ll get this started!

Windows Phone Business Cards

At Codemash, I finally gave away my last business card, and so I decided to make some new ones (if you’ve met me, you know my aversion to corporate business cards.)

Since I’ve been focused on Windows Phone for almost two years now, and plan on continuing that for the foreseeable future, I wanted to make a business card that reflected my current technology passion.  With that, I present to you my new Windows Phone business cards:

BusinessCardBackBusinessCardFront

And the final product, in terrible lighting…(the cards are actually a dark black).

WP_000626

I am one to share my work, however, so if you would like to download this template to use for your own cards, I’ve provided them in two formats:  Expression Design and Adobe Illustrator.  These were originally created in Expression Design, but the Illustrator files I’ve provided do work, but they’re just a little less accommodating (fonts are not editable, for example).

 

bg-design          

Download a 60-day trial of Expression Design.

Download a 30-day trial of Adobe Illustrator.

Once you’ve downloaded the templates and the software (if you need it), feel free to edit them to your heart’s content.  Some of you may not have a YouTube channel.  Others may not use LinkedIn.  Make it your own.  Change the colors.  Definitely change the Tag.

Finally, you’re going to need a place to print them for a reasonable price.  I’ve shopped around, and I found a print shop local to me that was willing to print 1000 of these cards on a heavy 16pt card stock, with a smooth UV coating, and rounded corners for $110.  They’re familiar with the cards, and they will do a phenomenal job for you as well.  You can find YesPress online at http://yespress.com.  Their price was nearly 72% less than every other print shop I talked to, including the online card makers like Moo ($389.70), but their quality was exactly the same as Moo’s rounded corner business cards.

Yespress Graphics

If you do make some cards for yourself, please post them in the comments here, so I can see what you’ve made!  Until next time…

The Curious “Today” Button

[UPDATED: This article was meant to share a quick hack that I created.  I am not endorsing this as a best practice that you should incorporate into your applications.  I’m offering it as an option to those of you building apps that only use the English language.]

Yesterday, I was working on a Windows Phone application that is very date-centric.  I show the user a list of events for a specific day, and the page always loads data for “today” by default.  They can always change it (I’m using a DatePicker for that), but I wanted to give them an easy way to return to whatever “today” may be.

I’d seen this before, in the Calendar app that comes on Windows Phone by default.  It looks like this:

As you can see, there is a “today” button in the ApplicationBar.  (In the image, today must be July 7th.)  Anyways, I did some investigation, and came to a conclusion that either that image is being generated on the fly, or they’ve included 366 images in their project, to accommodate every possible month/date combination.

Since I’ve never done any dynamic image generation before, it seemed like more work that I was prepared to accomplish in the short timeline I had to finish this application.  So, I went ahead and created the 366 images that are necessary to make this functionality happen.

To change the IconUri property of an ApplicationBarIconButton, you just need this one line of code:

((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IconUri = new Uri("/icons/dates/" + DateTime.Now.Month + "-" + DateTime.Now.Day + ".png", UriKind.Relative);

Finally, you’re probably interested in downloading this set of images, so you don’t have to spend the countless hours (it was less than 2) I spent creating them.  So, here they are:

1-11-21-31-41-51-61-71-81-91-101-111-121-131-141-151-161-171-181-191-201-211-221-231-241-251-261-271-281-291-301-312-12-22-32-42-52-62-72-82-92-102-112-122-132-142-152-162-172-182-192-202-212-222-232-242-252-262-272-282-293-13-23-33-43-53-63-73-83-93-103-113-123-133-143-153-163-173-183-193-203-213-223-233-243-253-263-273-283-293-303-314-14-24-34-44-54-64-74-84-94-104-114-124-134-144-154-164-174-184-194-204-214-224-234-244-254-264-274-284-294-305-15-25-35-45-55-65-75-85-95-105-115-125-135-145-155-165-175-185-195-205-215-225-235-245-255-265-275-285-295-305-316-16-26-36-46-56-66-76-86-96-106-116-126-136-146-156-166-176-186-196-206-216-226-236-246-256-266-276-286-296-307-17-27-37-47-57-67-77-87-97-107-117-127-137-147-157-167-177-187-197-207-217-227-237-247-257-267-277-287-297-307-318-18-28-38-48-58-68-78-88-98-108-118-128-138-148-158-168-178-188-198-208-218-228-238-248-258-268-278-288-298-308-319-19-29-39-49-59-69-79-89-99-109-119-129-139-149-159-169-179-189-199-209-219-229-239-249-259-269-279-289-299-3010-110-210-310-410-510-610-710-810-910-1010-1110-1210-1310-1410-1510-1610-1710-1810-1910-2010-2110-2210-2310-2410-2510-2610-2710-2810-2910-3010-3111-111-211-311-411-511-611-711-811-911-1011-1111-1211-1311-1411-1511-1611-1711-1811-1911-2011-2111-2211-2311-2411-2511-2611-2711-2811-2911-3012-112-212-312-412-512-612-712-812-912-1012-1112-1212-1312-1412-1512-1612-1712-1812-1912-2012-2112-2212-2312-2412-2512-2612-2712-2812-2912-3012-31

Or, if that’s not convenient, you can download the entire collection of Windows Phone Date Icons in a ZIP file here.

These images are completely free to use, I only ask that you comment here on how you used them.  Fair?

What’s On Your Phone?

I’ve seen many people posting app recommendations for their phones, and I thought I should participate.  (Specifically Brian Jackett and Brian Graham.)  I tend to prune the apps on my phone quite often, so while this is an alphabetical list of the apps and games on my phone, consider them a recommendation as well.  They wouldn’t be on this list if I didn’t use them regularly.

Apps

AccuWeather.com

Accuweather.com
Of all of the weather applications available, this one is the best.  It makes it easy to manage multiple cities, pin each of them to the start screen, and gives you real-time alerts when the weather turns bad.
Across the Room Free
Across The Room
Written by my friend and colleague Dave Bost, this simple application allows you to use your phone like a message ticker, scrolling a large-text message across your screen to a person you might be able to see, but can’t talk to.  This has been very handy as a proctor for speakers at a conference, and for getting a message into a conference room through a window.
Amazon Mobile
Amazon Mobile
All the features of Amazon.com in your pocket.  Wishlists, a very Metro interface, and a pinnable barcode reader are only the beginning.  I have used this many times to order a product from Amazon while standing in a competing brick & mortar store.
AppTracker
AppTracker
For those of you building applications for Windows Phone, this is a must-have app.  It lets you track your apps, monitor your feedback from all of the geographies your app is available for, and even offers Bing Translate when it’s in a different language.
DoodlePad
DoodlePad
A great little application to keep my kids entertained.  A simple drawing tool with a huge number of options.
ESPN ScoreCenter
ESPN ScoreCenter
More than just a portal to ESPN.com, this tool actually uses your ESPN credentials to remember who your favorites teams are, and shows you a customized dashboard with your teams, and their past and future games.
Facebook
Facebook
Windows Phone does a great job of integrating with Facebook, but for those niche needs (like managing photo albums), the Facebook app is perfect.
Find ESPN® Radio
Find ESPN Radio
I do a good bit of driving, and sometimes there’s a game on the radio that I’d like to listen to.  Instead of fighting with the Scan function on the radio, I just use this app, with its geolocation, to determine what the ESPN Radio station is currently.  Great app.
FML
FML
If you’re ever feeling down about yourself whatsoever, crack open this application, and you’ll feel better in a hurry.  This app exposes the data from fmylife.com, where people post short messages about the terrible things that happened in their lives.  Sad to say, it’s hilarious most of the time.
Geocaching
Geocaching
An amazing tool in the global scavenger hunt that is Geocaching.  If you’re not familiar with the concept, check out geocaching.com.  It’s great fair-weather fun for the whole family, and this app makes it much easier to do.
IMDb Movies, TV & Celebrities
Internet Movie Database (IMDB)
A great way to figure out what other movie that guy with the mustache has been in.  A go-to resource for movie and television trivia.
Key Ring Reward Cards
Key Ring
Tired of all of those rewards cards in your wallet?  This app stores all of them electonically, but still makes it possible for you to scan them at the checkout.  Syncs online, so when you change your phone, you don’t have to enter all of the info again.
Phonealytics
Phonealytics
A great Google Analytics app.  Allows you to favorite those websites you view the most often, and has a great number of reports and data available.  (The free version is very sufficient, so check it out before you buy the full one.)
Pizza Hut
Pizza Hut
The only major pizza chain on Windows Phone, you can take care of your entire order right from your phone.  Place your order, pay for it with a credit card, and track its progress.  If I could convince the driver to bring it directly to my couch, I’d never have to get up.
RitmoMix Ritku
RitmoMix Ritku
I have no idea what the name of this app means, but it allows me to wirelessly control my Roku boxes in my house.  It communicates over my wireless network, and is actually an improvement over the actual Roku remote control.
Tripit
TripIt
As a person that travels extensively, TripIt has been an invaluable tool for managing all of my reservations for hotels, rental cars, and flights.  Having an app on my phone makes accessing all of this information on the go much, much faster.
Wikipedia
Wikipedia
It’s an app that exposes all of the data in Wikipedia.  What more do you need?
WordPress
WordPress
This handy little application allows you to manage your WordPress blog.  Moderate comments, add new posts, and even edit existing posts (if they’re not too long.)

Games

There are many, many more games on my phone than are in this list, but I’ve only included those that I’ve played more than once.  Most of the games on my phone were downloaded for (or by) my kids.

Alphabuzzle
AlphaBuzzle
The alphabet has been divided into a set of sliding tiles, and you need to move them appropriately to reconstruct the alphabet in order.  It’s funner than I just described it, I promise.

Angry Birds

Angry Birds
Use a catapault to launch birds at the pigs that stole their eggs.  High replayability factor, great time waster.
Clowning Around
Clowning Around
Themed with life’s scariest creature, the clown, you use ropes, chains, ramps, levers, and some physics to get the clowns in the right buckets.  My 3 year old son found this in the marketplace, and it’s definitely worth the 99 cents.
Doodle God™
Doodle God
You start with 4 elements: wind, water, fire, and earth.  By combining them, you’ll eventually create over 195 things.  It’s not nearly as easy as you think, and plenty of fun.
FastBall 2
FastBall 2
Guide a red ball through progressively more difficult levels.  Tap the screen to jump over the hazards.  WARNING:  the music in this game is an earworm.
Harbor Master
Harbor Master
You steer an ever-increasing number of boats into their ports, unload their cargo, and send them back out to sea.  Meanwhile, you’ve got to avoid having any of the boats crash into each other.
The Moron Test
The Moron Test
Looking for a reason to feel stupid?  This little puzzle game will test you.  Outstanding and addictive.
Physi Bricks
Physi Bricks
A cool physics based game.  Knock the green bricks off the screen, leave the red ones.  Harder, and makes you want to keep coming back.
PvZ
Plants vs. Zombies (PvZ)
The most fun tower defense game out there.  I’ve paid for this game on five different platforms now, and it’s still addictive.
Sallys Salon LE
Sally’s Salon LE
A resource and time management strategy game, you own a hair salon, and have set some lofty career goals.  Despite the fact that this game is set in a salon, it is surprisingly fun, even for a guy like me.
Spell It
Spell It
A Scrabble game that isn’t Words With Friends.  The interface is great, and playing against a computer or human is available, even remotely, like WWF.  However, the moment WWF is available for Windows Phone, I’ll likely drop this app.
Spelling Millionaire Premium
Spelling Millionaire
Simple.  Confirm that each word in a set of 15 is spelled appropriately.  Sounds easy, right?  I’m a great speller, and I win maybe 60% of the time.
Super Jumping Mike
Super Jumping Mike
Very similar to FastBall 2, you are Mike, and you’re on a forced move through levels that require you to jump at appropriate times to avoid the obstacles and grab the three coins.  Very addictive.
Unite
Unite
A great fresh take on the old (and tired) labyrinth category, you need to get the metallic marbled together, where they become slightly larger.  Combine all of the marbles on the level to finish it.
Wordament
Wordament
A kind of crowd-sourced Boggle game.  You play against the world in fast-paced games.  Very fun if you like word games.
Xbox Companion
Xbox Companion
An app that lets me control my Xbox 360?  Yes please!

Want to change your Windows Phone emulator?

Today, I discovered that Pedro Lamas had released a skin for the Windows Phone emulator that allowed it to look like the Nokia Lumia 800.  (You can see it here.)

This inspired me to create another new skin for my current phone, the HTC Arrive.  (Click here to download the HTC Arrive Windows Phone Emulator skin.)  To use either of them, you simply need to copy the contents of the zip file to a specific folder on your computer (make sure to save a copy of the original files):

C:Program Files (x86)Microsoft XDE1.0

Once you’ve done that, your emulator can look like one of the images below!

Nokia-Lumia-800-skin-for-Windows-Phone-Emulator[1]                                  image

31 Days of Mango | Day #31: Promoting Your App

Day31-PromotingYourApplicationDay30-LocalDatabaseDay29-GlobalizationDay28-MediaLibraryDay27-MicrophoneAPI

This article is Day #31 in a series called 31 Days of Mango.

Getting users to find your application might seem like something that’s out of your hands, but you’re wrong. There are plenty of things you can do to drive awareness of your application. This section focuses on a few best practices you should utilize for every application that you create.

The First Week Is Vital

Unless your app becomes a runaway sensation, it’s highly likely that your app’s first week in the marketplace will also see your highest number of daily downloads. Getting exposure in the New category is a one time opportunity, and you need to make sure that you leverage this in a way that will make your app shine for much longer than a few days. Ultimately, your goal is to catapault from the New category to the Top Apps category. The 4-5 days that you will wait for your application to be approved should be spent executing a specific strategy for making the public aware of your application.

Linking To Your Application

When you first submit your application to the Marketplace, even before the app is approved, you are assigned a deep link that you can use to direct people to your app using a standard web URL. Here’s an example of the deep link to one of my applications, MathMaster:

http://windowsphone.com/s?appid=f08521cd-1cff-df11-9264-00237de2db9e

This link takes you to a webpage that will attempt to launch the Zune software on the user’s machine, and then direct them to the page for your app in the Marketplace. This link will not work until your application is approved. We recommend using this link everywhere you can, especially on the custom website you created for your apps. You were planning on doing that, right?

Creating a Web Portal for Your Apps

An important thing that you should have learned from the Marketplace walkthrough in Day #27 of the original 31 Days of Windows Phone was that your ability to discuss your apps is pretty limited. A few screenshots, and approximately 2,000 characters is all you have. By creating a website for your applications, you create several new opportunities for yourself.

1. You can create real connections with your users. The Windows Phone marketplace doesn’t give you any indication who your users are. A website allows you to interact with your fans.

2. You can provide a rich amount of information about your app, including videos and other promotional content that might make your app more appealing.

3. You can cross-sell your applications. The Marketplace doesn’t always do a great job at promoting your other applications to potential customers, so leverage your website to make that happen.

4. Your app is now discoverable by people that aren’t actively looking for it in the Marketplace.

5. This website doesn’t have to be a website at all. There’s nothing wrong with creating a page on Facebook or another social network that you can customize. The ultimate goal of this process is to provide a destination for your fans, so that they can spread the word about your awesome app.

If you would like an awesome template for building a custom web page for your application, check out the Windows Phone 7 App Site template on CodePlex.  It’s a customizable page that looks great, uses your application screen shots, allows your users to provide feedback, and gives them plenty of ways to learn more about your application.  Here’s a screenshot of the template:

image

Create A Walkthrough Video of Your App

One of the important features your website should include is a video walkthrough of your app. Screenshots in the marketplace are good, but allowing a user to see the actual experience in a controlled way will always provide them with more information. Our recommendation is to use a video screen capture tool like TechSmith’s Camtasia. Camtasia makes it easy to not only capture the video feed from the emulator, but to edit the results, add background music, and introduction information before and after the video. There are probably plenty of tools that will do this for you, but in our experience, Camtasia is the perfect tool for the job. You can see an example of my MathMaster video on YouTube here:

http://youtu.be/uMlyUn3sgJU

Have fun with it. Your video can add a level of excitement to your app that screenshots can never provide. Now that we’ve focused on websites and videos, let’s discuss the things you can do inside your application to help promote it.

Generating Reviews of Your Application

Reviews can be the deciding factor as to whether or not your application gets the downloads you’re looking for. Unfortunately, there’s not a built-in mechanism for reminding users to review your app. You need to do this yourself. We recommend making it a fun addition to your application rather than an annoyance to your user.

One idea we recommend is to make it an achievement within your app. Litter fun little surprises throughout your application, and you’ll hook an otherwise passive user. Give points for reading the credits of the app. Give more for using the app 10 times. By adding achievements to any application, you’ll find that your users will find themselves coming back again and again. You might also unlock a specific piece of functionality that would otherwise be unavailable when they review your app.

A second idea is to count the number of times your user has launched your application, and prompt them at the 2nd, 5th, and 10th times to review your application. Ask gently. You don’t want to annoy the user, but you do want their review. You can even use the MarketplaceReviewTask to take them directly to the review page for your application.

Great reviews generate more traffic. Oftentimes, a star review can be just as valuable as a written one. The average star rating (1-5) is displayed everywhere your application is, so a high rating often generates more traffic. Encouraging your users to leave a review will have a positive effect on your application’s download rates.

Cross-Selling Your Applications from Each Other

Within your app, you should provide a place where the user can find information about your company, support contacts, and other data like version number. In this place, or certainly in a more prominent location, you have an opportunity to promote the other applications you’ve created. Use your icons. Use the deep links or the MarketplaceDetailTask launcher. Provide a simple way for your user to find and download your other application offerings.

If you really want to get fancy, create an XML file on your webserver that contains all of the information about your apps, and consume this in your apps to create the list of your applications. This way, when you add a new app to your catalog, you won’t have to update all of your apps just to do this cross-promotion.

Summary

There are plenty of things you need to do in order to get your application ready, after you’ve finished your application. Make sure that you’ve considered your promotion strategy before you push the final Submit button on your app. Building a community around your application will only help to make your audience grow, because enthusiastic users are also powerful evangelists of your efforts.

If you’ve taken the time to create an amazing new application for Windows Phone, you need to be certain that it’s going to have the potential impact you’re hoping for. Focusing on monetizing, promotion, and reviews is almost as important your app.

This is the final post in this series.  I hope you’ve enjoyed it as much as my guest authors and I did writing it.  Thank you for reading all of the posts, and if you haven’t already…

toolsbutton

31 Days of Mango | Day #30: Local Database

Day30-LocalDatabaseDay29-GlobalizationDay28-MediaLibraryDay27-MicrophoneAPIDay26-BackgroundFileTransfers

This article is Day #30 in a series called 31 Days of Mango, and was written by guest author Chris Woodruff.  Chris can be reached on Twitter at @cwoodruff.

What is a Local Database?

In the original version of Windows Phone 7, we could save data but it took either custom code or using third party databases like SterlingDB to have the relational data repository that some applications need. This limited the types of applications some developers could produce for users.

In Windows Phone 7 Mango, developers still have isolated storage to keep data and information stored for their applications but now have SQL CE as a relational storage feature to created even better applications for Windows Phone.

Like other database solutions for the original Windows Phone 7, the native SQL CE database built into Mango has it data stored in the device’s Isolated Storage. You can learn more about Isolated Storage here. Microsoft also did not create new ways to work with the data on the phone and instead implemented LINQ to SQL for all database operations. LINQ to SQL is used to do all functions for the application when dealing with data including creating the data, populating data into the database, getting data and finally saving and deleting data.

A good tutorial for LINQ to SQL is here on MSDN.

Setting up a Local Database for your Mango Application

Like all starting points for Windows Phone 7, we will start with creating the Windows Phone Databound Application project within Visual Studio 2010.

clip_image002

We could have started with just the Windows Phone Application project but I like the additional features that the Databound project gives you to allow your application to have better design patterns like Model-View-ViewModel (MVVM).

Next we will update the MainPage of the project to allow for the data to be added to the database. Our data example will be collecting ideas that we all have and need to remember. We will not go into much detail about the design of the MainPage but here is the XAML to get the look and feel for our Idea collector.

<phone:PhoneApplicationPage
   x:Class="_31DaysMangoStorage.MainPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
   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&quot;
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
   mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
   d:DataContext="{d:DesignData SampleData/MainViewModelSampleData.xaml}"
   FontFamily="{StaticResource PhoneFontFamilyNormal}"
   FontSize="{StaticResource PhoneFontSizeNormal}"
   Foreground="{StaticResource PhoneForegroundBrush}"
   SupportedOrientations="Portrait" Orientation="Portrait"
   shell:SystemTray.IsVisible="True">

    <!–LayoutRoot is the root grid where all page content is placed.–>
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!–TitlePanel contains the name of the application and page title.–>
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="31 Days of Mango" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Idea Tracker" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!–ContentPanel – place additional content here.–>
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <!– Bind the list box to the observable collection. –>
            <ListBox x:Name="toDoItemsListBox" ItemsSource="{Binding IdeaItems}"
                    Grid.Row="0" Margin="12, 0, 12, 0" Width="440">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid HorizontalAlignment="Stretch" Width="440">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="50" />
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="100" />
                            </Grid.ColumnDefinitions>
                            <CheckBox
                               IsChecked="{Binding IsComplete, Mode=TwoWay}"
                               Grid.Column="0"
                               VerticalAlignment="Center"/>
                            <TextBlock
                               Text="{Binding ItemName}"
                               FontSize="{StaticResource PhoneFontSizeLarge}"
                               Grid.Column="1"
                               VerticalAlignment="Center"/>
                            <Button
                               Grid.Column="2"
                               x:Name="deleteTaskButton"
                               BorderThickness="0"                                
                               Margin="0"
                               Click="deleteTaskButton_Click">
                                <Image Source="appbar.delete.rest.png"/>
                            </Button>
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

            <Grid Grid.Row="1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <TextBox
                   x:Name="newIdeaTextBox"                    
                   Grid.Column="0"
                   Text="add new idea"
                   FontFamily="{StaticResource PhoneFontFamilyLight}"                    
                   GotFocus="newIdeaTextBox_GotFocus"/>
                <Button
                   Content="add"
                   Grid.Column="1"
                   x:Name="newIdeaAddButton"
                   Click="newIdeaAddButton_Click"/>
            </Grid>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>
 

Also to allow for your application to compile and run without doing anything the code below will be added to the MainPage.xaml.cs file inside the MainPage class implementation and after the constructor.

private void newIdeaTextBox_GotFocus(object sender, RoutedEventArgs e)
{
    // Clear the text box when it gets focus.
    newIdeaTextBox.Text = String.Empty;

}

private void newIdeaAddButton_Click(object sender, RoutedEventArgs e)
{

}

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    // Call the base method.
    base.OnNavigatedFrom(e);

}
 

Working with the Data Context

The Data Context is the point that will allow us to work with the database and also the proxy classes that represent our database tables. The data context is also a class and works against a number of “plain old CLR object” (POCO) classes that we will create for this project. The table objects that represent our database tables will contain a collection of entities for each table record stored in the database. Other details about our database are also given to us through the data context such as table keys and association mappings between tables.

Just a reminder that this local database has no connection with SQL Server 2008 R2 that is running locally on your PC or a server in your company or hosting provider and is only to hold data on your device.

There is not much to the DataContext class besides the connection string we are familiar in development and properties to each table that will exist in our database. Think of the DataContext as the “Hub” for your application’s data. The code for the sample application’s DataContext is below.

public class IdeaDataContext : DataContext
{
    // Specify the connection string as a static, used in main page and app.xaml.
    public static string DBConnectionString = "Data Source=isostore:/Ideas.sdf";

    // Pass the connection string to the base class.
    public IdeaDataContext(string connectionString)
        : base(connectionString)
    { }

    // Specify a single table for the to-do items.
    public Table<IdeaItem> IdeaItems;
}
 

Note that IdeaItem type will be detailed in the next section covering creating the Database.

Creating the Database

Unlike applications that are run from your PC or on IIS 7, databases in Windows Phone 7 Mango must be created and initialized on the first instance your app runs on the phone. We will first look at creating the classes that will represent our database tables and then look at database initialization.

For each table that we need to be built and exposed through the database on our phone for the application a new POCO needs to be created. Since these classes represent the entities that will be stored in the database let’s call them Entity classes. To begin the Entity class must adhere to the following two interfaces:

· INotifyPropertyChanged — The INotifyPropertyChanged interface is used to notify clients, typically binding clients that a property value has changed.

· INotifyPropertyChanging — The INotifyPropertyChanging interface is used to notify clients, typically binding clients that a property value is changing.

These two interfaces will allow each entity to notify the DataContext that is in the process of changing or has changed. This will then be reflected to the XAML views of our application through the binding we have set up.

The Enity class must be annotated as a Table to allow the DataContext to know how to work with it. An Entity classes must also have private and public properties for each Entity property as well as having the private property annotated to give valuable metadata about the Entity property (aka the database column). Remember to have primary key properties for each of your Entity classes.

Below is the IdeaItem Entity class that will be located in the IdeaItems table referenced in the DataContext we created before.

[Table]
public class IdeaItem : INotifyPropertyChanged, INotifyPropertyChanging
{
    private int _ideaItemId;
    [Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
    public int IdeaItemId
    {
        get
        {
            return _ideaItemId;
        }
        set
        {
            if (_ideaItemId != value)
            {
                NotifyPropertyChanging("IdeaItemId");
                _ideaItemId = value;
                NotifyPropertyChanged("IdeaItemId");
            }
        }
    }

    private string _itemName;
    [Column]
    public string ItemName
    {
        get
        {
            return _itemName;
        }
        set
        {
            if (_itemName != value)
            {
                NotifyPropertyChanging("ItemName");
                _itemName = value;
                NotifyPropertyChanged("ItemName");
            }
        }
    }

    private bool _isComplete;
    [Column]
    public bool IsComplete
    {
        get
        {
            return _isComplete;
        }
        set
        {
            if (_isComplete != value)
            {
                NotifyPropertyChanging("IsComplete");
                _isComplete = value;
                NotifyPropertyChanged("IsComplete");
            }
        }
    }

    [Column(IsVersion = true)]
    private Binary _version;
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangingEventHandler PropertyChanging;
    private void NotifyPropertyChanging(string propertyName)
    {
        if (PropertyChanging != null)
        {
            PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
        }
    }
}
 

Finally we must create the database is it does not exist. This will be done in the Application class’s constructor. You will find this in the App.xaml.cs file. The code that will be added to the end of the constructor method is as followed.

using (IdeaDataContext db = new IdeaDataContext(IdeaDataContext.DBConnectionString))
{
    if (db.DatabaseExists() == false)
    {
        db.CreateDatabase();
    }
}
 

We now have a database that has been created and initialized in application’s Isolated Storage. One more thing to remember is that local databases in Windows Phone 7 mango cannot be shared directly between apps on the phone due to the sandboxing security set up in the Windows Phone 7 Mango operating system.

LINQ to SQL Support for Windows Phone Mango

Windows Phone 7.1 SDK allows for some but not all features of LINQ to SQL inside the Windows Phone. The following are just a few things to remember when working with data and LINQ to SQL in Windows Phone 7 Mango.

· ExecuteCommand is not supported

· ADO.NET Objects (such as DataReader) are not supported

· Only Microsoft SQL Server Compact Edition (SQL CE) data types are supported

To get more limitations and features of using LINQ to SQL on Mango please read the MSDN page here.

Retrieving Data from a Local Database

To retrieve data or any data related work with the local database, we must first create the DataContext and connect to the database. This will happen in MainPage.xaml.cs through a private variable for the DataContext, an observable collection property for the ideas in the database table and in the MainPage constructor as followed.

private IdeaDataContext ideaDB;

private ObservableCollection<IdeaItem> _ideaItems;
public ObservableCollection<IdeaItem> IdeaItems
{
    get
    {
        return _ideaItems;
    }
    set
    {
        if (_ideaItems != value)
        {
            _ideaItems = value;
            NotifyPropertyChanged("IdeaItems");
        }
    }
}

public MainPage()
{
    InitializeComponent();

    ideaDB = new IdeaDataContext(IdeaDataContext.DBConnectionString);
    this.DataContext = this;
}
 

To get our ideas located in the local database we will use LINQ to SQL to query and get the collection back from the database via the DataContext.

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    var ideaItemsInDB = from IdeaItem todo in ideaDB.IdeaItems
                        select todo;

    IdeaItems = new ObservableCollection<IdeaItem>(ideaItemsInDB);
    base.OnNavigatedTo(e);
}
 

The ideas are now bound and reflected in the MainPage.xaml.

clip_image003

Storing Data to a Local Database

Finally we will build the saving of our idea data to the local database. We will not send the ideas to the database until we need to increase performance. We will keep all of the ideas in the local observable collection we created as a MainPage property (IdeaItems). The addition of new ideas to the local database will take place on the button click when the new idea is added to the IdeaItems collection.

private void newIdeaAddButton_Click(object sender, RoutedEventArgs e)
{
    IdeaItem newIdea = new IdeaItem { ItemName = newIdeaTextBox.Text };

    IdeaItems.Add(newIdea);
    ideaDB.IdeaItems.InsertOnSubmit(newIdea);
}
 

As mentioned before the ideas collected from the user will not be stored in the database until the application has transitioned from the MainPage either when the user exits the application or the application moves to a new page in the application. The code for the OnNavigateFrom event for the MainPage is below.

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);
    ideaDB.SubmitChanges();
}
 

Summary

So that’s pretty much it!  You now have a simple way to create, store, and retrieve relational data in your Windows Phone applications.  How are you going to use this?

To download a full Windows Phone project that includes all of the code and concepts from this article, click the Download Code button below.

download

Tomorrow, in the final article of this series, we will cover the best practices for promoting your Windows Phone applications.  See you then!

toolsbutton