Over the past several weeks I’ve been posting about how to work with local data in Windows Store apps of you’re an Android developer today. I want to wrap this series up by providing some useful links.

All Posts in this Series

  1. Working with Key-Value Pairs
  2. Working with Files
  3. Working with a SQL Database

If you would prefer a pdf of all three posts you can get it at: http://thinkfirstcodelater.com/docs/Android2Windows8LocalData.pdf

Additional Resources

Learn how to write code in Windows Store apps for Windows 8 that works with structured data in SQLite—a popular database that’s familiar to Android app developers.

Your app may need to work with data that’s more complex than simple key-value pairs—for example, a complex sales order or a survey with comments. For these kinds of data, you may want to use a database. One popular choice is SQLite—a self-contained, zero-configuration, relational, transactional database engine—which Android and Windows Store apps both support.

Here’s how to:

  • Install SQLite.
  • Reference it from a Windows Store app.
  • Get a helper library to make your coding easier.
  • Write code to create a database table.
  • Add, get, change, and remove the table’s records.

Installing SQLite

The first thing you’ll need to do is install the SQLite for Windows Store apps. This can be done by downloading the SQLite for Windows Runtime package

  1. In Visual Studio, click the Tools menu, then click Extensions and Updates

  2. In the tree on the left of the Extensions and Updates window, click Online, then click Visual Studio Gallery.
  3. Next, type sqlite in the search box in the upper right hand corner and press Enter.
  4. The SQLite for Windows Runtime package should appear. Click Download.

  5. You will then be prompted to click Install. Do so.

  6. Once the package is installed you will need to restart Visual Studio
Android tip
The SQLite for Windows Runtime package in Visual Studio is similar to the android.database.sqlite package.

Adding a Reference to SQLite

Now that SQLite is installed you need to add a reference to it from you project.

  1. Right click the References folder in your Windows Store project and click Add Reference…

  2. In the tree on the left hand side of the Reference Manager windows, expand the Windows and the Extensions nodes.
  3. Then select both the SQLite for Windows Runtime and the Microsoft Visual C++ Runtime Package and click OK.

  4. You should now see the extensions appear under the References folder for you project.

Visual Studio tip
After you add these references, your app’s project may not build or run. To fix this, on the Build menu, click Configuration Manager. In the Active solution platform box, click your specific target platform, such as ARM, x64, or x86. Then click Close.

Getting Helper Classes

The last thing you’ll want to do is obtain some helper classes that make working with SQLite a bit easier. There are a number available for Windows Store applications. The ones I prefer to use come from the sqlite-net library.

The sqlite-net library can be obtained from NuGet via the following steps

  1. Right click on the References folder in you Windows Store project and click Manage NuGet Packages…


  2. Expand the Online node in the left hand side of the Window.
  3. Enter sqlite in the search box in the upper right hand side of Window and press Enter.
  4. Select sqlite-net and click Install.


  5. Two source files will be added to your project: SQLite.cs and SQLiteAsync.cs.


  6. Build your project by pressing F6 to ensure it is set up correctly.
Visual Studio tip
NuGet is a Visual Studio extension that makes it easier to install and update third-party libraries and tools in Visual Studio. To learn more about NuGet, see the NuGet Gallery.After you get familiar with NuGet, you may find it easier to use the command-line version of NuGet. To get to it in Visual Studio, on the Tools menu, click Library Package Manager > Package Manager Console.

Using SQLite

In the last part of this section we’ll look at how to perform some basic tasks with SQLite in your Windows Store application.

Creating a Table

The first step you’ll need to take is to create a table that your application will use. For the sake of example, let’s say your application is storing blog posts in a SQLite table. Using the sqlite-net package you obtained in the last section, you can define the table by simply writing a class.

public class Post
{
 [PrimaryKey]
 public int Id { get; set; }
 public string Title { get; set; }
 public string Text { get; set; }
}

The PrimaryKey attributes come from the sqlite-net package. There are a number of attributes that the package provides that allow you to define the table’s schema.

Once the table is defined it needs to be created, which can be done like this:

private async void CreateTable()
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
    await conn.CreateTableAsync<Post>();
}

The “blog” parameter in the constructor for the SQLiteAsyncConnection class simply specifies the path to the SQLite database.

The Post type specified in the call to the CreateTableAsync method specifies the type of table that should be created. This maps back to the Post class created earlier.

Android tip
In Android apps, you create a table that extends the SQLiteOpenHelper class with code like this.

public void onCreate(SQLiteDatabase db) {    
 db.execSQL("CREATE TABLE Post ( Id INTEGER PRIMARY KEY, Title TEXT, Text TEXT )");
}

Inserting a Record

Now that the table is created, records can be added to it with the following code:

public async void InsertPost(Post post)
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
    await conn.InsertAsync(post);
}
Android tip
In Android apps, you can add a record with code like this.

public void insertPost(SQLiteDatabase db, String title, String text ) {    
 ContentValues values = new ContentValues();
 values.put("Title", title);
 values.put("Text", text);
 long newRowId;
 newRowId = db.insert("Post", null, values);
}

Retrieving Records

Retrieve a single records from the table with the following:

public async Task<Post> GetPost(int id)
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");

    var query = conn.Table<Post>().Where(x => x.Id == id);
    var result = await query.ToListAsync();

    return result.FirstOrDefault();
}
Android tip
In Android apps, you could return a Cursor object containing a single record with code like this.

public Cursor getPost(SQLiteDatabase db, Integer id){    
 String[] projection = {"Id", "Title", "Text" };
 String selection = "Id LIKE ?";
 String[] selelectionArgs = { String.valueOf(id) };
 Cursor c = db.query( "Post", projection, selection, selectionArgs,  null, null, null);
 return c;
}

Retrieve all record from the table with the following:

public async Task<List<Post>> GetPosts()
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");

    var query = conn.Table<Post>();
    var result = await query.ToListAsync();

    return result;
}
Android tip
In Android apps, you could return a Cursor object containing all records with code like this.

public Cursor getPosts(SQLiteDatabase db){    
 String[] projection = { "Id", "Title", "Text" }; 
 Cursor c = db.query( "Post", projection, null, null, null, null, null);
 return c;
}

Updating a Record

Updating a record requires the following code:

public async void UpdatePost(Post post)
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
    await conn.UpdateAsync(post);
}
Android tip
In Android apps, you can update a record with code like this.

public void updatePost(SQLiteDatabase db, Integer id, String title, String text ) {    
 ContentValues values = new ContentValues();
 values.put("Title", title);
 values.put("Text", text);
 String selection = "Id LIKE ?";
 String[] selelectionArgs = { String.valueOf(id) };
 int count = db.update("Post, values, selection, selectionArgs);
}

Deleting a Record

A record can be delete with the following:

public async void DeletePost(Post post)
{
    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("blog");
    await conn.DeleteAsync(post);
}

Android tip
In Android apps, you can delete a record with code like this.

public void deletePost(SQLiteDatabase db, Integer id ) {    
 String selection = "Id LIKE ?";
 String[] selelectionArgs = { String.valueOf(id) };
 db.delete("Post", selection, selectionArgs);
}

Next Steps

To learn more about how to work with SQLite, see these resources.

Learn how to write code in Windows Store apps for Windows 8 to save files, like photos or documents. You can store these files in app-specific file locations or save them to external storage media, like a USB drive.

A user may want to save a document that they’re working on and immediately return to the saved document it when they return to some document editor app. Or a user may want to save the current photo from some photo editing app to a USB drive and then connect that USB drive to a TV or a digital picture frame to view later. You can help your users do this by saving the document to an app-specific location on the user’s device, and by saving the photo to external storage media.

Here’s how app-specific file storage works behind the scenes in Windows Store apps. Each app can store files to a separate set of directories (called the local, roaming, and temporary directories) on a particular device:

· The local directory contains files that exist only on the local device.

· The roaming directory contains files that exist on all devices where the user has installed the app.

· The temporary directory is like the local directory, but the system can remove its files at any time.

When a user installs a Windows Store app, Windows automatically creates these directories. You don’t need to worry about where to find them because Windows tracks them for you. You just use the ApplicationData class to access them. If the user ever uninstalls the app, Windows automatically removes the matching directories so you don’t even have to worry about cleaning them up.

Windows tip
If a user wants to store app-specific files that are particularly valuable or irreplaceable, have your app store them in a more permanent location instead, like the user’s SkyDrive.

To store files in external storage media, you can use the DeviceInformation and StorageDevice classes. More about that later.

Here’s how to do all of this in code.

Save a file to an app-specific directory

In a Windows Store app, to save a file named hello.txt, write code like this for the local directory.

var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Hello.txt");
await FileIO.WriteTextAsync(file, "Hello world!");

Or write code like this for the roaming directory.

var file = await ApplicationData.Current.RoamingFolder.CreateFileAsync("Hello.txt");
await FileIO.WriteTextAsync(file, "Hello world!");

And you can write code like this for the temporary directory.

var tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("TempFile.txt");
Android tip
In Android apps, write code like this for the local directory.

String filename = "hello.txt";
String string = "Hello world!";
FileOutputStream outputStream;

outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());outputStream.close();

Set the file-creation mode to MODE_PRIVATE so that other apps can’t access your app’s files. Windows Store apps, in contrast, can access only their own files.

Write code like this for the temporary directory.

File tempFile;
tempFile = File.createTempFile("TempFile.txt", null, context.getCacheDir());

Saving a File to External Storage

In a Windows Store app you must declare the Removable Storage capability in the in the Package.appsxmanifest associated with your app

After you declare this capability, check to see if external storage media is available using code like this.

public async Task<bool> IsExternalStorageAvailable()
{
  var devices = await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector());
   if (devices.Count > 0)
    return true;
   else
    return false;
}

If the external storage media is available, create the file using code like this.

var storage = StorageDevice.FromId(deviceInformation.Id);
await storage.CreateFileAsync("HelloWorld.png");
Android tip
In Android apps, to do something similar, first request the WRITE_EXTERNAL_STORAGE permission in your app’s manifest, like this.

<manifest>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

After you request this permission, check to see if external storage media is available, using code like this.

public boolean isExternalStorageWritable() {    
 String state = Environment.getExternalStorageState();
 if (Environment.MEDIA_MOUNTED.equals(state)) {
   return true;
 }
  return false;
}

If the external storage media is available, you can then create the file. For example, to create a file in the media’s Pictures directory, write code like this.

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "HelloWorld.png");

Next steps

To learn more about saving files, see these resources.

Users often want to save the highest level that they reached in a game and then continue playing at that level when they return to their game. Or they want to continue reading where they left off when they return to a book reader.

One way you can enable this is by saving key-value pairs that persist on the user’s device between sessions and even after an app closes. In Android apps, these key-value pairs are called shared preferences. In Windows Store apps, they’re called application settings or just app settings.

To read and write shared preferences in Android apps, you use the SharedPreferences class. To read and write app settings in Windows Store apps, you use the ApplicationData class.

Windows tip
In Windows Store apps, you can also create key-value pairs by using the Dictionary class, but such pairs are stored only in local memory. They go away after they go out of scope in your app’s code.

Here’s how app settings work behind the scenes for Windows Store apps. When a user installs an app, Windows creates a special location and some special registry entries on the device to store that app’s settings. You don’t need to worry about where to find this location and the registry entries, because Windows tracks them for you. You just use the ApplicationData class to access them. If the user ever uninstalls the app, Windows automatically removes the matching app settings location and registry entries. You don’t have to worry about cleaning them up.

Windows tip
You can store more than just app-related settings. For example, you can store documents that are related to that particular app. However, if the user uninstalls that app, those related documents will automatically be removed, too. If those documents are particularly valuable, store them in a more permanent location, like the user’s SkyDrive.An app’s related settings and files together are called its application data, or just app data. Only app settings are covered in this post.

In Windows Store apps, you can store app settings in two ways: local and roaming. Local settings are stored only on the current device. Roaming settings are shared among all devices that the user installed the app on.

Here are all of the data types that you can create app settings for.

Boolean Guid Rect UInt16
Byte Int16 Single UInt32
Char Int32 Size UInt64
Char16 Int64 String Uri
DateTime Object TimeSpan Void
Double Point UInt8

Here’s how to create and get app settings in code.

Create app settings

In a Windows Store app, to create a local app setting with a key of “Name” and a value of “Me”, write code like this.

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["Name"] = "Me";

To create a similar roaming app setting, write code like this.

var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["Name"] = "Me";
Windows tip
While you can store app settings in both the local location and the roaming location, you don’t have to.
Android tip
In Android apps, to create a similar shared preference, write code like this.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 
editor.putString("Name", "Me"); 
editor.commit();

You can share preferences among apps by using interactive mechanisms in the ContentProvider, BroadcastReceiver, and Service classes. In contrast, Windows Store apps can access only their own app settings.

Get app settings

In a Windows Store app, to get a local app setting with a key of “Name” and a default value of “Me” (that is, the value “Me” is returned if the app can’t find the “Name” key), write code like this.

string nameValue = "";
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

Object value = localSettings.Values["Name"];

if (!value)
 nameValue = value.ToString();
else
 nameValue = "Me";

To get a similar, roaming app setting, write code like this.

string nameValue = "";
var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;

Object value = roamingSettings.Values["Name"];

if (!value)
 nameValue = value.ToString();
else
 nameValue = "Me";
Android tip
In Android apps, to get a similar shared preference, write code like this.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
string nameValue = sharedPref.getString("Name", "Me");

Next steps

To learn more about how to create and get app settings, see these resources:

· Quickstart: Local application data

· Quickstart: Roaming application data

· Application data sample

Over the past several weeks I’ve been posting about how to build your first Windows Phone 8 application if you’re an Android developer. I want to wrap this series by providing some useful links:

All Posts in this Series

  1. Setting up the Development Environment
  2. Creating Your First Windows Phone Project
  3. Exploring the Windows Phone Project
  4. Running the Windows Phone Application
  5. Building a Simple User Interface
  6. Adding a Second Page

If you would prefer a pdf of all seven posts you can get it here: http://aka.ms/AndroidToWindowsPhone8

Additional Windows Phone 8 Development Resources

Over the past several weeks I’ve been working on some content I’m excited to finally share with you through a series of blog posts. This series will introduce you to Windows Phone 8 development from an Android developer’s perspective. Through the course of the series you’ll create your first app. It won’t be anything pretty, but you’ll learn the ins and outs of the development environment, how to create a simple user interface, and how to perform navigation. Along the way you’ll see some Android Hints that will help make it easier for you to transition your existing skills to the Windows Phone platform. You’ll also see some Visual Studio Tips to make you more productive in your development environment. Good luck!

In the previous lesson you created a simple UI that accepts text from a user. In this lesson you’ll create a second page in your application to display the user’s input.

Create the Second Page

Right-click the project in Solution Explorer, click Add, and click New Item.

In the Add New Item dialog, select Windows Phone under Visual C#.

Select the Windows Phone Portrait Page template, give the page a name of SecondPage.xaml, and click Add.

You should now see SecondPage.xaml in Solution Explorer.

If SecondPage.xaml is not open, double-click it.

Remove the content from the outermost <Grid> element. You should end up with something that looks like this:


<!–LayoutRoot is the root grid where all page content is placed–>


<Grid x:Name=”LayoutRoot” Background=”Transparent”>

 


</Grid>

Add a <TextBlock> element to the grid:

<Grid x:Name=”LayoutRoot” Background=”Transparent”>


<TextBlock x:Name=”messageFromUser” />


</Grid>

 

Respond to the Send Button

You now need to get the message from the first page to the second page. Start by opening up MaingPage.xaml.

To respond to the <Button> element’s Click attribute to the element

<Grid x:Name=”LayoutRoot” Background=”Transparent”>

<StackPanel x:Name=”theStackPanel”

Orientation=”Vertical”>

<TextBlock x:Name=”theLabel”

Text=”{Binding Path=LocalizedResources.MessageLabelText,

Source={StaticResource LocalizedStrings}}” />

<TextBox x:Name=”theMessage” />

<Button x:Name=”sendButton”

Content=”{Binding Path=LocalizedResources.SendButtonText,

Source={StaticResource LocalizedStrings}}”


Click=”sendButton_Click”/>

</StackPanel>

</Grid>

ANDROID HINT

The Click attribute is similar to the android:onClick attribute of the Android <Button> element.

 

Open the code-behind file for MainPage.xaml (MainPage.xaml.cs) and add the following method:

private
void sendButton_Click(object sender, RoutedEventArgs e)

{

 

}

VISUAL STUDIO TIP

You can open a code-behind file for a file you’re working with in design view by pressing F7.

 

Now you need to do three things.

  1. Get the text the user entered.
  2. Create a URI to navigate to SecondPage.xaml that includes the text entered by the user. This is done by including the text as a query string parameter.
  3. Navigate to SecondPage.xaml.

All three can be accomplished by adding the following to the sendButton_Click method:

private void sendButton_Click(object sender, RoutedEventArgs e)

{


//Get the message from the <TextBox> element


var message = this.theMessage.Text;

 


//Use a default message if none is provide


if (string.IsNullOrEmpty(message))

message = “Hello World!”;

 


//Create the uri to navigate to SecondPage.xaml, passing


//the message through in the query string


var uri = new Uri(string.Format(“/SecondPage.xaml?message={0}”, message),

UriKind.Relative);

 


//Perform the navigation


this.NavigationService.Navigate(uri);

}

 

ANDROID HINT

In Android you would create an Intent and call the startActivity method to navigate to the second page with code similar to the following:

 

public void sendButton_Click(View view) {

Intent intent = new Intent(this, SecondPageActivity.class);

startActivity(intent);

}

 

If you run your app now (F5) and press the button, you’ll notice that you go to the second page. We’ll work on displaying the message in the last part of this lesson.

Display the Message

Now that you’re able to navigate to SecondPage.xaml from MainPage.xaml you need to display the message the user entered.

Open SecondPage.xaml.cs (the code-behind file for SecondPage.xaml).

Add an override for the OnNavigatedTo method


protected
override
void OnNavigatedTo(NavigationEventArgs e)

{


base.OnNavigatedTo(e);

}

 

Finally retrieve the query string parameter from the page’s NavigationContext property and display in the <TextBlock> element with the following code:

protected override void OnNavigatedTo(NavigationEventArgs e)

{

base.OnNavigatedTo(e);

 


//Check that the query string contains the message parameter


//and display on the page if found


if (this.NavigationContext.QueryString.ContainsKey(“message”))


this.messageFromUser.Text =


this.NavigationContext.QueryString["message"];

}

Run the app (F5) to see the results!

Conclusion

Congratulations! You just build your first Windows Phone application. To learn more about building Windows Store apps, continue to follow this series. The next installment is Working with Data.

Previous Posts in this Series

  • Setting up the Development Environment
  • Creating Your First Windows Phone Project
  • Exploring the Windows Phone Project
  • Running the Windows Phone Application
  • Building a Simple User Interface

Additional Resources


 

Over the past several weeks I’ve been working on some content I’m excited to finally share with you through a series of blog posts. This series will introduce you to Windows Phone 8 development from an Android developer’s perspective. Through the course of the series you’ll create your first app. It won’t be anything pretty, but you’ll learn the ins and outs of the development environment, how to create a simple user interface, and how to perform navigation. Along the way you’ll see some Android Hints that will help make it easier for you to transition your existing skills to the Windows Phone platform. You’ll also see some Visual Studio Tips to make you more productive in your development environment. Good luck!

A Windows Phone application is simply a collection of pages. A page is the interface seen by the end user.

ANDROID HINT

A page is similar to an Activity in Android development

 

Each page is designed for the end user to interact with the application. A page is composed of layout controls and various widgets. Only one page can be seen by the end user at a time.

ANDROID HINT

Like Android there is a system level “Back” button in Windows Phone.

 

To better familiarize yourself with the user interface components of a Windows Phone application the following table maps Android widgets to their Windows Store counterparts:

Purpose

Android

Windows Store

Display Text

TextView

TextBlock

Edit Text

EditText

TextBox

Radio Button

RadioButton

RadioButton

Check Box

CheckBox

CheckBox

Submit

Button

Button

Show Progress

ProgressBar

ProgressBar

Display a List of Components

LinearLayout

StackPanel

Vertical List of Components

ListView

ListView

2-Dimensionl Grid

GridView

Grid

Display an Image

ImageView

Image

 

This is by no means an extensive list. As with many development technologies there are a number of ways to perform the same task. For example, instead of using a ListView to display a vertical list in a Windows Phone app I could simply use a StackPanel and set its orientation property accordingly.

In this lesson you’ll learn how to create a simple interface for your Windows Phone application.

Add a Text Field

For your UI you’ll want a label to tell the user what to do, a field where users can input text, and a button. You’ll start by adding the text field.

Open the MainPage.xaml file in the root directory of your project.

VISUAL STUDIO TIP

When you open a *.xaml file you’ll first see a split view. The left view contains a visual designer. This lets you build layouts using WYSIWYG tools. The right view contains the markup generated by the designer. For this lesson, you’re going to work directly with the XAML. To give yourself more screenspace you can go to a “XAML only” view using the following steps.

  1. Click the button on the toolbar between the designer and the markup view. This will move the markup view to the left and designer view to the right.
  2. Click the button on the toolbar between the two views. This will minimize the designer.

 

You’ll notice that Visual Studio adds quite a bit to the markup for a page when it is created. For simplicity we’re going to delete most of it. Delete everything within the outermost <Grid> element of the page. You should end up with something that looks like this:


<Grid x:Name=”LayoutRoot” Background=”Transparent”>

 


</Grid>

Add a <StackPanel> element to the <Grid> element:


<Grid x:Name=”LayoutRoot” Background=”Transparent”>


<StackPanel x:Name=”theStackPanel”


Orientation=”Vertical”>


</StackPanel>

</Grid>

ANDROID HINT

A StackPanel is equivalent to a LinearLayout in Android development. It allows you to lay out child elements in either a verity or horizontal orientation.

 

The x:Name attribute is similar to the android:id attribute. However, you are not required to provide a x:Name attribute for your visual elements.

 

The Orientation attribute is identical to the android:Orientation attribute of the LinearLayout in Android. The default value for the Orientation attribute is Vertical.

 

Now add a <TextBox> element inside of the <StackPanel> element you just created. Be sure to provide a x:Name attribute for it. You should end up with something like this:

<Grid x:Name=”LayoutRoot” Background=”Transparent”>

<StackPanel x:Name=”theStackPanel”

Orientation=”Vertical”>


<TextBox x:Name=”theMessage” />

</StackPanel>

<Grid>

 

Add String Resources

Next you’ll want to add a label to your page to instruct the user on what to do. You might be tempted to add a <TextBlock> element and sent its Text attribute to the text you want displayed. While this will work, it goes against best practices for localization.

Start by opening the AppResources.resx file by double clicking it in Solution Explorer.

You’ll see several resources were defined when Visual Studio create the project. To add an additional resource, simply enter it on the last line of the editor. You should end up with something like this:

Add a Label

With the Resource file in place you’re now ready to add the label to your page.

Open MainPage.xaml if not’s not already open and add a <TextBlock> element above the <TextBox> element in the <StackPanel> like this:

<Grid x:Name=”LayoutRoot” Background=”Transparent”>

<StackPanel x:Name=”theStackPanel”

Orientation=”Vertical”>


<TextBlock x:Name=”theLabel”


Text=”{Binding Path=LocalizedResources.MessageLabelText,


Source={StaticResource LocalizedStrings}}” />

<TextBox x:Name=”theMessage” />

</StackPanel>

</Grid>

The Text attribute specifies the text the element will display. You need to do two things:

  1. Specify where the string resides (Source={StaticResource LocalizedStrings}).
  2. Specify the name of the specific string you want to use (Binding Path=LocalizedResources.MessageLabelText).

Add a Button

The last thing you’ll need to do as part of this lesson is to add a <Button> element to the page so you can send the message the user enters to a second page.

Before you add the <Button> be sure to add a string resource for its Content property in the AppResources.resx file.

Now add a <Button> element under the <TextBox> element in MainPage.xaml, being sure to specify the appropriate Content attribute for localization.

<Grid x:Name=”LayoutRoot” Background=”Transparent”>

<StackPanel x:Name=”theStackPanel”

Orientation=”Vertical”>

<TextBlock x:Name=”theLabel”

Text=”{Binding Path=LocalizedResources.MessageLabelText,

Source={StaticResource LocalizedStrings}}” />

<TextBox x:Name=”theMessage” />


<Button x:Name=”sendButton”


Content=”{Binding Path=LocalizedResources.SendButtonText,


Source={StaticResource LocalizedStrings}}” />

</StackPanel>

</Grid>

Congratulations! You just created your first Windows Store UI. It might not be pretty, but it works. You can run your app now (press F5 or F6 to see the results).

Previous Posts in this Series

  • Setting up the Development Environment
  • Creating Your First Windows Phone Project
  • Exploring the Windows Phone Project
  • Running the Windows Phone Application

Additional Resources

Over the past several weeks I’ve been working on some content I’m excited to finally share with you through a series of blog posts. This series will introduce you to Windows Phone 8 development from an Android developer’s perspective. Through the course of the series you’ll create your first app. It won’t be anything pretty, but you’ll learn the ins and outs of the development environment, how to create a simple user interface, and how to perform navigation. Along the way you’ll see some Android Hints that will help make it easier for you to transition your existing skills to the Windows Phone platform. You’ll also see some Visual Studio Tips to make you more productive in your development environment. Good luck!

In the last lesson you explored the Windows Phone project Visual Studio created for you. Now it’s time to run and see what it looks like. There are two different ways you can run the application:

  1. In an emulator
  2. On a device

In this lesson you’ll learn how to run the application in both of these ways.

Emulator

Windows Phone Emulator is a desktop application that emulates a Windows Phone device. It provides a virtualized environment in which you can debug and test Windows Phone apps without a physical device. It also provides an isolated environment for your application prototypes.

Windows Phone Emulator is designed to provide comparable performance to an actual device. Before you publish your app to the Windows Phone Store, however, it is recommended that you test your app on a physical device.

You can test your app on a unique emulator image for each of the OS versions and screen resolutions supported by Windows Phone. The default emulator image in Visual Studio is Emulator WVGA 512MB, which emulates a memory-constrained Windows Phone 8 phone. This default selection encourages you to target the largest possible market for your Windows Phone 8 app.

To run the application in the emulator, simply click the button in the toolbar. This will do the following:

  1. Build your app.
  2. Package your app.
  3. Start the emulator (if it isn’t already running).
  4. Deploy (install) your app in the emulator.
  5. Start the app.

Of course, there’s not much to see yet, but at least your app is running!

Device

The emulator is designed to provide comparable performance to an actual device. Before you publish your app to the Windows Phone Store, however, it is recommended that you test your app on a physical device.

There are three prerequisites to running your app on a device from Visual Studio:

  1. Register with the Windows Phone Dev Center at http://bit.ly/StpJhE. When you set up your development environment this was an optional step. To run your app on a device this is required.
  2. Acquire a Windows Phone device. This might seem obvious, but you never can tell.
  3. Unlock the device using the Windows Phone Developer Registration tool that was installed on your machine when you installed Visual Studio. After you unlock your device you should see a screen like this:

 

After you have unlocked your Windows Phone running your app on the device is simple.

  1. Click the arrow on the right hand side of the button in the toolbar.
  2. Select Device from the dropdown.
  3. Click the button in the toolbar.

This will do the following:

  1. Build your app.
  2. Package your app.
  3. Deploy (install) your app to the device.
  4. Start the app on the device.

VISUAL STUDIO TIP

You don’t have to press the toolbar button to run your app. After you’ve selected where you want your app to run (Emulator or Device) you can press F6 to simply run the app or press F5 to run the app in debug mode to step through code.

 

That’s how you run your first Windows Phone app! Of course there isn’t much to see yet. In the next lesson you’ll start building out the user interface.

Previous Posts in this Series

  • Setting up the Development Environment
  • Creating Your First Windows Phone Project
  • Exploring the Windows Phone Project

Additional Resources

 

Over the past several weeks I’ve been working on some content I’m excited to finally share with you through a series of blog posts. This series will introduce you to Windows Phone 8 development from an Android developer’s perspective. Through the course of the series you’ll create your first app. It won’t be anything pretty, but you’ll learn the ins and outs of the development environment, how to create a simple user interface, and how to perform navigation. Along the way you’ll see some Android Hints that will help make it easier for you to transition your existing skills to the Windows Phone platform. You’ll also see some Visual Studio Tips to make you more productive in your development environment. Good luck!

In the last lesson you created your first Windows Phone project. In this lesson you’ll spend some time exploring the project and learning about some key files and directories.

WMAppManifest.xml


This is the application’s manifest. It is an XML document that contains details about the app, such as the App ID and the capabilities the app uses.

ANDROID HINT

WMAppManifest.xmal is similar to the AndroidManifest.xml file used by Android applications.

 

Here is some additional information about the manifest:

  • When you submit your apps to the Windows Phone Store, info from the manifest file is used in the certification process, to filter your app correctly in the Store, and to deploy and run your app on the device.
  • The info from the manifest file is stored as metadata in the app database.

If you double-click the manifest in the solution explorer you’ll get a UI you can use to edit the various properties of the manifest. For this app we’ll leave everything as is.

ANDROID HINT

In the generic Android app example I mentioned earlier, you set the default activity for the app in AndroidManifest.xml. Typically it looks something like this:

If you open up WMAppManifest.xml you’ll see an option for Navigation Page this is where you set the default page for the app to open when it starts.

 

MainPage.xaml and MainPage.xaml.cs


As mentioned in the last lesson XAML (eXtensible Application Markup Language) is the declarative language used to create the UI for Windows Phone applications. MainPage.xaml is the default page for your application. This is where you’ll create your simple UI (in the next lesson). MainPage.xaml.cs is the associated C# code that goes along with your UI.

VISUAL STUDIO TIP

The *.xaml.cs file that is associated with a *.xaml file is called the code-behind file.

 

ANDROID HINT

The relationship between *.xaml and *.xaml.cs files is similar to the relationship between layouts and activities in Android development. When you create a generic Android app, you’ll get an activity_main.xml file in the res > layout
directory. This is where you define the UI for your Android app. You also get a MainActivity.java file in your src directory. This is where you write the code that goes along with the UI. In our app MainPage.xaml corresponds to activity_main.xml, and MainPage.xaml.cs corresponds to MainActivity.java

 

App.xaml and App.xaml.cs


App.xaml can be used to store information about application wide resources. By default a reference is added to a file used to store localized string values.

App.xaml.cs provides application-specific behavior to supplement the default application class. This is also where you can tie into the following events of the application lifecycle:

  • Launching – when the application is initially launched.
  • Activated – when the application is brought to the foreground after being in the background.
  • Deactivated – when the application is sent to the background due to a system event (i.e. phone call).
  • Closing – when the user presses the hardware Back button.

ANDROID HINT

The following table maps the appropriate Android method to its Windows Phone event counterpart:

Android Method

Windows Phone Event

onCreate()

Launching

onStart()

Launching

onResume()

Launching or Activated

onPause()

Deactivated

onStop()

Closing

onDestroy()

Closing

 

The Windows Phone application lifecycle will be covered in depth in another installment of this series.

Assets Directory

The Assets directory contains default artwork used by the application.

ANDROID HINT

The items contained in the Assets directory are similar to those found in the res/drawable-* directories of your Android projects.

 

Resources and LocalizedStrings.cs

The Resources directory contains resources used across the application. By default it contains one file, AppResources.resx. This file is where you store strings displayed in the UI for localization.

ANDROID HINT

AppResources.resx is similar to the res/values/strings.xml file used in Android projects.

 

The LocalizedStrings.cs file wraps access to the AppResources.resx file and gives your app programmatic access to the string resources it contains.

As you can see, Visual Studio gives you a lot for free so you can get started on your app. You should continue to explore your project set up as well as the files and directories that get created with the of the other project templates as Visual Studio does a lot of heavy lifting for you.

In the next lesson you’ll learn how to run your application.

Previous Posts in this Series

  • Setting up the Development Environment
  • Creating Your First Windows Phone Project

Additional Resources


 

Windows Phone 8 offers up some exciting new features and opportunities for developers. The customer base is getting larger with new form factors and low-memory devices. Is your app ready? Are you ready to add the new Windows Phone 8 features to your existing 7.x app? Do you understand the key scenarios to make your app shine on Windows Phone 8 and bring nothing but 5-star reviews? The Windows Phone Evangelism team at Microsoft is hosting a Windows Phone 7.x Upgrade Lab to help you make your app shine on Windows Phone 8.

What is a Windows Phone Upgrade Lab?

The Windows Phone Upgrade Lab is a free, fun, no-fluff workshop for Windows Phone Developers by Windows Phone Developers. Our Technical Evangelist team will introduce you to the new features in Windows Phone 8 and what you, as a Windows Phone Developer, need to do to take advantage as these features. We will also guide you along the path of making your app work great across the new form factors and low memory devices coming from the many Windows Phone manufactures. Below are the locations and dates of our upcoming labs:


Location Date
Houston, TX 4/11
Irving, TX 4/15
Southfield, MI 4/16
Columbus, OH 5/3
Chicago, IL 5/7
Edina, MN 5/7
Indianapolis, IN 5/9

What can I expect?

The Windows Phone Upgrade Lab is a working lab. This means, bring your development machine and your source code and be ready to submit your Windows Phone 8 updates by the end of the day. We will start off the day by discussing the new developer features of the Windows Phone 8 SDK. Following this, our technical experts will be on-hand to assist you in bringing some of these features to life in your app. We will help identify what features would be best utilized in your app, help you implement those features, and assist you in submitting your app into the store by days end. We will cap off the day by introducing you to strategies for bringing your app to Windows 8 and opening up your app to a whole new world of new customers!

Some of the features we’ll be discussing, include…

  • New Windows Phone 8 Features
  • What is the Windows Phone Runtime?
  • What’s new in Tiles and Notifications
  • Handling Multiple Resolutions
  • Understanding the required artwork
  • New Proximity Scenarios with Bluetooth and NFC
  • New Mapping technology from Nokia
  • Lock Screen integration
  • How to start thinking of bringing your app to Windows

Notes:
1. Download and Install the Windows Phone 8 SDK at http://aka.ms/Phone8Tools

2. The Windows Phone 8 SDK Emulator requires your machine to support SLAT (Second Level Address Translation). You can verify if your machine supports SLAT by running the CoreInfo tool. More information can be found at http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj863509(v=vs.105).aspx.

If your machine does not support SLAT, you can still use the SDK and test against a physical Windows Phone Device. If you don’t have a Windows Phone 8 device, we will have some on hand during the workshop to test with.

3. You can get a jump start on the workshop by working through the tutorials in the Windows Phone 8 Training Kit or playing around with the many Windows Phone Code Samples.

In addition to registering for this Workshop, be sure to take advantage of great resources such as access to free expert guidance, app and game frameworks, as well as free storage and tools with Generation App! Sign up at http://aka.ms/AppFor8.