Posts Tagged ‘Windows Phone’

Is Microsoft becoming the cool kid?

Times are changing…

I just came back from Microsoft TechEd North America, so much more than PowerPoint!!

They had the Microsoft Mustang developed as Project Detroit that was developed with West Coast Customs. This project was so cool it was featured on CoolCarsHotGirls, who ever thought Microsoft would be on a website with a name like that!. By the way it’s Open Source too!

Similar to a concept car, Project Detroit was created to inspire developers to think about building apps and automotive technologies of the future. Connected-device scenarios featured in the car incorporate Kinect for Xbox 360, Xbox 360, the Windows operating system, Windows Phone, Windows Azure, Bing, Ford Sync and more.They had the Boxing Bots from Coding for fun (thank you Clint for helping me beat @GeekTrainer not once, but twice). This brings Rock’em Sock’em robots to a whole new level and controlled by Kinect! Coding4 Fun does some very cool stuff!

Battling Bots with Kinect

Not only that they had a whole section of classic arcade games. (Galaga!) Vijay destroyed me at air hockey, but I retained some Canadian pride by subsequently beating him at bubble hockey.

The Kinect just makes everything more fun, they even had a Windows 8 app on a massive screen where you could zoom in and out with Kinect on a flight tracking application!

I had some great discussions, including one with a developer from the company that built the Hunger Games and Prometheus websites using HTML5.

There were also  opportunities to check out Windows Phones including the Nokia Lumia 900 which was reviewed and recommended by Playboy magazine?!  Sure Consumer Reports recommending the Titan as a good buy, but Playboy!

I also had fun showing off my own Samsung slate running Windows 8 to lots of curious developers showing them some of the features that I think make developing for Windows 8 unique (Share Contracts rock!)

Oh yeah, there were some good sessions too Smile, I particular recommend the exam cam on the 70-599 Windows Phone exam, but I’m biased.

If I can build a phone app anyone can: Changing the keyboard and IsNumeric

In todays blog I start coding my app, the first task is having users enter a time for my timer and making sure they enter a number. So I explore adding code to make sure they enter a number, and changing the on screen keyboard to show just numbers.

Wow I’ve been spending a lot of time learning about the projects, tools, and controls, it’s great that I am finally starting to code! If you missed any earlier posts you can find them here. My application will be a presentation timer that I can use to make sure I don’t talk too long.

I’ve created a New project of type Windows Phone Application in Visual C# (by the way as I start to code if you can make any of my code more elegant, feel free to leave comments, I am open to suggestions and improvements).

When I created my project I chose target Windows Phone OS 7.1 (which is the same as 7.5 which is the same as Mango) because at this point most Windows Phone users have Mango and I want to be able to use the latest features.

Adding validation code

I need a text box where a user can enter the number of hours, minutes, or seconds for the timer. So I’ll just drag a TextBox control to my page. I change the name of the TextBox to txtHours and set the Text to a value of 1, this will be the default value. When I run the app and click in the TextBox it looks like this.

TextKeyboard

I don’t want users entering letters, so I had better add some validation to make sure the users enters numbers in the TextBox and i will add a TextBlock for displaying an error message to the user.

I create a TextBlock control and name it blkMessage and set the Foreground property to Red and the Text property to an empty string.

Now I double click on the my TextBox control which takes me to the code page and creates a TextChanged event handler for me. The TextChanged event handler fires whenever a user changes the content of my TextBox, so it literally fires every time you type in a letter or number (that means I don’t want too much code in there because it wouldn’t be great for performance). In my event handler I test to see if the value in the text box is numeric, if it isn’t, I display an error message. If it is a valid value, I clear out the error message. My code looks like this. BUT IsNumeric is a function I had to add myself it is not built in! I got the code for the IsNumeric function from this blog post (thank you Keith Murray)

        private void txtHours_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!IsNumeric(txtHours.Text))
            {
                blkMessage.Text = "You must enter numbers only";
            }
            else
            {
                blkMessage.Text = "";
            }
        }

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

Now if a user enters letters or other non numeric values in the field they see an error message like this:

EnterNumbersOnly

Changing the on screen keyboard

That works, but I don’t like the way the keypad comes us as letters as default which could be a bit annoying. With mobile apps you really want the user to have to use the keyboard as little as possible, so every keyboard tap I can save the user is a good thing. In addition, it’s good design to stop someone from entering an invalid value in the first place wherever possible, if I display a numeric keypad I don’t need to worry about someone entering letters and symbols! A quick bing search turns up a blog post that talks about setting the InputScope to get the numeric keyboard. Sounds worth a try. Unfortunately I can’t find a way to set that value in the property page so I am going to have to edit the XAML, and of course the XAML example in the blog post doesn’t work, but a quick search on MSDN for InputScope gives me the correct syntax.

So I have to open up the XAML pane by clicking on the little arrow button in the corner

imageThen find the <TextBox …/> called txtHours and add the InputScope attribute and set it to Number (wow I didn’t think I’d be messing in the XAML code this soon! but this really wasn’t that scary)

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBox InputScope="Number" 
                     Height="69" 
                     HorizontalAlignment="Left" 
                     Margin="76,106,0,0" 
                     Name="txtHours" 
                     Text="1" 
                     VerticalAlignment="Top" 
                     Width="77" 
                     IsEnabled="True"/>
        </Grid>

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

And now when I run the application in the emulator, check it out: just numbers! Much better for my user!

NumericKeypad

So now I just need to replicate that logic for my hours, minutes and seconds textboxes. It’s fun to be starting my application. We’ll see what I learn next. Hope you are making progress with your apps as well. Remember if you publish an application by May 20th, 2012 you can get cool stuff thanks to the developer movement so get coding!

If I can build a phone app anyone can: Controls, and more controls…

In this blog I create my project and have to learn the different controls I can choose from to build my app

As I continue my series on building my first phone app, I have chosen the Windows Phone application template and I am ready to start adding controls to my first page. If you missed any of the earlier posts in the series, you can access them here.

As I look at the Toolbox, I realize there are a lot of different controls to choose from, so in this post I’ll try to figure out what they do. There are so many controls I broke them into three groups for my quick description of each control just scroll down, I’ve also tried to hyperlink to documentation on the controls as I researched what each control is for.

Controls for entering and displaying data

  • Checkbox
  • ListBox
  • Map
  • PasswordBox
  • RadioButton
  • Slider
  • TextBlock
  • TextBox

Controls that do stuff

  • AdControl
  • Button
  • HyperlinkButton
  • MediaElement
  • WebBrowser

Controls to make things look pretty

  • Border
  • Canvas
  • Ellipse
  • Grid
  • Image
  • Rectangle
  • StackPanel

Controls for entering and displaying data

CheckBox

A Checkbox is a great way to let a user enter a Yes or No | True or False value. You’ll need to set the Content property to change the text that appears beside the textbox. The IsChecked property tells you whether the checkbox is checked or unchecked. There is also a IsThreeState property which allows you to have a checkbox represent something 3 different values like Yes/No/Unknown. IsChecked will be true if the checkbox is checked, false if the value is unchecked. If you enable the IsThreeState the unknown/undetermined state of the checkbox will return a value of Nothing for IsChecked.

imageListBox

Allows you to give the user a list of items to choose from. Specify the values to show in the list using the Items property, or I am sure you can set up data binding as well to read the data to display from some form of data source. This is the sort of list that takes up a lot of space on the screen, it’s not a drop down list. When you select one of the values it will be highlighted. I don’t see an option for allowing multiple selections, and it’s really hard to select the listbox after you create it, whenever I click on the listbox, it keeps selecting the Listbox items instead which is kind of annoying.

image

Map

I guess you use maps to display data, data such as where you are, or where something is located! Looks like using this control is a bit more involved! There is all sorts of extra stuff they talk about like if you want to use a Bing Maps Silverlight Control you need a Bing Maps key which you get from the Bing Maps Account Center. I get the feeling the map control would be a blog unto itself! So for now I’ll just say, yes you can display a map and highlight locations on a map or directions on a map. I know the Where’s Timmy app from Tim Hortons has a map!

PasswordBox

This is like a text box where you can enter data, but no-one can see what you are typing, perfect for entering passwords! Instead a character appears on the screen. You can control what character appears with the PasswordChar property.

image

RadioButton

Great to give a user selection between 2-5 choices on the screen and only one can be selected at a time. Use the Content property to change the text displayed beside the radio button. The IsChecked Property will tell you if a particular radio button is selected. When you add multiple radio buttons to a screen by default they all become part of one group, so as soon as you choose one radio button, all the others are deselected.

imageSlider

A slider is great for getting a user to choose a value in a range. You specify the highest and lowest values for the slider control with the Minimum and Maximum properties and then the Value property will tell you the value selected by the user.image

TextBlock

This is your label control for displaying text. You specify the text to display with the Text property.

image

TextBox

This is your control for letting users type in data with the on screen keyboard, the Text property will tell you the value entered by the user or can be used to set a default value.

image

Controls that do stuff

AdControl

This is the new control that came out which allows you to include advertising in your applications. Adding the control is pretty straightforward, drag and drop. You can set the height and width properties to resize it. But it takes more than just dropping the control on your form to get advertising working according to this site. You have to register your mobile app using Microsoft pubCenter and then you have to set the Application Id and Ad Unit ID properties in the ad control then you will have an ad enabled app in the marketplace to make money.

Button

Buttons are what you expect, buttons a user can tap to do something. You’ll want to set the Content property because that controls the text that appears on the button. At some point you will create Click event handlers for the button as well where you can write the code that makes stuff happen when a button is pressed. One thing I noticed about the button control on the phone is the buffer around it. It turns out this is deliberate so you don’t accidentally put buttons really close together and make it hard for someone with fat fingers to tap the right button.

image

HyperlinkButton

Is exactly what it sounds like: it’s a button that looks and acts as a hyperlink. You will want to set the NavigateUri property to specify where to go when someone clicks it, and the Content property to change the text that appears for the button.

image

MediaElement

This control lets you add audio or video. You specify the audio or video to play in the Source property. I found a little article here that describes how to use this control.

WebBrowser

This control could display HTML content you generate in your code if you want to get fancy, or you can use it to display content from a website specified by the Source property.

image

 

 

Controls to make things look pretty

Border

Allows you to draw a pretty border around other controls on your form. You can set the properties you would expect like BorderThickness and BorderBrush to control the color and thickness of the line around the border, Background to change the background color within the border. CornerRadius is kind of cool so I can make rounded corners. Wow, I could make some really ugly apps with this. Check out my green and red border with rounded corners! Did I mention, I am not known for making elegant looking pages.

imageCanvas

According to MSDN: “A canvas defines an area within which you can explicitly position child objects by using coordinates relative to that area.” Okay then I guess I would use a canvas if I want to be able to move something around on the screen with my code. I guess I could make one of those annoying pages with a button that says “Click here to win one million dollars” and whenever you tap on it it moves. You can set the Background property to set the background color.

Ellipse

This just draws an ellipse on the screen. The Stroke property controls the color of the outline of your ellipse. StrokeThickness controls the width of the line. Fill controls the background colour of the ellipse. Weird how all the property names are different for Ellipse than they are for Border and Canvas eh? I made an ugly red and green ellipse to go with my ugly border.

image

Grid

A grid is an area made up of columns and rows, so this would be great for displaying a table of data. You’ll need to go to the ColumnDefinitions property and add ColumnDefinitions for each column you want in the table. For each column you can specify a MinWidth and MaxWidth property. Then you need to go to the RowDefinitions Property to add a RowDefinition for each row. There is also a ShowGridLines property that controls whether you see the lines on the grid between columns and rows. You can then add controls in the different squares of the grid. Here’s my 3 row, 2 column grid with the grid lines displayed.

imageImage

Okay I know Images can be used to display data or to make things look pretty, I had to pick somewhere to put it! The image control allows you to display images. Use the Source property to specify the image to display. If your images aren’t the same size as your image control, play around with the Stretch property to control whether it clips, or resizes the image for you. It looks like JPEG and PNG formats are supported

imageRectangle

This just draws a rectangle on the screen. The Stroke property controls the color of the outline of your rectangle. StrokeThickness controls the width of the line. Fill controls the background colour of the ellipse. Weird how all the property names are different for Ellipse than they are for Border and Canvas eh? I decided to go with blue and green for my rectangle Smile

image

ScrollViewer

The ScrollViewer lets you create a scrollable area, great for letting users read large amounts of text that might not fit on the scree, the user can then scroll to see all the content. It can have a horizontal or vertical scroll bar which you control with the HorizontalScrollBarVisibility and the VerticalScrollBarVisibility properties. Now what’s interesting is when I did a little searching I found a few articles that said you need to use Blend to create a ScrollViewer, those were pre 7.5, but when I tried to dig into 7.5/Mango I found comments about performance improvements so maybe you still need to use Blend to create this, still not sure. I could see this control being very useful though!

StackPanel

A StackPanel lets you nicely line up child controls horizontally or vertically, for example you could make sure all your radio buttons are nicely lined up. I like this one, easy to use and helps me make my form look much cleaner!

image

If I can build a Phone App anyone Can – What project type to choose? Pivot? Panorama?

Part 4 in Susan’s series on building a Windows phone app from absolute scratch, in this post I figure out the differences between project types including pivot and panorama.

Did you miss part of the series? Check here!

Okay, I’ve installed the tools, I’ve done a Hello World application.l I want to start building my app now! So Go to Visual Studio 2010 | File | New Project and I see this…

CreateNewPhoneProject

There are 9 different project types just for Silverlight! (Quick aside: the XNA Game Studio 4.0 Phone projects are generally for games, and I am not going to try a game for my first app, but if you have played with XNA and are interested go for it and let me know how it goes, I’ve seen lots of cool windows phone games built by students!)

So which one should I use? Well I suppose I need to figure out the differences so here goes, I’ll dig through all the documentation and hopefully save you some time and effort doing the same.

Windows Phone Application

This creates a one page application. I checked and yes, you can add additional pages. You can’t get any simpler than this as a project type. So if your application is just going to be one or more screens and you will have the user navigate between them, this will work. Users will click on buttons or links to move between pages.

Windows Phone Databound Application

This creates a one page application, that has a listbox on the page and it implements the Model-View-ViewModel design pattern! Well that clears that up!  Okay what the heck does that mean for me…apparently its a way to separate your data from your user interface. So basically you write a class that says what data you want to show in the application (that’s the Model part), then you design a control that will show the data (that’s the View part), then you write code that says which bits of data display in which parts of your control (that’s the ViewModel part). Users will click on buttons or links to move between pages.

So I would choose this type of project if I was designing an app that was going to get data from some sort of source and was going to be displaying this data to the user. I think the Where’s Timmy app that finds you the nearest Tim Hortons is an example of a Windows Phone Databound application.

Windows Phone Class Library

If you are planning to build multiple phone applications, and you write a clever piece of code that you want to be able to re-use in more than one phone app, put it into a Windows Phone Class library.

If you aren’t sure, you can always do this later. I have two apps I want to build this year, both of them will have a timer that counts down, so there is a probably a way I can make the logic that counts down the timer re-usable. But for my first app, I’m not going to worry too much about re-usability, I just want to get it working, I’ll probably go back and rework it a bit to make the code re-usable when I build my second app. But if you are one of those programmers who likes to make everything re-usable right from the get go, you could add a Windows Phone Class Library to your application right away to hold the code you want to use in other apps.

Windows Phone Panorama Application

Gives you a project with a panorama control. Well that doesn’t help if I don’t know what a Panorama control is! Luckily I have a co-worker who wrote a blog post on the difference between panorama and pivot and here’s what I learned from that post.

Forgetting the phone for a second, a panorama picture is one of those long horizontal pictures like this

panoramapicture

On phones sometimes you scroll up and down, sometimes you scroll from left to right. Apparently they did research and figured out that it is more natural for our hands to scroll side to side instead of up and down (who knew!) Panorama applications are designed for sideways scrolling. When you do a panorama application you can make multiple pages appear on a single background. Users scroll side to side to see the different pages but the pages feel more integrated as you scroll across the content because you have a continuous background. It’s a really cool look and feel. You move from one page to the next as you scroll. It’s great for unstructured content, where you just want someone to explore by scrolling across to see what’s in the application. The red rectangle below gives you a sense of what the user sees on the screen. They can see just a fraction of the header and content for the second page so they can see that something is there and it encourages them to scroll and explore.

panoramapicture

The IMDb app is an example of a Panorama app.

Windows Phone Pivot Application

According to MSDN a pivot application is a phone that uses a Pivot Control (and if you look up redundant in the dictionary it says see redundant). So back to Paul’s blog on Pivot vs Panorama.

Pivot applications scroll left to right just like panorama applications, but Pivot applications are usually more structured and data driven. If you think your user will expect specific menu items to choose from in the application, go with pivot. For example, when I open a twitter application, as a user I want to be able to choose between viewing my twitter feed, my Direct messages, and tweets that mention my twitter handle. Each of those will display a different list of data on my screen.

Another difference between a pivot and panorama control is that you can see the title of the next page. The user can scroll to move pages or tap the menu item to move to the that page. For example, if I built an app for the winter Olympics, when they are looking at Today’s events they can see from the title bar that scrolling will take them to the medals, or they can tap the word medals to move to that page.

PivotControl

You can’t see any content from the medals until you move to that page.

PivotControlSecondScreen

The Globe and Mail is a pivot application, so is the email application built into the phone.

These rules are not absolute! There is no rule that says you can’t show structured data in a panorama app. Check out the Facebook app, they went with Panorama, Twitter went with Pivot. I recommend checking out different panorama and pivot apps and seeing which you think best suits your app.

Windows Phone Silverlight and XNA Application

This creates a project that allows you to use Silverlight and XNA in the same application. This is something that lots of people wanted and was added in 7.5/Mango. You can also go the XNA Game Studio 4.0 project types and pick the same template. You get the same template either way. This template will give you an application with two pages: one Silverlight, and one Silverlight that shows XNA content. You also get a button to go from the Silverlight to the XNA.

Gamers like to use this project type because they use XNA for their games, but Silverlight is great for things like listing high scores, or letting users choose between levels.

Don’t dismiss it for non gaming applications! if you want to add cool 3D graphics to your application you’ll need XNA for that. Check out the application built by British Airways, it’s a great example of how using XNA can add some Wow to a Silverlight application.

Windows Phone Audio Playback Agent

Want to play music in the background? Do you want the option of having the music keep playing if someone leaves the application?

Adding this project to your application will give your application access to the classes you need to play audio files in the background.

Windows Phone Audio Streaming Agent

This is the same as the Windows Phone Audio Playback agent except you use it for streaming audio files.

Adding this project to your application will give your application access to the classes you need to play streamed audio files in the background.

Windows Phone Scheduled Task Agent

Do you want to have a scheduled task running in the background? Do you want to periodically check if there are new blog entries? DO you want to refresh data on the phone when the user has a network connection instead of over the data plan?

Adding a windows phone scheduled task agent gives you access to the classes that allow you to schedule tasks to run in the background at a particular time or under particular conditions (such as when the user has a network connection).

Wow, did that blog ever take me a long time to write! But I feel a lot better about my understanding of the project types now and hopefully I saved you some time with the summary. There are really 4 base project types: Phone Application, Phone Databound Application, Panorama, and Pivot. My first app is going to be a timer so I’m starting with a Phone application next blog I can start coding my app!

Join me on my quest to publish an app, and remember you could get cool stuff if you publish an app in Canada by May 20th, 2012.

If I can build a phone app anyone can!

I can write code, but I always run into issues installing, testing, deploying, and dealing with nit-picky stuff. Everyone told me if you can code you can build a phone app, so I decided to put that to the test in this blog series.

I will update this blog post as I continue my adventures so you can follow the series, please join me on my adventure as I code and publish my first app!

Part 1 – Installing the tools

Part 2 – Writing Hello World

Part 3 – Tombstoning

Part 4 – Project Types (Pivot vs Panorama and more)

Part 5 – Controls and more Controls

Part 6 –  Displaying a numeric keypad and validting numeric values

If I can build a phone app anyone can: Part 3 What the heck is tombstoning?

Every time I start digging through Windows Phone stuff I find a blog or video about tombstoning (well okay not that kind). Now that I have my Hello World App I am ready to figure out what the heck tombstoning is! If you want to build an app you will need to know it, if you don’t have tombstoning, your app might not be accepted in the marketplace. So today I’m going to figure this out!

For those of you just joining, I am learning to build a phone app from scratch. If you can code you can build a phone app. The first two blogs in the series will get you started if you need help.

Part 1 Getting the tools you need

Part 2 Writing Hello World

So apparently tombstoning is all about making sure your app gives the user a nice experience if they have to do something like answer a call on their phone (I know, who ever uses their phone for phone calls anymore, let’s say you have to answer a text message, that’s more realistic). You wouldn’t want a user to enter a bunch of information on the screen painstakingly done on a tiny keyboard, leave the page to send a text, come back and have to enter it all over again! That would not make you popular! So tombstoning is about making sure when you come back to the app everything is the way you left it.

At the end of our Hello World app we had a page with a textbox, button, and textblock that looked like this

HelloSusanNow apparently a simple way to test tombstoning is to click on the “Windows” button to go back to the menu, and then use the back button to return to your application.

PhoneButtons

So If I type Susan into the textbox, hit the Windows key, yup I leave the application, then I hit the Back button and I am back at the application and hey it remembers the value in my text box! Sweet! So I guess I don’t have to worry about writing any code for tombstoning. I know in the pre-Mango applications it didn’t work this way, because your application was deactivated when you left and it didn’t remember state. But they fixed that in Mango. This could be my shortest blog post ever! But no… you see what happened, is when I pressed the window button and went back to the menu, my app was deactivated and became dormant. When I tapped the back button to return to my app it became active again. Here’s a diagram I found that describes what my mango phone application is doing.

image

BUT!!!! Yes there is a but, the phone can’t just leave all applications in memory forever, that would make the other applications run really slow, and drain battery power. So what happens is the phone keeps an eye on the memory and if there is too much running on the phone it will “tombstone” your application. When that happens it won’t remember stuff like what you had typed into a text box. Here is another diagram I found that shows the extra bubble for tombstoned.

image

But how the heck do you test this? If the phone decides when it is going to tombstone an app instead of just leaving it dormant, how on earth do I write code to say “if the app was tombstoned go get the values the user entered and put them back in the text box again” and how do I test that if I don’t have a phone? Turns out they thought of that. If you go to the Solution Explorer windows, right click on your project and go to Properties.

ProjectProperties

When you get to the project properties choose Debug and select the checkbox that says Tombstone upon deactivation while debugging.

TombstoneInVisualStudio

Now if I use the Windows button to exit my application in the simulator it will tombstone my app so I can test my tombstoning logic in my application to make sure it will work in case a phone device does tombstone my app behind the scenes.

So let’s see what happens now when I run my application, and then use the Windows button to exit and the Back button to return to my application and sure enough, the name I had typed into the text box is gone!

NoSaveStateOkay so now I can see the problem users will have if I don’t do tombstoning. Users who leave my app to do something else on the phone don’t want to come back and lose everything they had typed in. I found a great big MSDN article on how to preserve and Restore Page State, I’ll try to break it down to the basic concepts here, but feel free to go read the article.

So after a little digging I discovered that the best place to remember what someone typed in is in the OnNavigatedFrom event handler of the page. This event fires when you leave the page in your application. To get to the code for your page so you can add the event handler you can right click on the background of the page where you see your screen and choose View code, or in Solution Explorer you can expand your page by clicking on the little arrow so you see the code-behind page listed in Solution Explorer. You can then double click on the code behind page to navigate to the code

imageNow I can add a OnNavigatedFrom event handler, the syntax is a little different in VB and C#. What I want to do is remember the value the user typed into my text box when I leave the page. After a little digging I found that you can use the State dictionary to remember the values. Basically you call the Add method of the State dictionary and tell it the value you want to store, and what you want to call the value stored so you can get it back later. Call the add method once for each value you want to remember. You do need a little error handling though in case the value is already stored, so I added a little logic that says if the value is already there, delete it and add it back with the new value. When I am done my code looks like this:

Protected Overrides Sub OnNavigatedFrom
(e As System.Windows.Navigation.NavigationEventArgs)
    MyBase.OnNavigatedFrom(e)

    If Me.State.ContainsKey("NameEntered") Then
        Me.State.Remove("NameEntered")
    End If

    Me.State.Add("NameEntered", TxtName.Text)

End Sub

Now I need to add code so that when they come back to the page it reads the value I saved and puts it back in the textbox again. I do this in a OnNavigatedTo event handler. Again I add a little bit of error handling because if someone enters the app for the very first time there won’t be a value stored in state yet, and I don’t want that to crash my application, so basically I say if you find a value go get it and put it in the text box. The code looks like this:

    Protected Overrides Sub OnNavigatedTo
(e As System.Windows.Navigation.NavigationEventArgs)
        MyBase.OnNavigatedTo(e)

        If Me.State.ContainsKey("NameEntered") Then
            TxtName.Text = Me.State("NameEntered")
        End If

    End Sub

Now to test it! Run the application, use Windows button to exit, back to return and Woo hoo! I have successfully told my phone application to remember the value even if it gets tombstoned. If you see a little ‘”resuming…” message then you know for sure your application was tombstoned, but depending on how long it takes to restore your application you may not see the message.

Now, the programmer in me has one issue with the code I just wrote. Most of the time, my application will not be tombstoned it will just be dormant. So I now have code that runs 100% of the time as you enter and leave the page, but really only needs to run some of the time. Not the best performing code! It turns out you can actually find out programmatically if your application was tombstoned and then you should only restore state IF it was tombstoned.

If you go to the application code page (go to solution explorer, expand the little arrow pointing to App.xaml, and you will see App.xaml.vb or App.xaml.cs, double click on that .vb or .cs file to get to the application code page). By the way there is a whole lab on how to do this tombstoning stuff you can download as well if you want.

image

If you scroll down through the code you will find a Application_Activated event this is where we can check to see if the application was dormant or tombstoned, because this event receives an argument called IsApplicationInstancePreserved which will be true if the app was dormant, and false if the app was tombstoned.  The problem I have though is that I need to be able to find this out in my OnNavigatedTo event handler on the page. There may be more clever ways to do this (open to suggestions from the peanut gallery here) but what I am going to do is create a class called Statemanager with a shared/Static property called restorestate that I can set in the Activated event and read in the OnNavigatedTo event.

    Private Sub Application_Activated
(ByVal sender As Object, ByVal e As ActivatedEventArgs)
        If e.IsApplicationInstancePreserved Then
            StateManager.RestoreState = False
        Else
            StateManager.RestoreState = True
        End If

    End Sub

Visual Studio Tip: I could create the class before I create the event,  but when I get the squiggly under the class name, i just hover the mouse over the little red line (or click on that line and then do CTRL + . on the keyboard, that’s a period by the way) and a little pop-up menu appears that offers to generate the class for me since it doesn’t exist. I choose Generate Class StateManager from the pop-up menu and voila Visual Studio makes the class for me. of course then it complains that the property RestoreState does not exist, so I use the same little trick, click on the line with the squiggly do my CTRL + . and pick Generate field for StateManager (yeah I could do a property here instead of a field, I am just being lazy, I know that in good OO design you always have properties, but this is just a hello world application right now). But I love this little feature in Visual Studio that generates classes, properties, and method stubs for me Smile.

image

I can now double click on my StateManager class to edit the code, or if you didn’t use the little tip above you could have created the StateManager class yourself by right-clicking the project HelloBonjour and choosing Add Class to create the class from scratch myself and added a shared/static field for RestoreState. Either way, when you are done Your class should look something like this:

Class StateManager

    Friend Shared RestoreState As Boolean

End Class

Now I can go back to my OnNavigatedTo event handler and specify to only load state if RestoreState is true.

    Protected Overrides Sub OnNavigatedTo
(e As System.Windows.Navigation.NavigationEventArgs)
        MyBase.OnNavigatedTo(e)

        If StateManager.RestoreState Then
            If Me.State.ContainsKey("NameEntered") Then
                TxtName.Text = Me.State("NameEntered")
            End If
        End If

    End Sub

That’s it that’s all and that’s definitely more than enough for this blog post, time to pat myself on the back for figuring out yet another step in the steps towards building a windows phone app. You know I am beginning to believe I can do this! The whole tombstoning thing always had me confused, I feel a lot better now that I have that piece figured out.

Yup time to do the Hello World App – My First phone app Part 2

If I can publish a phone app, anyone can, at least that’s my theory! So if you have ever thought about it, try it yourself as I blog. There are always roadbumps on the way. With the pressure of having you doing this with me I think I can do this. Last blog I managed to get the tools up and running. Today my goal is to get some code running.

As cliche as it is, I am going to build a Hello World app, if I am going to build a phone app, I need to make sure I know how to use the tools, that way when I start to get weird error messages on the screen, then I know it’s my code, and not because I don’t even know how to use the tool! By the way, this may look like a long blog, but that’s just because I have a lot of screenshots to help anyone who is new to Visual Studio.

If you don’t already have the tools installed you can check out Part 1 – Installing the Phone tools (the title doesn’t match but that’s what I did in the actual blog post)

Okay let’s go.

I have Visual Studio installed on my PC, you may have to launch Visual Studio Express for Phone, but once you are in the tool the steps should be nearly identical.

Step 1 – Launch Visual Studio 2010 (Start | All Programs | Visual Studio 2010 | Microsoft Visual Studio 2010)

Step 2 – Create a phone project (Okay I admit it, I like VB .NET better than C#, I can write C# but I have to think harder to do it, if I am going to embarrass myself by sharing my code with you, I might as well go all out and use VB.NET, all you C# aficionados can scoff if you wish, but I like it)

Choose File | New Project | Installed Templates (either pick Visual Basic or Visual C#) | Windows Phone Application

Sure there’s a bunch of other project types there, but I figure the first one will work for a Hello World application. I’ll have to figure out the difference between all those other ones later.

Now I get a window popping up asking which Windows Phone Platform I want to target for the application. I am going to choose 7.1, because 7.1 is the Mango release, I know there are some nice new features in that release and I want to be able to use them in my application. I also know that pretty much all Windows Phone users in Canada have the Mango update so I am not limiting who can use my application.

PickTargetPhonePlatform

Okay now I see a screen with a whole bunch of scary looking XAML. I just want to create a hello world app, so let’s hide that XAML stuff for now. There is a tiny double arrow you can click on to hide the XAML pane.

CollapseXAML

Now I just have a page in front of me which says MY APPLICATION, and page name.

Let’s start by changing the text “MY APPLICATION” to “HELLO BONJOUR APPLICATION”. If you click on the text that says My application it will select the TextBlock control that displays the text. That TextBlock control has properties that affect how it is displayed. When you select the TextBlock you can see the property window displayed in the bottom right hand corner.

TIP:  if you like you can click on that property window and drag it out and resize it so it is easier to see. If you close the property window, you can get it back by:

  • selecting a control and hitting the <F4> key
  • selecting View | Properties Window from the menu
  • right clicking the control and selecting Properties from the pop-up menu.

PropertyPanel

Go into the property window and change the Text Property to “Hello Bonjour Application”. The text on the screen should now show your new application title. I know from developing windows and web applications that you spend a lot of time editing properties, so good to get used to that right away.

image

Now let’s add a Button, a TextBox, and a TextBlock to the screen. In order to add controls to the screen I need to display the toolbox window. On the far left of your Visual Studio window you will see a little tab called toolbox. You will need to click on that so that you can see the toolbox and add controls by dragging them to your screen. Lucky for me, although I have never built a phone app, I have used Visual Studio so I can actually help you out there if you haven’t.

Toolbox

Once you can see the toolbox, drag a TextBox control, a Button Control and a TextBlock control to the screen and put them under the page name textblock. When you are done your screen should look something like this.

image

Tip: If you find it annoying the way you have to keep re-opening the toolbox, there is a little pushpin icon that allows you to pin it in place so it stays there all the time. The pushpin is a toggle, so if you want the toolbox to go away again you can just click on that pushpin icon again.

Toolboxpinning

When you add controls, it is always a good idea to rename them, having controls called Button1 and textBox1, textBox2 is not very easy to keep track of later. I use a prefix to remember the type of control (e.g. txt, btn, blk) and then a meaningful name of some sort for each control. Let’s rename our controls. Button – btnDisplayMessage, TextBox – txtName, textBlock – blkMessage. You will find that makes life easier when you start adding code as well. To rename a control, bring up the properties and click on the control name, then you can type in a new name.

image

Let’s also change a couple of properties to change how they are displayed.

  • BtnDisplayMessage set Content = Click Here
  • TxtName set Text to blank
  • BlkMessage set Text to blank

Now we need to add some code, what we’ll do is have the user type their name into the text box, then click on the button. When you click on the button we’ll display a message saying Hello <insert name here> on the screen.

Since we want our code to run when you click on the button, we can add an event handler to the button by double clicking on the button. That automatically creates a click event handler where you can write code that will execute when you click on the button. We are going to write code that says get the content of the Text property of the TxtName field (that will contain whatever the user types in) and put that value into the text property of our textblock concatenated to a string that says “Hello/Bonjour”  so basically you need to add the following code to your event handler.

BlkMessage.Text = “Hello\Bonjour ” & TxtName.Text

When you are done it should something like this (I reformatted a little bit to make it more readable)

    Private Sub BtnDisplayMessage_Click(sender As System.Object,
                                        e As System.Windows.RoutedEventArgs
                                        ) Handles BtnDisplayMessage.Click
        BlkMessage.Text = "Hello\Bonjour " & TxtName.Text

    End Sub

You now have two windows open, one is the designer window (MainPage.xaml) where you can add more controls and change properties. The other is the code window (MainPage.xaml.vb) where you can add and modify code. You can move back and forth freely between the windows by clicking on the tabs.

image

We’re done! Now we can test our application!

You can launch the application a couple of ways, you can click on the debug button in the toolbar. you can choose Debug | Start Debugging from the menu, or you can right click on the project name in the Solution Explorer window and choose Debug | Start new instance.

StartDebuggingZoomin

Now you wait a few little while for the emulator to load, dum de dum, (it takes a little time the first time you launch it) and then the application appears in the emulator.

PhoneEmulator

If you have a touch screen you can actually touch the textbox and the on screen keypad will appear in the emulator. If you don’t have a touchscreen, you can use your mouse to click inside the textbox and the onscreen keyboard will appear. This is where I go a little batty. You have to use the on screen keyboard by clicking the keys with your mouse, or tapping it with your fingers. You can’t use your desktop or laptop keyboard. Maybe they did that on purpose to remind us what it will be like for a phone user who doesn’t have a real keyboard Smile

EmulatorKeyboard

Now you can click on the button and ha! I just realized, when I screwed up my project and had to restart that I forgot to change the label on the button! So in the screen shots you will see that the button label is not set to “click here”!  Man, I should really go fix that shouldn’t I…I am not going to go recreate all the screen shots though, forgive me! Hey i guess I get to show you how to go back to your code,

tip: DO NOT click on the ‘X’ beside the emulator. That works, but it unloads the emulator and then you have to wait for it to reload again. Instead go back to Visual Studio and choose Debug | Stop Debugging from the menu or click on the Stop debugging button in the toolbar. Then when you start debugging again it will be faster.

StopDebugging

Okay go back, select the button, <F4> to bring up properties, Change Content to “Click Here”. Now run it again to test <Start Debugging> Ha! fixed it! Now Type “S u s a n” into the text box, click on the “Click Here” button and cool! the textblock now says Hello/Bonjour Susan. I love it!

HelloSusan

So now that I have a very very simple application that I can run in the emulator I can play around a bit, start adding more controls to see what they look like, figure out how to line up the fields so they look nicer, play around with font sizes, explore the emulator buttons. That is why I like Hello World apps. They get me just far enough that I can start to explore. Next blog…I’m going to figure out how to put the application on my actual Windows Phone! But I got my Hello World finished, time to go celebrate with chocolate (I hope my kids have some Halloween candy left)