DiscoverWindows Phone 8.1 Development for Absolute Beginners (Audio) - Channel 9
Windows Phone 8.1 Development for Absolute Beginners (Audio) - Channel 9
Claim Ownership

Windows Phone 8.1 Development for Absolute Beginners (Audio) - Channel 9

Author: Microsoft

Subscribed: 0Played: 2
Share

Description

Bob Tabor (LearnVisualStudio.NET) delivers this 9+ hour series on Windows Phone 8.1 Development for Absolute Beginners! This series covers: Windows Phone UI with XAML layout and eventsNavigation modelApplication lifecycleWorking with the Windows Phone EmulatorUnderstanding MVVM (Model-View-ViewModel)HTML apps in the WebViewStorageMapsAnimationsMedia (Video/Audio with the MediaElement control)You'll learn by doing as you build five apps, covering a range of scenarios, from media playback to hosted HTML to accessing geolocation data and mapping to extending your Windows Phone app to become a universal Windows / Windows Phone app. So jump on in and learn how to build the next great Windows Phone apps! For more Absolute Beginner series visit: https://channel9.msdn.com/posts/Beginner Source Code: http://aka.ms/absolutebeginnerwp81 PDF Version: http://aka.ms/AbsoluteBeginnerWP81PDF
30 Episodes
Reverse
Let me congratulate you on making it all the way through this series. Think about how far you've come in such a short amount of time! It takes a high degree of commitment to work your way through 10 hours of content, but you did it, and you definitely have what it takes to see a project through to the end. And so, I'm confident that you can build the next great app. I would encourage you to take your time, aim high, and test, test, test your app to make sure your app is polished and ready for others to use it.I love to hear from people who have watched these series I've created and who have built an app and submitted it to the app store.   That's probably the best feedback that we can get ... that this series helped you in some small way and that you actually built an app and released it into the Windows Store. If that describes you, and if you need a beta tester, by all means please send me a tweet @bobtabor or write me at bob@learnvisualstudio.net.Before I wrap this up, I want to thank Larry Lieberman and Matthias Shapiro who sponsored and edited this series. If you like this content, please let them know ... there's a feedback link on the footer, or just leave a comment below this video.Also, I want to thank Channel9 for their ongoing support of my work, including Golnaz Alibeigi, and those I've worked with in the past who have taught me so much, like Clint Rutkas who got a major promotion to the Halo team and of course, Dan Fernandez who I've been working with for over 10 years and who has keep me connected with Microsoft. It is much appreciated.Allow me to make one last plug for my website, www.LearnVisualStudio.NET. I try to share everything I know with my clients about C#, Visual Studio, Windows and web development, data access, architecture and more.Finally, I honestly wish you the best in your career and in life. Thank you.
Download the source code for this lesson at http://absolutebeginner.codeplex.com/In this final lesson, we’ll build the MapNotes app.  It is a GPS-aware note app that records not just the note you take but also where you took that note and displays it on a map.  Then you’ll be able to read that note and see a map of where you took the note.  You can then delete the note or continue on from there.  In addition to working with Phone storage, the Map control and Geolocation, I’ll also add some nice little touches like truncating long note titles replacing the remainder of the title with an ellipsis and adding a MessageDialog to ask the user to confirm an operation:To begin, I’ll open the New Project dialog, and (1) create a new Blank App project template (2) called MapNotes, then (3) click the OK button:First, I’ll add a DataModel folder:Then will add a new file to that folder.  In the Add New Item dialog, I’ll add (1) a class (2) called DataSource.cs, then (3) I’ll click the Add button:In the new DataSource.cs file, I’ll create a model called MapNote, adding a number of properties that represent the note, where the note was created, etc.:The DataSource class will be our primary focus.  You’ll notice how similar it is to other DataSource classes we created in the past.  In fact, as I was developing this, I merely copied code and renamed the data class to MapNote (since that is the type of data we’re working with in this app).  While I don’t advocate copy and paste always, as a means of templating some common functionality, it can be useful.I’ll start by creating a private ObservableCollection<MapNote> that the remainder of the methods in the DataSource class will manage… adding new items, deleting items, saving and retrieving from Phone storage, etc.:We’ll begin by providing access to the _mapNotes through the GetMapNotes() method.  Again, note the templated nature of this method from what we’ve used earlier.  GetMapNotes() called a helper method called ensureDataLoaded().  The ensureDataLoaded() method checks the count of items in the collection, and if it is empty will call the getMapNoteDataAsync() which has the responsibility of hydrating the object graph of MapNotes from Phone storage into memory.We’ve talked about methods similar to getMapNoteDataAsync() in the past.  In a nut shell, we’ll use a DataContractJsonSerializer to open a file from the Phone’s LocalFolder storage and de-serialize the file’s contents into an in-memory collection of MapNotes.We’ll need to create a constant with the fileName since we’ll be using it to both save and retrieve data on disk.We want to allow the user to create new MapNote objects and save them to the Phone’s storage.  The AddMapNote() method will add a new MapNote to the private  ObservableCollection<MapNote>, then persist that to storage by calling saveMapNoteDataAsync().  The saveMapNoteDataAsync() is the corollary to getMapNoteDataAsync() … it, too, uses a DataContractJsonSerializer to save a file to the Phone’s Local Folder.Finally, we want to allow a user to delete a note.  We’ll call Remove() on the collection of MapNotes, then again, call saveMapNotDataAsync() to make sure that change is saved to the Phone’s storage:We want to make our DataSource class available throughout all pages in our app, so I decided to create an instance of DataSource as a public static field on the App claass.  In the App’s constructor, I create an instance of DataSource and set it to the DataModel field:Now, we’re ready to create a page that will allow a user to add a new note or look at an existing note.  While looking at an existing note, we’ll allow the user to delete the note as well.  We’ll use a single page for both purposes, changing out the names of the buttons and their operation depending on the current state of the current MapNote.I’ll add a new item, a new Blank Page called AddMapNote.xaml:Before I begin to lay out the controls on the new AddMapNote.xaml page, I need a way to navigate from the MainPage.xaml to the AddMapNote.xaml page.  There will be two ways to do this … the first will be to click a button in the MainPage.xaml’s CommandBar to add a new note.  The second way will be to tap an existing note’s title / entry in the list of notes on that page to view (and potentially delete) that note.First, I want to add a CommandBar and CommandBarButton.  I’ll put my mouse cursor in the Page definition, and in the Properties window I’ll click the New button next to BottomAppBar:That action will create a Page.BottomAppBar and a CommandBar.  Now, I’ll put my mouse cursor in the CommandBar and then select the ellipsis button next to PrimaryCommandButton:And the PrimaryCommandButton editor dialog appears.  I’ll (1) click the Add button to add a new AppBarButton, (2) select the newly added button in the Items list box on the left, then (3) make sure to change the Icon to type SymbolIcon, and (4) select the Map symbol from the dropdown list:(1) I’ll scroll down to the Label property and set that to “Add Note”, then (2) click the OK button:Finally, in the XAML editor, I want to add a click event handler for the new button, so I’ll add a Click=”AppBarButton_Click” event handler method.I’ll use the F12 technique to create the method stub in the MainPage.xaml.cs file.  Here, I’ll want to set the DataContext for the page to the collection of MapNotes in the OnNavigatedTo() method (like we’ve demonstrated before).  I’ll also Frame.Navigate() to AddMapNote.xaml when the user clicks the AppBarButton:Back on the MainPage.xaml, I’ll lay out the main area of the page by (1) surrounding the Grid with a ScrollViewer so that we can view a long list of items, (2) I’ll add two RowDefinition objects to create an area for the app title and for the list of items, (3) I’ll add a TextBlock with the title of the app into that first RowDefinition with the style set to the built-in HeaderTextBlockStyle:I’ll add a ListView control into the second RowDefinition, binding its ItemsSource to the Page’s DataContext, and setting properties to ensure that a given list item can be tapped, not selected.  This involves setting the SelectionMode to none, the IsItemClickEnabled to true, and creating an event handler for the ItemClick event.  Furthermore, I’ll add the ItemTemplate and DataTemplate so that we can begin fleshing those out in the next step:Each list view item will be comprised of two TextBlocks … one bound to the Title of the note, the other to the Note property of the MapNote:Now, we’ll move on to the AddMapNote.xaml page.  Here, I’ll add four row definitions and set the margins on the Grid:     <Grid Margin="10,0,10,0">        <Grid.RowDefinitions>            <RowDefinition Height="40" />            <RowDefinition Height="Auto" />            <RowDefinition Height="*" />            <RowDefinition Height="Auto" />        </Grid.RowDefinitions>    </Grid>I’ll leave the top row empty in order to give the app some vertical spacing.  I suppose I could add my app’s title or other branding elements there as well.  In the second row, I’ll add a StackPanel containing the Title and Note TextBoxes:        <StackPanel Grid.Row="1">            <TextBlock Text="Title:" />            <TextBox x:Name="titleTextBox" TextWrapping="Wrap" />            <TextBlock Text="Note:"/>            <TextBox x:Name="noteTextBox" TextWrapping="Wrap" Height="125" />        </StackPanel>Next, I’ll drag-and-drop a Map Control to the desginer which adds the MapControl and its namespace to the Page.  I’ll clean out the extraneous properties and set it to the third row:        <Maps:MapControl x:Name="MyMap" Grid.Row="2" />In the fourth row, I’ll add two buttons in a StackPanel along with event handler methods for their Click events:        <StackPanel Orientation="Horizontal" Grid.Row="3">            <Button x:Name="addButton" Content="Add" Click="addButton_Click" Margin="0,0,10,0" />            <Button x:Name="cancelButton" Content="Cancel" Click="cancelButton_Click" />        </StackPanel>When I’m finished, the preview looks like this:While the name of the page is AddMapNote.xaml, I intend to use it for two scenarios: adding a MapNote and viewing / deleting a MapNote.  To accomplish this I’ll need to often determine the current scenario I’m in … am I adding or viewing / deleting?  We see how that affects the OnNavigatedTo() event handler … if I’m adding a new MapNote, then I’ll want to determine the current location of the Phone.  However, if I’m viewing / deleting a MapNote, I’ll want to retrieve the location from the existing MapNote and set the Map Control to display it on the Page.I’ll start with the “Add” scenario.  I’ll use the Geolocator object to determine the current position:I still have a lot of work to do here, such as set the Map Control to the current Geopoint, however this is a good start.The note reminds me I need to add a Capability for Location.  I’ll open the Package.appxmanifest file, go to the Capabilities page, and click the check box next to Location:Back in the AddMapNote.xaml, I’ll handle the “Add” scenario for the addButton_Click() event handler method.  I’ll need to resolve some namespaces, and I’ll need to fix a problem with the names of one of my properties which I misspelled (will do that in the next step).  Here, we’ll create a new instance of the MapNote class, set its properties including the Latitude and Longitude, then call the App.DataModel.AddMapNote() passing in the new instance of MapNote.  Finally, I’ll navigate back to the MainPage.xaml:As I said a moment ago, I realize I forgot the letter ‘d’ on the property named Created.  I’ll fix that back in the MapNote class:Back in the AppNoteNote.xaml.cs, I want to think about the OnNavigatedTo() event handler again.  This time, I want to think about how I’ll handle both the “add” and “view / delete” scenarios.  I’ll use the NavigationEventArgs input parameter that contains the input parameter from the previous page.  If the parameter is empty (null), that wil
Download the source code for this lesson at http://absolutebeginner.codeplex.com/In this lesson we're going to talk about animation.  To be clear, what we really do is change properties of the controls on our pages over time.  This could take the form of moving an element from one place to another, changing its size from small to large, or changing the opacity of a control.   In this lesson we're going to keep it very simple but you can combine many different effects together to create a complex sequence.  I originally hoped to incorporate animation into the last project in this series which we’ll begin in the next video.  However, as it turned out, I didn't really need animation.  Still, I wanted to cover this topic, at least the very basics of it.  If this is something you want to use in your apps, you'll want to learn more about Microsoft Blend which is a tool similar to Visual Studio that has a more powerful set of animation tools.  However, this less should get you familiar with the concept of animation at a high level.We'll talk about animation using both XAML and C#.  If you watched the Windows Phone 8 for Absolute Beginner series, which I created about a year ago with Clint Rutkas, we used a simple animation to animate the images as we were pulling them down from Flikr.  In that series I discussed why you might need to take a pure C# approach versus a pure XAML approach towards animating properties of controls.  In this lesson I'll demonstrate both approaches and then let you choose which one you want to use for your specific purpose.We’ll start by opening the New Project dialog and (1) creating a new Black App project template called (2) WorkingWithAnimation, then (3) clicking the OK button.On MainPage.xaml I'll replace the Grid with a StackPanel.  We’ll begin by animating an image’s opacity to give it the appearance of fading the image in and out.  To follow along, you’ll need to add the two images from the Assets folder of the Lesson28.zip file into your project’s Assets folder.Inside the StackPanel I’ll add a Button and an Image.  I’ll set the source of the Image control to the snowy.png file which we copied into the Assets folder.  I’ll also set the Opacity to 0 meaning we want to begin with the image being completely transparent.My objective is to move the opacity property from 0.0 (completely transparent) to 1.0 (completely opaque) over two seconds.  We'll get to that in just a moment.  When the user clicks a button we’ll kick off that animation.  Animations are defined inside of Storyboards.  A Storyboard is simply a collection of animations that all happen at the same time.  As a developer you decide which events trigger the Storyboard to play all of its animations.As I said earlier, you can animate many properties of controls including the size, the opacity, the color of the control.  There are different animation objects that know how to work with colors, numbers, etc.Let's create a Storyboard.  We’ll create a Resources section of the StackPanel.  In other words, here are the resources that'll be available to all the children of the StackPanel.  Inside of the StackPanel.Resources, we’ll create two Storyboards.  The first I’ll call “ShowStoryboard” and the second I’ll call “HideStoryboard”.  Inside of the “ShowStoryboard” I’ll set the target control, the target property of the target control, the original value and the target value, and finally the duration of the animation:In this example, the ShowStorydoard has one animation defined, a double animation (”double” as in the double data type, with numeric values after the decimal point) which specializes in moving a numeric-based property from one number to another.  When it is triggered, it will animate the animatedImage control’s Opacity property from 0.0 to 1.0 over the course of two seconds.  In our simple example, we’ll trigger the ShowStoryboard’s animations by calling the Begin() method in response to some event, such as the animateButton_Click event:When we run the app, we can trigger the image to slowly appear by clicking the “Animate” button:We can also cause the image to disappear slowly using a second Storyboard with a single DoubleAnimation object that does the opposite of the first: changing the Opacity property from 1.0 to 0.0 over the course of two seconds:Now we’ll add some logic to toggle the effect of showing and hiding the image by checking the current state of the animatedImage’s Opacity property and calling the appropriate storyboard’s Begin() method:So, we can define XAML Storyboards that contain DoubleAnimation objects then use C# to trigger those storyboard at key moments in the app.We can take a second tact.  This second tact is helpful when we want to programmatically add new controls and animate them as we add them.  In this case, I’ll re-work the Image control’s XAML definition to include an ImageOpened event handler method called animatedImage_ImageOpened:The animatedImage_ImageOpened() method will fire whenever the Image control’s image is changed via its Source property.We’ll also re-work the animateButton_Click() event handler method to dynamically load a different image into our Image control (the Assets/sunny.png file):Notice how we created the BitmapImage control … by providing a new Uri object set to a location as designated by a special prefix: ms-appx:///Similar to how we can use http:// to indicate a URL, we can use the ms-appx:/// to denote a location that is relative to the current deployment package’s root.  Obviously in this case we’re expecting our sunny.png file to be deployed to the Assets folder of the compiled package.Inside the animatedImage_ImageOpened() event we have an opportunity to intercept the display of the image in the control with code we write.  In this case, we’ll intercept to create a new Storyboard object and child DoubleAnimation on the fly with the same definition as the ones we created earlier, except using just C# instead of XAML:Now, when we load a new image into the Image control, the Image control will first create a Storyboard with a DoubleAnimation that animates the Opacity property, then kicks off the Storyboard:As I said at the outset, these are two very simple examples of animation.  However, that should get you at least some basic understanding of what animations are, how they're associated with storyboards,  how to kickoff a storyboard with the storyboard’s Begin() method.
Download the source code for this lesson at http://absolutebeginner.codeplex.com/In this lesson, we're going to talk about the map control and talk about the GPS sensor inside of the device. Besides the specifics of the GPS sensor, the more general principles of working with the Phone's sensors apply here as well. So, while we are examining a specific capability, you can apply the general knowledge to all the capabilities of the Phone and how to work with them. The Phone's API always supplies classes and methods representing the particular sensor and its functionality you want to work with. In the case of the Phone's location features, we'll be able to get the latitude and the longitude in a GeoPosition object that we can then work with. What can we do with the location, the GeoPosition object? For one thing, it works well with the Map Control. We can set current position of the Map Control to a specific location (GeoPosition) or retrieve the current location from the Map control and ask "Where in the world are you displaying?" We can zoom into the map, zoom out of the map, and things of that nature.We’ll start by opening the New Project dialog (1) creating a new Blank App project, (2) renaming it to LocationAndMaps, and (3) clicking the OK button. The easiest way to get started working with the Map Control is to use the Toolbox. Usually, I advocate directly typing in the XAML, however as we’ll see in a moment, the Map Control requires a bit of extra work that the drag-and-drop action will take care of for us: Here I resize the Map Control on the design surface so that we can see the message that it only renders when the app is running: In addition to the XAML that was generated inside of the Grid, notice the namespace that was added to the Page’s namespace declarations:This is one reason why I prefer to drag-and-drop to the design surface when working with the MapControl.Next, I’ll edit the layout of the Grid and the Map.  Ideally, it takes up the first row set to *:And when I run the app, notice that the Map is simply set to North America (at least, since I am in North America.  I’m not sure what would happen if you tried this from other parts of the world).The first thing I want to accomplish is the set the MapControl, by default, to a specific location.  I’ll choose an out door mall near the Microsoft campus in Redmond, Washington, as the location of the Phone using the Emulator’s Additional Tools dialog:Back in my project, in the MainPage.xaml.cs I’ll modify the OnNavigatedTo() event handler method to work with the Geolocator.  This object is your interface to the GPS / location features of the Phone.  Since we’re running in emulation, I would expect to retrieve the location in Redmond, Washington that I set.  Once I have the Geolocator retrieving the location, I attempt to set the MapControl’s view to that location:A few things I want to point out.  Notice that we’re setting the DesiredAccuracyInMeters to 50.  Due to technological features of the phone and the GPS system, it is not always possible to get an exact location of the phone.  It will try different techniques to get as close as possible.  For example, it will not only use the GPS satellite, but it may also use wifi signals and cell tower signals to attempt to triangulate the location. Depending on how accurate you need this to be and what the resources are near the device at the given time that you're attempting to retrieve the position, it could take longer because it has to account for all of these possibilities, wifi signals that are nearby, cell towers, GPS in order to find the location.   Honestly, I don't understand how all that works.  However, at some point, we're going to obtain a Geoposition object providing us with a Coordinate.  A Coordinate is made up of positioning information.  The most important for our purposes is a Point.  A Point is simply just a combination of the latitude and longitude and we'll use that information to try and set the view for the mapWhenever you see that key word “try” in a method name, that means it's going to return back to you a true or false: true if the operation was successful, false if it wasn’t.  For our purposes in this pithy example, we’ll ignore the return value.  In other words, if TrySetViewAsync() fails, then it just fails and it will be quiet about it. In the TrySetViewAsync() we're passing a Point which is a Geocoordinate position which is basically what we get from position.Coordinate.  We also pass in the zoom level.  A setting of zero would zoom to see all of North and South America, and a zoom level of 20 would be where we can see in our own back yards.  It is a double data type so I add the D next to it just is a way of making the value 18 into a double literal. Before we run the app, we’ll need to add the Location capability to our app.  Open the package.appxmanifest, go to the (1) Capabilities tab, and (2) select the Location capability:Now we should be able to run the application and then see our map control some where near this Redmond Town Center in Redmond, Washington.  Unfortunately, I don’t know the streets of Redmond, Washington well enough to verify how far the location we’re given in the MapControl is to the location we set in the Emulator’s Location tab, but I’ll assume it is close.Next, I’ll implement two Button controls to set and retrieve the current position of the map.  I’ll add two more row definitions and setting the height of each to 50:As a means of further exercising the Geolocation and Map Control, we'll write out the current position of the Map Control to a TextBlock and I’ll programmatically set the position of the Map Control.  Two Button controls will trigger these actions.  So, I’ll add the following XAML inside the Grid:        <StackPanel Orientation="Horizontal" Grid.Row="1">            <Button Name="getPositionButton"                     Content="Get Position"                     Click="getPositionButton_Click"                     Margin="0,0,20,0" />            <Button Name="setPositionButton"                     Content="Set Position"                     Click="setPositionButton_Click"                     Margin="0,0,20,0" />        </StackPanel>        <TextBlock Name="positionTextBlock"                    Grid.Row="2"                   FontSize="22" />I’ll create method stubs for the getPositionButton_Click and setPositionButton_Click by putting my mouse cursor on their names in the XAML and pressing F12.In each of those two methods, I’ll add the following code:        private void getPositionButton_Click(object sender, RoutedEventArgs e)        {          positionTextBlock.Text = String.Format("{0}, {1}",              MyMap.Center.Position.Latitude,              MyMap.Center.Position.Longitude);        }        private async void setPositionButton_Click(object sender, RoutedEventArgs e)        {          var myPosition = new Windows.Devices.Geolocation.BasicGeoposition();          myPosition.Latitude = 41.7446;          myPosition.Longitude = -087.7915;          var myPoint = new Windows.Devices.Geolocation.Geopoint(myPosition);          if (await MyMap.TrySetViewAsync(myPoint, 10D))          {            // Haven't really thought that through!          }        }Hopefully all of this looks familiar, or at least, straight forward.  In the getPositionButton_Click I’m merely retrieving the Map’s Center position, grabbing the latitude and logitude and printing to a TextBlock.  This demonstrates how to retrieve all or part of the current location OF THE MAP CONTROL which can be useful when building Map-centric apps.In the setPositionButton_Click, I’m hard-coding the position of the Map.  Again, I’m using TrySetViewAsync() to do the heavy lifting.  However, this time I’m creating a BasicGeoposition object to contain the latitude and longitude and then creating a Geopoint using the BasicGeoposition as a constructor argument.  When I run the app, I can retrieving the current position into a TextBlock by clicking the “Get Position” button …… and can set the position of the Map to a specific location near where I grew up by clicking the “Set Position” button:Next, I’ll add a Slider control to perform zooming.  I’ll add the following XAML to the Grid:        <Slider Name="mySlider"            Maximum="20"                 Minimum="10"                ValueChanged="Slider_ValueChanged"                 Grid.Row="3"                />And will use the F12 shortcut to create the Slider_ValueChanged event handler method, to which I add the following code:        private void Slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)        {          if (MyMap != null)            MyMap.ZoomLevel = e.NewValue;        }Simply put, the slider will allow me to move from 10 to 20 (extreme close up).  Finally, I’ll initiate the Slider’s value at start up by setting its value to the Map Control’s current ZoomLevel in the OnNavigatedTo event handler method:Now, when I run the app, I can adjust the zoom level:I can reset the position using the “Set Position” button, and can zoom in dramatically:Finally, if you want to build apps that include the Map Control, you’ll need to provide a MapServiceToken.  You’ve see the warning message each during run time.  You can obtain a MapServiceToken from the Windows Phone Dev Center after you register your app (which we do not cover in this series).  You would set it like so:
Download the source code for this lesson at http://absolutebeginner.codeplex.com/In this exercise we’ll build a project that combines many of the things we talked about previously into a single example.  The Daily Rituals project is essentially it's a goal-tracking app.  The idea is, for 30 days, you'll track your progress against all the goals you've created.  For example, I'll create a new ritual or goal for myself.  I’ll click the + Add icon in the Command Bar …  Which allows me to add a new Ritual.  I’ll create dummy data for this demo, the Goal Name “Ritual 1” and the Goal Description: “Description of my new ritual”, and I will click the Add button …I’ll return to the main screen where I can see a list of rituals.  (I’ve added a second one in the screen shot, below):I can click the “I Did This Today” button which will keep track of the days I completed this goal and it will show progress on a Progress Control below the Ritual.  The progress bar will fill up over 30 days of establishing these daily rituals.I’ll begin by (1) creating a new Blank App project (2) called Daily Rituals.  (3) I’ll click the OK button on the New Project dialog to create the project.First, I’ll create a new folder called DataSource:Then right-click to Add > New Item … in that folder.In the Add New Item dialog, (1) I’ll add a Class (2) named DataSource.cs then (3) click the Add button:First, I’ll create a simple Ritual class using the prop code snippet to create the auto-implemented properties.  I’ll also add the proper using statement for the ObservableCollection<T> using the Control + [dot] keyboard shortcut.Second, I’ll flesh out the DataSource class adding a private field of type ObservableCollection<Ritual> called _rituals.  I’ll create a new instance of ObservableCollection<Ritual> in the constructor.  As you may anticipate, the rest of the DataSource class will define methods that operate on this private field.We’ll follow the pattern we’ve seen several times before now, creating a helper method called ensureDataLoaded() that will determine whether or not the _rituals collection contains instances of Ritual.  If not, then we’ll call the (yet to be implemented) getRitualDataAsync() method.We delegate the responsibility of retrieving data from a serialized file back into an object graph stored in the _rituals collection to the getRitualDataAsync() method.  We’ve seen this code before when working with serialized types that we need to “re-hydrate” back into an object graph.  Most of the heavy lifting is performed by the DataContractJsonSerializer and the ApplicationData.Current.LocalFolder.OpenStreamForReadAsync() method.There are several things we’ll have to fix with this code, including the creation of a constant for the fileName which I’ll define near the top of the DataSource class:… and I’ll also need to add various using statements to satisfy all of the class references:Next, I’ll implement the corollary to the getRitualDataAsync(), the saveRitualDataAsync() method which will be delegated the responsibility of persisting / “de-hydrating” the object graph stored in the _rituals field to disk.  Here again, most of the heavy lifting is performed by the DataContractJsonSerializer and the Application.Current.LocalFolder.OpenStreamForWriteAsync() method.We will want to allow one of our pages to add new Rituals to the _rituals collection.  Therefore, we’ll implement a public method that will do that:Furthermore, we’ll want to retrieve the _rituals collection:We have enough of the data model in place.  Next we can focus on the AddRitual.xaml page.  I’ll right-click the project name and select Add > New Item … to display the Add New Item dialog.  I’ll (1) select a Blank Page, (2) name it AddRitual.xaml, and (3) click the Add button:Before we begin work on the new page, we’ll need to be able to reference the DataSource class from the entire project.  To do so, (1) in the App.xaml.cs, (2) I’ll create a public static field called DataModel (3) which will necessitate the need to add a using statement to the DataModel namespace.In the App() class’ constructor, I’ll create a new instance of DataSource().Now, that I have a way to get at the DataModel, I’ll wire up the data context for the MainPage.xaml.  Up to now, we’ve done this by creating an instance of the DataSource class and holding a reference to it in a public read only property that we bind to declaratively.  However, this time I decided to do something different.  Here I’m calling App.DataModel.GetRituals() to get an ObservableCollection<Ritual> and set the DataContext property of the page.  Using this technique, there’s no additional work to be done in XAML. In the MainPage.xaml, I add RowDefinitions, then the title TextBlocks:Below that, I add an inner Grid containing an ItemsControl.  This will give the Grid the binding behavior of a ListView.  Notice that the ItemTemplate has a blue-squiggly line beneath it … that’s because we haven’t created the ItemTemplate yet:Next, we’ll add the ItemTemplate called dataTemplate.  We implement it as a child to the Grid in the Grid’s Resources property.  It consists of a StackPanel that arranged two TextBlocks vertically.  The TextBlocks are bound to the Name and Description of a given Ritual object:We’ll add a Button control to the DataTemplate.  We’ll utilize the Button later, but for now it’s just for layout purposes:In order to add a new Ritual, we’ll need a CommandBar with a Primary Command Button.  To begin, put your mouse cursor in the Page element (top or bottom) and in the Properties window, select the New button next to BottomAppBar:This will create a CommandBar object as a child to the Page’s BottomAppBar property:Put your mouse cursor in the CommandBar element and in the Properties pane click the ellipsis button next to the PrimaryCommands property:This will display an editor allowing you to add app bar buttons.  Click the Add button to create your first app bar button:The Properties pane on the right allows you to modify properties of the selected app bar button on the left.  Here we’ll change the label to: Add Ritual …… and the Icon to (1) an Icon (2) set to the + Add symbol:To close the editor dialog, click the OK button at the bottom.  This will have created an AppBarButton element.  We’ll add a Name and Click attribute like so:<AppBarButton Icon="Add" Label="Add Ritual" Name="AddRitual" Click="AddRitual_Click"/>Put your mouse cursor in the AddRitual_Click event handler name and select the F12 keyboard key to create a method stub.  When a user clicks the Add button in the command bar, we want to navigate to our new AddRitual.xaml page, so we’ll add the following code:        private void AddRitual_Click(object sender, RoutedEventArgs e)        {          Frame.Navigate(typeof(AddRitual));        }Next, in the AddRitual.xaml page, I’ll paste in the following XAML inside of the Grid element:        <TextBlock HorizontalAlignment="Left"                    Margin="34,161,0,0"                    TextWrapping="Wrap"                    Text="Goal Description:"                    VerticalAlignment="Top"/>                <TextBox x:Name="goalDescriptionTextBox"                  HorizontalAlignment="Left"                  Margin="34,170,0,0"                  TextWrapping="Wrap"                  VerticalAlignment="Top"                  Height="125"                  Width="332"/>                <TextBox x:Name="goalNameTextBox"                  HorizontalAlignment="Left"                  Margin="34,98,0,0"                  TextWrapping="Wrap"                  VerticalAlignment="Top"                  Width="332"/>                <TextBlock HorizontalAlignment="Left"                    Margin="34,89,0,0"                    TextWrapping="Wrap"                    Text="Goal Name:"                    VerticalAlignment="Top"/>                <Button x:Name="addButton"                 Content="Add"                 HorizontalAlignment="Left"                 Margin="34,322,0,0"                 VerticalAlignment="Top"                 Click="addButton_Click" />Which creates the following preview:Next, we’ll need to write code to handle the click event of the Add button.  We’ll want to (a) add the new Ritual to the collection of rituals in memory, and save it to the Phone’s storage, then (b) navigate back to the MainPage.xaml.  Put your mouse cursor on the addButton_Click event handler name and press the F12 key on your keyboard to create the method stub.  I’ll add the following two lines of code to the method:Now when I run the app, I can click the Add button in the command bar:… I can enter a Goal Name and Goal Description, then click the Add button:And when I return to the MainPage.xaml, I should be able to see the ritual I just added.To ensure that we’re saving the data to the Phone’s local storage, I’ll go to Visual Studio while the app is running in the emulator and select the drop down list of Lifecycle Events and choose “Suspend and shutdown”:When I re-start the app, the new ritual should still be present.Next, we’ll want to wire up  the “I Did This Today” button so that, when a user clicks that button, it will record today’s date for the associated Ritual.To begin, I’ll add a new Command folder:Then I’ll add a new class.  In the Add New Item dialog, (1) select Class, (2) rename to CompletedButtonClick, then (3) select the Add button:In the new CompletedButtonClick class, you’ll make it implement the ICommand interface like we learned in a previous lesson.  To accomplish this, first you’ll need to add a using statement using the Control + [dot] technique, then selecting the first option from the Intellisense menu:Then you’ll need to use the Control + [dot] technique a second time to display the Intellisense option to “Implement interface ‘ICommand’”.Once you’ve selected this, the CanExecuteChanged event, as well as the CanExecute() and Execute() methods will be stubbed out for you:Before we develop our own implementation of the Execute(
 Download the source code for this lesson at http://absolutebeginner.codeplex.com/The last piece of the puzzle we’ll need before building our next complete exercise app is to understand Value Converters.  In short, sometimes you want to use data in your View Model that is not in the correct format or must be in some way modified before you can bind to it.  A Value Converter allows you to perform a conversion on the data to format the data, change the value of the data, perform calculations on the data and more.In fact, in this lesson, I’ll demonstrate how diverse your value converters can be.I’ve created a “Before” folder in Lesson25.zip.  Please make sure you download this and unzip it to a directory called BindingWithValueConverters.  Here I have the beginnings of a weather app.  In this example, I’m randomly generating weather, however in a real app you would obviously be pulling weather from an online weather service.Notice the structure of the classes that will form the data model.  First, there is a DayForecast defined as so:public class DayForecast{  public DateTime Date { get; set; }  public Weather Weather { get; set; }  public ObservableCollection<TimeForecast> HourlyForecast { get; set; }}For a given day (the Date property) the Weather property will indicate the defining attribute of the day (whether sunny, cloudy, rainy or snowy … I’ve reduced the number of options for simplicity’s sake).  I’ve used an enum called Weather to denote the various values of Weather.  Finally, the HourlyForecast property is made up of an ObservableCollection<TimeForecast> … precisely 24 TimeForecast objects, to be exact, one for each hour of the day from 0 (midnight) to 11pm (hour 23) as indicated by the Hour property.  TimeForecast is defined as:public class TimeForecast{  public int Hour { get; set; }  public int Temperature { get; set; }}How will we create data for the Temperature of each TimeForecast object?  I’ve created a FiveDayForecast class which has a single method, GetForecast().  Its job is to deliver an ObservableCollection<DayForecast> to the MainPage.xaml.  This class also has a helper method called generateRAndomTimeForecast that creates 24 hours with a random temperature and returns those as an ObservableCollection<TimeForecast> for use in the DayForecast.HourlyForecast property:private static ObservableCollection<TimeForecast> generateRandomTimeForecast(int seed){  var random = new System.Random(seed);  var forecast = new ObservableCollection<TimeForecast>();  for (int i = 0; i < 24; i++)  {    var timeForecast = new TimeForecast();    timeForecast.Hour = i;    timeForecast.Temperature = random.Next(105);    forecast.Add(timeForecast);  }  return forecast;}How will this data be displayed in our app?  If you run the Before app as is, you’ll see the layout of the User Interface.Admittedly, most of the data is faked right now.  The data exists, however we’ve not bound to it because it’s not in the correct format for our purposes.Let’s look at the XAML to understand what is happening and how we’ll need to plug our converted values into the existing app.<Page  . . .  DataContext="{Binding WeatherViewModel, RelativeSource={RelativeSource Self}}"><ScrollViewer>  <StackPanel>    <ListView ItemsSource="{Binding}">      <ListView.ItemTemplate>        <DataTemplate>          <StackPanel Orientation="Vertical" Margin="20,0,0,30">            <TextBlock Text="{Binding Date}" FontSize="24" />            <StackPanel Orientation="Horizontal" Margin="0,10,0,0">              <Image Source="assets/snowy.png" Width="100" Height="100" />              <StackPanel Orientation="Vertical" Margin="20,0,0,0">                <TextBlock Text="High: " FontSize="14" />                <TextBlock Text="55" FontSize="18" />                <TextBlock Text="Low: " FontSize="14" />                <TextBlock Text="32" FontSize="18" />              </StackPanel>            </StackPanel>          </StackPanel>        </DataTemplate>      </ListView.ItemTemplate>    </ListView>  </StackPanel></ScrollViewer>As you can see, we’re employing a ScrollViewer to allow us to scroll past the bottom of the viewable area.  It wraps a StackPanel that contains a ListView.  In retrospect, a GridView may have worked as well if not better in this situation.  The ListView is bound to the ViewModel.  The ListView’s DataTemplate is made up of a series of StackPanels with TextBlocks and an Image.  The only data item we’re binding to at the moment is the Date, but even that is in need of a little massaging to make it look correct.  Ultimately, we’ll want to bind the source of the Image based on the Weater enum, and we’ll determine the high and low temperatures for a given day all using Value Converters.I’ll add a new class to the project called DateToStringConverter.First, I’ll make the class public and I’ll require it to implement IValueConverter.  Once I’ve added that code, public class DateToStringConverter : IValueConverter{}Next, with my text cursor on the term IValueConverter I’ll use the Command [dot] shortcut to display the Intellisense menu:… which will allow me to choose to Implement the interface by hitting the [Enter] key on my keyboard.  My class now looks like this:public class DateToStringConverter : IValueConverter{  public object Convert(object value, Type targetType, object parameter, string language)  {    throw new NotImplementedException();  }  public object ConvertBack(object value, Type targetType, object parameter, string language)  {    throw new NotImplementedException();  }}As you can see, two method stubs are added to the class by implementing the IValueConverter.  Convert will perform the conversion to your target display value, ConvertBack will do the opposite.  In our case, we merely need to format the Date into a string with the format I desire, so I implement like so:    public class DateToStringConverter : IValueConverter    {        public object Convert(object value, Type targetType, object parameter, string language)        {            DateTime date = (DateTime)value;            return String.Format("{0:dddd} - {0:d}", date);        }        public object ConvertBack(object value, Type targetType, object parameter, string language)        {            // For "display only", I don't bother implementing ConvertBack            // HOWEVER if your planning on two-way binding, then you must.            throw new NotImplementedException();        }    }Note that a better / more complete example of a ValueConverter that takes into account the language / culture as well as the converter parameter is found here:https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.data.ivalueconverterNext, I’ll need to tell my MainPage.xaml to use this new converter (I’ll remove everything except what will be added or changed):<Page  . . .  xmlns:valueconverter="using:ValueConverterExample"  . . .>  <Page.Resources>    <valueconverter:DateToStringConverter x:Key="DateToStringConverter" />  </Page.Resources>  . . .        <TextBlock Text="{Binding Date,                    Converter={StaticResource DateToStringConverter}}"                   FontSize="24" />                           In the Page declaration, I create a new namespace.  In this specific case I didn’t have to do this because the Value Converter I created is in the same namespace as the local namespace that’s already defined in the page.  However, at some point I plan on moving my Value Converters into a folder and will change their namespace accordingly.  Therefore, I’ve added this as a reminder / placeholder to myself.Next, I add the Value Converter key “DateToStringConverter” and point it to the class named DateToStringConverter (inside the namespace that is aliased to “valueconverter”).Third, I use the value converter in my TextBlock, inside the binding expression.Testing the result provides the format we desire.Next, I’ll add a value converter that will be used to change the Image’s source.  I’ll use the same basic procedure as before to create a new value converter called WeatherEnumToImagePathConverter.  A bit wordy, admittedly, but very descriptive.  I’ll implement it like so:public class WeatherEnumToImagePathConverter : IValueConverter{  public object Convert(object value, Type targetType, object parameter, string language)  {    var weather = (Weather)value;    var path = String.Empty;    switch (weather)    {      case Weather.Sunny:        path = "assets/sunny.png";        break;      case Weather.Cloudy:        path = "assets/cloudy.png";        break;      case Weather.Rainy:        path = "assets/rainy.png";        break;      case Weather.Snowy:        path = "assets/snowy.png";        break;      default:        Break;    }    return path;  }  public object ConvertBack(object value, Type targetType, object parameter, string language)  {    throw new NotImplementedException();  }}Hopefully you see a pattern.  I am merely taking the value, casting it to the original type I am expecting, then performing some logic or formatting on the value to determine the end result.  In this case, I’m returning the path to the image I’ll use in the Image’s source.I’ll now add the code to the XAML to implement this:. . .<Page.Resources>  . . .  <valueconverter:WeatherEnumToImagePathConverter x:Key="WeatherEnumToImagePathConverter" /></Page.Resources>. . .      <Image Source="{Binding Weather,              Converter={StaticResource WeatherEnumToImagePathConverter}}"             Width="100"              Height="100" />Running the app will display each of the icons at least once.Next, I’ll determine the high and the low for each day.  Recall that each day’s forecast contains an ObservableCollection<TimeForecast> that represent the temperature for each hour.  All we need to do is look at that collection and find the highest number (or lowest number) and return those from our Value Converter.  A simple LINQ query will do the trick in each case.I’ll add two more classes, HourlyColle
Download the source code for this lesson at http://absolutebeginner.codeplex.com/We’ve already discussed several facets of the Model-View-ViewModel design pattern, or rather MVVM.  In this lesson I want to add one more piece to the puzzle so that we can employ it in our upcoming project.MVVM provides a clean separation of concerns between the data model and the view.  This is accomplished through the ViewModel class which is responsible for publishing methods that return collections of our data model to the view so that the view can bind to it and display it.That covers the *display* of data.  What if, for example, we want to not only bind data in our view, but also bind the Click event of a button to a method defined on our data model?  Commands allow us to do that.It is easier to show you what I mean than to explain it in theory without a concrete example in front of you.I’ll create an app that might be used to check in cars at a Car rental company.  Customers drop off their cars in an airport, the Car rental employee sees a list of cars scheduled to be returned today, they click a button next to the car that they receive and see a message with the check in time.  This is far from a complete example, but it will allow us to see a simple example of Commands in action.I’ll start by creating a new project called “BindingToCommands”.  I’ll immediate add a Car class:public class Car{  public int ID { get; set; }  public string Make { get; set; }  public string Model { get; set; }  public string CheckedInDateTime { get; set; }}Note: Ideally we would store CheckedInDateTime as a DateTime, not a string.  I did this because I want to format the string nicely.  As you’ll learn in the next lesson, we can create a ValueConverter for the purpose of formatting the date nicely while keeping the value as a DateTime.Next I create a simple CarDataSource like so:public class CarDataSource{  private static ObservableCollection<Car> _cars       = new ObservableCollection<Car>();  public static ObservableCollection<Car> GetCars()  {    if (_cars.Count == 0)    {      _cars.Add(new Car() { ID = 1, Make = "Olds", Model = "Cutlas" });      _cars.Add(new Car() { ID = 2, Make = "Geo", Model = "Prism" });      _cars.Add(new Car() { ID = 3, Make = "Ford", Model = "Pinto" });    }    return _cars;  }}In the MainPage.xaml, I’ll call the static GetCars() method to wire up the Default View Model for the page:private ObservableCollection<Car> _carsViewModel =      CarDataSource.GetCars();public ObservableCollection<Car> CarsViewModel {  get { return this._carsViewModel; } }… and then binding to the view model in XAML like so:<Page  . . .   DataContext="{Binding CarsViewModel,       RelativeSource={RelativeSource Self}}">Then I’ll implement the layout and make sure the binding works.<StackPanel Margin="20,40,20,40">  <ListView x:Name="myListView" ItemsSource="{Binding}" >    <ListView.ItemTemplate>      <DataTemplate x:Name="dataTemplate">        <StackPanel Orientation="Horizontal">          <StackPanel Orientation="Vertical" Margin="0,0,20,0">            <TextBlock Text="{Binding Make}" FontSize="24" />            <TextBlock Text="{Binding Model}" FontSize="24" />          </StackPanel>                                  <Button Content="Check In"                   Width="100"                   Height="50"                   Margin="0,0,20,0" />          <TextBlock Text="{Binding CheckedInDateTime}" FontSize="24" />        </StackPanel>      </DataTemplate>    </ListView.ItemTemplate>  </ListView></StackPanel>This produces the following visual result:With the preliminary work out of the way, we can turn our focus to implementing the Command.  The first order of business is to implement the command that represents a “check in” for a car.  I’ll create a class called CheckInButtonClick that implements ICommand.  Then, I’ll use the Control + [dot] keyboard combination to implement the ICommand interface:This provides a stubbed out set of methods and the event declaration like so:    public class CheckInButtonClick : ICommand    {      public bool CanExecute(object parameter)      {        throw new NotImplementedException();      }      public event EventHandler CanExecuteChanged;      public void Execute(object parameter)      {        throw new NotImplementedException();      }    }First, I need to merely answer the question “can this be executed”?  Here I could write logic to decide whether or not this command can be executed based on the current state of the Car object that is passed in as a parameter.  Ultimately, I’ll return a bool.  In our case, since I’m going to keep this simple, I’ll merely return true.  This command can always be executed regardless of the state of the object.public class CheckInButtonClick : ICommand{  public bool CanExecute(object parameter)  {    return true;  }        . . .}In actuality, I would probably want to check to see whether if this instance of Car has already been checked in prior to allowing it a second time.  I’ll leave the implementation of that business rule to you for experimentation.Now, I need to associate the command with my Car class:        public ICommand CheckedInCommand { get; set; }        public Car()        {            CheckedInCommand = new CheckInButtonClick();        }I create an auto-implemented property of type ICommand, then in the Constructor, set the property to an instance of the CheckInButtonClick() command class.  Now I have a class that can be Commanded, in other words, that I can bind a Command to it.Next, I’ll want to tell the command what to do when this command is executed?  That’s what we’ll do in the Execute method.  In this case I want to set the CheckedInDateTime property to DateTime.Now.  Also, per my note, above, I want to format that for proper display.I have two options.  I can either implement this in my model (i.e., a public method on my Car class) or the classes I use to generate by View Model (i.e., the CarDataSource class).  Which one you choose depends on how accessible you want to make your View Model and how flexible you want to make your Command.  If you were to either make your Data Source a property of the App OR make all the methods of your Data Source class static, AND you don’t mind your Command being tied specifically to your CarDataSource class, then you could implement the Execute command like so:public async void Execute(object parameter){  CarDataSource.CheckInCar((Car)parameter);}And in your CarDataSource, you would implement the CheckInCar() method like so:public class CarDataSource{  . . .    public static void CheckInCar(Car car) {    _cars.FirstOrDefault(p => p.ID == car.ID)         .CheckedInDateTime = String.Format("{0:t}", DateTime.Now);  }}However, this approach has one obvious downside.  The Command is now coupled to the CarDataSource.  It could not be used as a more general purpose command.  That might be fine for your purpose, however another option is to make the CheckInCar() method a public property of the Car class itself:public class Car{  . . .  public void CheckInCar()  {    this.CheckedInDateTime = String.Format("{0:t}", DateTime.Now);  }}And I can call this method from the Command’s Execute() method like so:public async void Execute(object parameter){  //CarDataSource.CheckInCar((Car)parameter);  ((Car)parameter).CheckInCar();}I prefer this.  Next, I’ll need to wire up the binding correctly.  I will want to fire the Command when I click the button, AND I’ll want to pass in the current instance of the Car to the Command’s Execute() method.  To do this, I’ll add the following XAML in the Button’s declaration:<Button Content="Check In"         . . .         Command="{Binding CheckedInCommand}"        CommandParameter="{Binding}"        . . . />In this case, the CommandParameter is bound to it’s parent binding which is defined in the ListView’s ItemSource:<ListView x:Name="myListView" ItemsSource="{Binding}" >… which in turn is bound to:<Page  . . .  DataContext="{Binding CarsViewModel, RelativeSource={RelativeSource Self}}">To me, this is a bit confusing.  It looks like I’m binding the ENTIRE CarViewModel to the CommandParameter.  However, the correct way to interpret this … the ListView’s ItemSource expects a collection.  Then each item is then bound to just one instance of that collection, therefore the CommandParameter=”{Binding}” means “bind to the current instance of the Car class”, not to the entire collection.  That was a little tricky for me to understand at first.  The key is understanding how the DataContext flows down from the page, into the ListView and then into the ItemTemplate.Unfortunately, when I run the app, I may not get the results I was hoping for visually.  I would expect the value of CheckedInDateTime to change and then be presented on the screen when I click the Check In button.  It does not.  I assure you, the value is being changed in the data model, but because Car is not notifying the user interface of this property change, the user interface does not know it should update it’s presentation of the data.Do you recall what we need to do to tell the user interface that a property changed?  Yes, we need to implement the INotifyPropertyChanged interface on the Car class, then in the CheckedInDateTime setter, call the NotifyPropertyChanged() method that the interface forces us to implement.  Let’s implement that now using the Control + [dot] technique from earlier.Note: Keep in mind that this is not part of Commands per se, however if your Commands will be updating properties, you very well may need to implement INotifyPropertyChanged to enable some user interface update like we’ll do from this point on in the lesson.public class Car : INotifyPropertyChanged{  . . .  public event PropertyChangedEventHandler PropertyChanged;  private void NotifyPropertyChanged(string propertyName)  {    if (PropertyChanged != null)    {      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));    }  }}In this cas
Download the source code for this lesson at http://absolutebeginner.codeplex.com/In this short lesson we’ll learn about the CommandBar, another user interface element we can use on the Phone to provide more options in the form of icons and menu options to the user than what they see displayed by default.Here’s an example of a CommandBar with a single PrimaryCommand AppBarButton:Clicking the ellipsis on the right will reveal the label for the PrimaryCommand AppBarButton and reveals a SecondaryCommand AppBarButton for an “about” feature:How do you add these?  Obviously, with XAML.  However, Visual Studio does have a tool that makes quick work of this.Create a new Blank App project called CommandBarExample.  Open the MainPage.xaml into the designer.On the left side of Visual Studio, hover over the Document Outline tab and pin it down.  It will reveal each of the elements of the Page including a BottomAppBar and a Grid:Right-click the ButtomAppBar to reveal a context menu.  Select “Add CommandBar”:The following will be generated for you:As you can see, several items were created in XAML.  First, a BottomAppBar is created for the Page.  Inside the BottomAppBar is a CommandBar element containing two AppBarButton controls:    <Page.BottomAppBar>        <CommandBar>            <AppBarButton Icon="Accept" Label="appbarbutton"/>            <AppBarButton Icon="Cancel" Label="appbarbutton"/>        </CommandBar>    </Page.BottomAppBar>If you peek back at the Document Outline window, it will display the new elements in the outline:We’ll right-click the SecondaryCommands item and select the menu option from the context menu to add a new AppBarButton:Now, the XAML looks like this:    <Page.BottomAppBar>        <CommandBar>            <CommandBar.SecondaryCommands>                <AppBarButton Label="appbarbutton"/>            </CommandBar.SecondaryCommands>            <AppBarButton Icon="Accept" Label="appbarbutton"/>            <AppBarButton Icon="Cancel" Label="appbarbutton"/>        </CommandBar>    </Page.BottomAppBar>In addition to the PrimaryCommands and SecondaryCommands, we can also add an AppBarToggleButton:This will provide two states … on and off, as designated by the “chrome” around the symbol:The Phone API has many common symbols available.  Put your mouse cursor on a given AppBarButton in the XAML view, then look at the Properties window.  If you scroll down to the Icon section, the Symbol Icons are visible by default:You can select one of the available symbols for use in your app:You can also use Fonts to choose a Glyph (letter) for use as an icon:This selection produces the following XAML:            <AppBarButton Label="appbarbutton">                <AppBarButton.Icon>                    <FontIcon Glyph="B"/>                </AppBarButton.Icon>            </AppBarButton>And produces the following preview.There are other options that allow you to use your own images as well.  Final note: the AppBarButton operates much like a regular button insomuch that you can handle the Click event and other related options.
 Download the source code for this lesson at http://absolutebeginner.codeplex.com/I want to continue to build on the knowledge we’ve already gained from building the I Love Cupcakes app.  I want to focus on some slightly more advanced ideas so that we can create an even more advanced app. In this lesson we’ll discuss the technique required to save a text file to the Phone’s storage, then open and read that file from the Phone’s storage.  There are probably several ways to write and read data from a phone.  For example, if we were working with binary data — like an image file — we would go about this differently.  However, for our purposes, we want to merely save application data.In our case, we will have an object graph that we want to save to the Phone’s storage.  This will be input the user created when working with our app.  If it were a contact management app, it would store the names, addresses, phone numbers and email addresses for our friends and acquaintances.  We will want to store that data on the phone so that we can retrieve it the next time the user wants to look up a contact.  So, we need to figure out how to take an object graph and persist it to storage.  To do this, we will need to serialize the data.  Serialization is the process of representing an object graph in memory into a stream that can be written to disk using some format that keeps each instance of an object in the object graph distinct.  It keeps all of its state — its property values — as well as it’s relationship to other objects in the object graph intact.The content of the stream is based on which class in the Phone API you choose to perform the serialization.  In this lesson I’ll look at the DataContractSerializer which will convert our object graph into XML, and I’ll look at the DataContractJsonSerializer which will convert our object graph into Json.  These classes also can DE-SERIALIZE, which performs the opposite task of taking a stream and turning it back into an object graph for use in our app.Once we have a serialized stream of objects, we can persist it to storage.  On the Phone, each app has a designated area where data for the app should be written and read from called the Local Folder.  The local folder is the root folder of your app’s data store.  Use this folder to persist data on the phone.  In addition to general data storage, there are sub folders that should be used for specific scenarios.  https://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402541(v=vs.105).aspxI found this Quickstart very helpful when I was first trying to understand how the Phone stores application data and other media. The way you access the Local Folder is through the:Windows.Storage.ApplicationData.Current.LocalFolder object… like so:ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(fileName);… and …ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.ReplaceExisting)These will open a stream that will read contents from the file or write the contents of a stream to a file, respectively.  As you can see, when opening a stream for writing, you have some options regarding file name collisions.  CreationCollisionOption enum has the following values:OpenIfExists - Instead of writing, open the file into the current stream.FailIfExists - Throw and exception if a file by the same name already exists.GenerateUniqueName - Generate a new name for the file if a file by the same name already exists.ReplaceExisting - Overwrite the existing file with the same name no matter what.Ok, so there are two basic components.  You need a stream to read a file into, or a stream with data to write to a file.  The stream is the in memory representation of the file.Then you have the Phone API methods that operate on the physical storage of the Phone.But there’s also one final (optional) part … the  Phone API classes and methods that perform serialization and deserialization.  They write the object graph to the stream using a particular serialization scheme - XML, Json, Binary, etc.  AND they perform the corollary operation of deserializing the stream from XML, Json, Binary, etc. BACK into an object graph.To demonstrate these pieces, we’ll create a simple example using the Blank App Template called “StoringRetrievingSerlizing”.We’ll start by building the User Interface:    <StackPanel Margin="0,50,0,0">        <Button x:Name="writeButton"                Content="Write"                Click="writeButton_Click"                />                <Button x:Name="readButton"                Content="Read"                Click="readButton_Click" />                <TextBlock x:Name="resultTextBlock"                   FontSize="24"                   Height="400"                   TextWrapping="Wrap"                   />            </StackPanel>Next, I’ll create an object graph.  I’ll define a class (Car, for simplicity’s sake) and a helper method that will create instances of the Car class and save them in a List<Car>:    public class Car    {        public int Id { get; set; }        public string Make { get; set; }        public string Model { get; set; }        public int Year { get; set; }    }… and …private List<Car> buildObjectGraph(){  var myCars = new List<Car>();  myCars.Add(new Car() { Id = 1, Make = "Oldsmobile", Model = "Cutlas Supreme", Year = 1985 });  myCars.Add(new Car() { Id = 2, Make = "Geo", Model = "Prism", Year = 1993 });  myCars.Add(new Car() { Id = 3, Make = "Ford", Model = "Escape", Year = 2005 });   return myCars;}In the first example, the Write button will serialize the object graph to XML, then save it as a file to the Local Folder.  The Read button will read the file from the Local Folder and simply display the contents to screen.  We will NOT deserialize the XML back to an object graph in this example because I want you to see the XML that was created.  Therefore, we’ll simply use a StreamReader class to read the content from the stream into a String that we can then display in the resultTextBlock element.private const string XMLFILENAME = "data.xml";private async Task writeXMLAsync(){  var myCars = buildObjectGraph();  var serializer = new DataContractSerializer(typeof(List<Car>));  using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(                    XMLFILENAME,                    CreationCollisionOption.ReplaceExisting))  {    serializer.WriteObject(stream, myCars);  }  resultTextBlock.Text = "Write succeeded";}private async Task readXMLAsync() {  string content = String.Empty;  var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(XMLFILENAME);  using (StreamReader reader = new StreamReader(myStream))  {    content = await reader.ReadToEndAsync();  }  resultTextBlock.Text = content;}… Now, we’ll call these two helper methods from the appropriate button click event handler methods:private async void readButton_Click(object sender, RoutedEventArgs e){  await readXMLAsync();}private async void writeButton_Click(object sender, RoutedEventArgs e){  await writeXMLAsync();}Run the app, click the Write button, then the Read button to see the results:In this series of lessons we’ll use Json as our serialization format of choice.  I suppose there’s nothing wrong with XML other than it being verbose.  It has gotten a bad rap through the years as being difficult to work with.  There’s a joke: “I had a problem, and to solve it I used XML.  Now I have two problems.”  Json seems to be the preferred data format de jour.  It’s less verbose, and it is the native format for JavaScript objects, and JavaScript is all the rage right now.  But other than that, I see no technical reason to prefer one over the other.  Nonetheless, we’ll be using Json from here on out.Let’s create two new helper methods that work with Json instead of XML.  As you’ll see, the code is almost identical:private const string JSONFILENAME = "data.json";private async Task writeJsonAsync(){  // Notice that the write is ALMOST identical ... except for the serializer.  var myCars = buildObjectGraph();  var serializer = new DataContractJsonSerializer(typeof(List<Car>));  using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(                JSONFILENAME,                CreationCollisionOption.ReplaceExisting))  {  serializer.WriteObject(stream, myCars);  }  resultTextBlock.Text = "Write succeeded";}private async Task readJsonAsync(){  // Notice that the write **IS** identical ... except for the serializer.  string content = String.Empty;  var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(JSONFILENAME);  using (StreamReader reader = new StreamReader(myStream))  {    content = await reader.ReadToEndAsync();  }  resultTextBlock.Text = content;}… And I’ll modify the button click events …private async void readButton_Click(object sender, RoutedEventArgs e){  //await readXMLAsync();  await readJsonAsync();}private async void writeButton_Click(object sender, RoutedEventArgs e){  //await writeXMLAsync();  await writeJsonAsync();}When I run the app …But ultimately we do want to work with an object graph, not just Json.  So, I’ll create one final helper method:private async Task deserializeJsonAsync(){  string content = String.Empty;  List<Car> myCars;  var jsonSerializer = new DataContractJsonSerializer(typeof(List<Car>));  var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(JSONFILENAME);  myCars = (List<Car>)jsonSerializer.ReadObject(myStream);  foreach (var car in myCars)  {    content += String.Format("ID: {0}, Make: {1}, Model: {2} ... ", car.Id, car.Make, car.Model);  }  resultTextBlock.Text = content;}And change the Read button’s event handler method to call it:private async void readButton_Click(object sender, RoutedEventArgs e){  //await readXMLAsync();  //await readJsonAsync();  await deserializeJsonAsync();}… and then run the app …RecapThe biggest challenge is understanding the role e
Download the source code for this lesson at http://absolutebeginner.codeplex.com/In this exercise, I want to build an entire app based on the lessons we have learned about the Hub App project template. I want to show you how easy it is to transform that default Hub App project template into something completely different.  In this case we will create a media application that will display images and recipes of cupcakes as well as instructional videos of how to make cupcakes. Start by creating a new Project.  In the New Project dialog, (1) select the Hub App template, (2) rename to: ILoveCupcakes, (3) Click OK:First, we’ll remove all of the assets in order to replace them with our own tiles, backgrounds, etc.  In the Assets folder, select all files:… then use the Delete keyboard key.  When asked to confirm, select OK:Lesson21.zip contains an Assets folder with all of the images for app tiles, hub images, background images, etc.  In Windows Explorer, (1) select everything EXCEPT SampleData.json, and (2) right-click and select Copy from the context menu.Right-click the Assets folder in the Solution Explorer and select Paste.  Your file structure should look similar to this:Next, (1) open the package.appxmanifest, and (2) in the Application tab, modify the Display name property to: I Love Cupcakes … Next, (1) select the Visual Assets tab, (2) select the Square 71x71 Logo, (3) select the ellipsis button beneath the Scaled 240 asset … … in the Select Image dialog, (1) select the ILoveCupcakes-170.png, and (2) click Open.Repeat that technique to select the proper scaled image for (1) the Square 150x150 Logo, (2) the Wide 310x150 Logo, (3) the Square 44x44 Logo, (4) the Splash Screen, each time (5) selecting the appropriate image from the Assets folder.(1) Select the Square 71x71 Logo page again, and this time (2) in the show name check boxes, place a check next to both check boxes.If you open the HubPage.xaml, you’ll see that the background image is no longer visible.  In fact, the background is transparent.  This is because the style used for the background is no longer referencing an image in our project.  We’ll fix that in a moment.First, on the HubPage.xaml we’ll want to remove the Hub Sections we no longer need.  I’ll comment out the definition for HubSection1 …… as well as HubSection4 and HubSection5:Next, I’ll locate the parent Hub control.  Notice that the Background property for the control is bound to a ThemeResource called HubBackgroundImageBrush.  I’ll place my mouse cursor inside of that identifier and select the F12 key on my keyboard:… to view the definition for that ThemeResource.  The ImageSource property of the ImageBrush is set to an image that no longer exists in our project:I’ll update the reference to the new background image called: ilovecupcakes-background.png …Now, when I return to the HubPage.xaml, I can see the pink background.  Furthermore, I’ll modify the Header property of the HubSection1 to “RECIPES” and see it reflected in the preview pane:Likewise, I’ll update HubSection3’s Header to “VIDEOS” and see that change in the preview pane as well:At this point, we’ve make significant changes to the app (although we haven’t re-written much code per se).  Most of the changes have been “configuration” changes up to now.The app is styled as we would expect.  However, we’re missing data.  We’ll fix that soon.If you select the Windows button and navigate to the Apps page, you can see the app’s icon and title appears as we would expect:Furthermore, if we pin the app to the Start page and modify the tile sizes, we can see the the titles appear …... And the large branded tile appears as well:Now it’s time to make more significant changes to the app, specifically the data model.  In the SampleDataSource.cs, we’ll modify the SampleDataItem class adding a property called Type.  We’ll use the Type property to determine whether to navigate to a page that can display recipes and images or a page that can display video.I’ll use the prop [tab] [tab] code snippet to create the new Type property of type string:I’ll also change the constructor to allow the new type property to be passed in at construction, and will set the property in the same manner as the other properties are set:The other change comes when we’re loading the JSON into memory.  Therefore, we have to update the creation of new SampleDataItems in the GetSampleDataAsync() to include the new input parameter to the constructor:(1) Open the the SampleData.json file.  (2) Currently doesn’t have a “Type” property.  Furthermore, there’s a lot of data to input including Group and Item titles, subtitles, image paths, etc.  To keep this lesson short and reduce the possibility of fat-fingering the data in the file (causing runtime errors), I decided to create an alternative SampleData.json that we’ll copy into our project.  Before we delete this file, take note that (3) the Build Action property of the file is set to “Content”.  When I replace this file, I’ll need to make sure to set that property correctly to ensure the compilation process treats our new SampleData.json correctly.First, I’ll delete the current SampleData.json.  In Windows Explorer, in Lesson21.zip’s Assets folder, drag and drop the new SampleData.json into the DataModel folder of the project in the Solution Explorer.(1) Select the new SampleData.json file in the Solution Explorer, then (2) in the Build Action, change the value from None (the default) to (3) Content.If you open the new SampleData.json, you can see the shape of the data has changed to reflect our new Type property and the data also is specific to our app.If we re-run the app, we should now see images and cupcake-specific titles for the tiles in the Hub control.The next step is to set up the navigation from these tiles in the Hub control to pages that can display the pictures and recipe data or the “How To” videos for making cupcakes.  For the former requirement, I’ll simply re-use the ItemPage.xaml.  For the latter, I’ll add a new video.xaml page.Right-click the project name in the Solution Explorer, select Add > New Item … from the context menu.  In the Add New Item dialog, (1) select Basic Page, (2) change the name to Video.xaml, (3) click the Add button:In the new Video.xaml page, I’ll add a MediaElement control telling it to stretch to the dimensions of the parent grid, and setting the AutoPlay property to true, play as soon as the media source is determined:In the Video.xaml.cs, we need to determine which video to load into the MediaElement.  To do this, we’ll need to accept a parameter from the HubPage.xaml.  We’ll use the UniqueID of the SampleDataItem to determine which video should be displayed.  The UniqueID should be the same as the name of the video, sans the file extension “.mp4”.  Therefore, when a user taps a thumbnail image on HubSection3, we’ll determine the UniqueID associated with that item, and pass that UniqueID as a navigation parameter to the Video.xaml page.  In the NavigationHelper_LoadState() method, we’ll retrieve the SampleDataItem associated with the UniqueID (via the LoadStateEventArgs.NavigationParameter), we’ll construct a URI to the video file in the Assets folder by appending the file extension “.mp4” to the UniqueID.  Finally, we’ll set the MediaElement’s Source property to the newly constructed URI.There are a few problems with this code that need to be resolved.  First, we need to add a using statement for the ILoveCupcakes.Data namespace.  Second, we’ll need to add the async keyword to the method signature to accommodate the await keyword when calling SampleDataSource.GetItemAsync.Also, if we want to set the title of the page, we’ll need to give the TextBlock that contains the page title a name.Therefore, back in Video.xaml, I’ll modify the page title in the “TitlePanel” by giving it a programmatic name “PageTitle” so that our C# code that sets it will work:That concludes the changes required to the Video.xaml.Next, we’ll need to modify the ItemPage.xaml which will display the app’s title, and we’ll add a StackPanel in the Grid named “ContentRoot” to display an Image and a TextBlock.  After adding the XAML (below) you can see the changes to the ItemPage.xaml’s preview:Since the ItemPage.xaml was already “wired up” by the project template, no further changes will be necessary.The last significant change will be in the logic that determines whether to send the user to the ItemPage.xaml or the Video.xaml page based on the type of the item in the Hub’s ItemView controls that the user clicked on.  Note that both ItemView controls (defined in HubSection2 and HubSection3) use the same event handler method, ItemView_ItemClick.  Therefore, we’ll retrieve the ItemClickEventArgs.ClickedItem input parameter which lets us know which item was clicked and cast it to SampleDataItem.  Once we have the item, we can determine both the Type and UniqueID properties for the selected item.If the Type is “Recipe”, then we’ll send the user to the ItemPage.  If the Type is “Video”, we’ll send them to the Video.xaml page.  In both cases, we’ll send the UniqueID so that the proper SampleDataItem is displayed to the user.One final issue remains.  While we attempted to change the app name in several places in our XAML, it seems to ignore those changes.  The answer is that these settings were localized.  Localization is a topic we don’t cover in this series, however it allows you to create mutli-language versions of your app based on the user’s language and region preferences.  In this case, we’ll open the Strings\en-US\Resources.resw file in the Solution Explorer and modify the top two properties setting their values to “i love cupcakes”.Furthermore, in the Video.xaml page, I’ll make sure to update the title of the app (since I forgot to do it earlier):Now, when I run the app, it looks complete and the app’s name is consistent throughout.I see one last tweak to the default layout of the ItemTemplate for my videos …
Download the source code for this lesson at http://absolutebeginner.codeplex.com/You may think it an odd transition from talking about MVVM and awaitable tasks to something rather fun and mundane like playing video and audio in your phone app, however this is the last lesson before we go off and build a full app based on the ideas we’ve learned thus far.  I won’t spoil the surprise by foreshadowing what it is we’ll be building, but it will involve playing video and the Hub App Template just to show how flexible the Hub App Template is with a little imagination.To keep the example as simple as possible, I’m going to create a new Blank App Template project called “SoundAndVideo”.I will illustrate some very simple scenarios in this lesson … just a bit more than we’ll need for our full featured app in the next lesson, but not enough to go off and create some great audio player app.  You’ll want to consult the documentation if you have a more advanced scenario.I’ll begin by adding the XAML for my project:    <StackPanel>        <MediaElement x:Name="myMediaElement"                       Height="10"                       Width="10"                       Source="/Assets/Duck.wav"                      />            </StackPanel>Also, I’ll copy the Duck.wav file from the assets I’ve included with this series to the \Assets folder in my project by dragging-and-dropping from Windows Explorer to Visual Studio.When I run the app, I immediately hear the Duck quacking.  Admittedly, the sound is briefly interrupted during playback, but I’ve marked that up to the fact that there’s a lot going on during the deployment from Visual Studio to the emulator.What if I do not want the sound to play immediately, but only want it to play when I click a button?        <MediaElement x:Name="myMediaElement"                       Height="10"                       Width="10"                       Source="/Assets/Duck.wav"                      AutoPlay="False"                      />        <Button x:Name="playSoundButton"                 Height="80"                 Width="200"                 Content="Play Sound"                 Click="playSoundButton_Click" />I added the AutoPlay=”False” to stop the sound from playing automatically.  In the button’s click event:private void playSoundButton_Click(object sender, RoutedEventArgs e){  myMediaElement.Play();}What if I want to use this same MediaElement for multiple sounds or videos?  First, I would remove the Source and AutoPlay properties:        <MediaElement x:Name="myMediaElement"                       Height="10"                       Width="10"                       />And I would set the Source property in code:private void playSoundButton_Click(object sender, RoutedEventArgs e){  myMediaElement.Source = new Uri("ms-appx:///Assets/Duck.wav", UriKind.RelativeOrAbsolute);  myMediaElement.Play();}The ms-appx:/// means “look for this in the current app package once it is deployed to the Phone.What if I want to use the same MediaElement to play both an audio file AND a video file?  I’ll make the size of the MediaElement larger to accommodate the video:        <MediaElement x:Name="myMediaElement"                       Margin="0,40,0,40"                      Height="400"                       Width="240" />I’ll add a button:        <Button x:Name="playVideoButton"                Height="80"                Width="200"                Content="Play Video"                Click="playVideoButton_Click"/>I’ll copy the video named coffee.mp4 file from the assets I’ve included with this series to the \Assets folder in my project by dragging-and-dropping from Windows Explorer to Visual Studio.And I’ll handle the button’s click event:private void playVideoButton_Click(object sender, RoutedEventArgs e){  myMediaElement.Source = new Uri("ms-appx:///Assets/coffee.mp4", UriKind.RelativeOrAbsolute);  myMediaElement.Play();}What if I want to pause the video during playback?  I would need to keep track of the current state of the MediaElement.  I suppose there are many ways to do that, but I can imagine several states: Playing, Paused, Stopped.  So, I’ll add a new class file to create an enum called MediaState:    public enum MediaState    {        Stopped,        Playing,        Paused    }Then I’ll use that to perform the following logic:        private MediaState state = MediaState.Stopped;        private void playVideoButton_Click(object sender, RoutedEventArgs e)        {            if (state==MediaState.Stopped)            {                myMediaElement.Source = new Uri("ms-appx:///Assets/coffee.mp4", UriKind.RelativeOrAbsolute);                state = MediaState.Playing;                myMediaElement.Play();            }            else if (state==MediaState.Playing)            {                state = MediaState.Paused;                myMediaElement.Pause();            }            else if (state==MediaState.Paused)            {                state = MediaState.Playing;                myMediaElement.Play();            }        }I’ll also modify the MediaElement to handle the MediaEnded event in order to set the MediaState back to Stopped.<MediaElement x:Name="myMediaElement"     Margin="0,40,0,40"    Height="400"     Width="240"     MediaEnded="myMediaElement_MediaEnded" />Finally, I’ll handle the MediaEnded event:private void myMediaElement_MediaEnded(object sender, RoutedEventArgs e){  state=MediaState.Stopped;}As I said at the outset, there are more features of the MediaElement than we’ll discuss.  However, this will at least get you started thinking about what’s possible.  In the next lesson, we’ll put many of these ideas together to create an entire app.
We’ve spent a lot of time examining the Hub App Template, and for good reason — it illustrates many important concepts.  We’ll turn our focus back to the SampleDataSource class to talk about several keywords that I’ve ignored until now.  The keywords I'm referring to are:(1) async (2) await(3) Task<T>These keywords are newly added to C# 5.0 and are generally referred to as the new "async" feature, which is short for "asynchronous" or "asynchrony".  In a nut shell, this new feature is a simplified way of improving the performance of the app and making it more responsive to the user without the complexity of writing code to use multiple threads.  If you call a method of the Windows Phone API or some other library supporting async that could potentially take a "long time", the method will say "I promise to get those results to you as soon as possible, so go on about your business and I'll let you know when I'm done".  The app can then continue executing, and can even exit out of method contexts.  Another word for this in computer programming terminology is a "promise".Under the hood, when you compile this source code (i.e., the SampleDataSource class), the Compiler picks apart the source code and implements it as a complex series of statements in the Intermediate Language to allow this to happen flawlessly and it does it without the use of multiple threads in most cases.Async is best used for operations that have a high degree of latency, but are not compute intensive.  So, for example, the GetSampleDataAsync() method retrieves data from the SampleData.json file and loads it into an object graph of SampleDataGroup and SampleDataItem instances.  That could potentially take a second or two which is an eternity in computing.  Another example would be calling a web API to collect data.  Relying on communications over the Internet could potentially take a long time.  But the Phone's PROCESSOR is not busy at all.  It's just sitting there, waiting for a reply from the web service.  This is known as "I/O Bound" ... I/O means "In / Out" ... so things like the file system, the network, the camera, etc. involve "I/O bound operations" and are good candidates for async.  In fact, the Windows Phone API designers decided to bake async into all I/O Bound operations forcing you to use this to keep the phone responsive to the end user.Contrast that to a compute-intensive operation such as a photo filter app that must take a large image from the camera and run complex mathematical algorithms to change the colors or the position of each pixel in the image.  That could take a long time, too, but in that case, the Phone's processor is hard at work.  This type of operation is known as "CPU Bound".  This is NOT a good use of async.  In this case, you would want to consider a Background Worker which helps to manage threads on the Windows Phone platform.  If you are developing in .NET, you may prefer to work with threading via the Task Parallel Library instead, or revert back to managing threads manually which has been an option since the very earliest versions of .NET.Understanding multi-threading, parallel programming, the Task Parallel Library, even Background Workers on the Windows Phone API are WAY beyond the scope of this series and this lesson.  It's a large topic and I'll not lie to you, it makes my head spin. If you want to learn a little more about async and how it applies to the Windows RunTime, check out:Working with Async Methods in the Windows Runtime... and be sure to read the comments where I further explain this idea.But back to the topic at hand ... async is for those common occasions when you have a blocking operation that is not compute intensive, such as our case where we are waiting for these lines of code to complete:StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);string jsonText;using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) {. . . }In this case, we use the await keyword, which says "I'll get back to you when I'm finished".  The thread of execution can continue on through the other lines of code until it absolutely must have the results of that operation.  Now, in our case, we attempt to open and work with the contents of the file in the very next line of code, so little advantage is gained.  However, we must still use the await keyword because the StorageFile.GetFileFromApplicationUriAsync() and file.OpenAsync() methods both return IAsyncOperation<TResult>.  IAsyncOperation<TResult> is just a specialized version of Task<TResult> that is used by the Windows and Phone API.  By virtue of the fact that they return a Task<T>, we must await the results.  You'll see await-able methods with a common convention ... they all end with the suffix Async.Furthermore, any method that uses an await-able method must be marked with the async keyword in their method signature, AND if it is supposed to return a value it must return the value wrapped with a Task<T>.  If the method is void, it will merely be marked void in the method signature.  Since both the StorageFile.GetFileFromApplicationUriAsync() and file.OpenAsync() methods are marked with await, and our method, GetSampleDataAsync() returns a Task we must mark our method with async.  private async Task GetSampleDataAsync() { }In this case, Task is the return value.  What is returned exactly?  Just a promise that the GetSampleDataAsync() will finish running and when it does, any code calling GetSampleDataAsync() will be notified.  Here again, a lot of compilation magic happens at this point, the likes of which I don’t pretend to fully understand.How about in the case of GetItemAsync():public static async Task<SampleDataItem> GetItemAsync(string uniqueId){ . . . }In this case, Task<SampleDataItem> is returned.  But what is returned exactly?  Just a promise that the GetItemAsync() will finish running and when it does, any code calling GetItemAsync will be notified and will be rewarded with an instance of SampleDataItem.  Again, at this point a lot of compilation magic happens.In both of these cases, the presence of an awaitable task essentially means that any code  that calls our methods can continue executing until it absolutely needs the result of those methods.Again, remind me, why are we doing all of this?  In hopes of making our app more responsive.  This operation should not be blocking the Phone's processor from taking on other tasks like answering a phone call or running background tasks on behalf of other apps.  It won't prevent the user from selecting any of the hardware buttons on the phone and getting an instant response.Finally, even if you didn’t understand much of what I just said, let me make it really simple:(1) Certain methods in the Phone API use awaitable tasks to make ensure that they return control back to your code thus making your app hopefully as responsive as possible.(2) Therefore, when you need to use one of these methods in your app, you need to do the following:private void myExample() {  Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json");  StorageFile file =  StorageFile.GetFileFromApplicationUriAsync(dataUri);}(2a) Add await before the call to the Async method(2b) Remove void, add: async Taskprivate async Task myExample() {  Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json");  StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);}(2c) Call your new method using await… Or, if you intend to return a value …private StorageFile myExample() {    Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json");  StorageFile file =  StorageFile.GetFileFromApplicationUriAsync(dataUri);}Follow the previous steps, but do this instead:(2d) Rework the return type to:  async Task<StorageFile>So:private async Task<StorageFile> myExample() {    Uri dataUri = new Uri("ms-appx:///DataModel/SampleData.json");  StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);}… and the compiler will take care of the rest.RecapTo recap, the big take away in this lesson is what async is, how it works, what scenarios it was designed to address, and it's overall purpose -- to keep the phone and your apps responsive during long running I/O bound operations.
 In the previous lessons we learned about the Data Model and how it is used as the Data Context for Pages and Controls.  And when we talked about the Data Model, we’re talking specifically the classes in the SampleDataSource.cs file.  We learned about the binding syntax used by XAML to bind to the Data Model that was exposed by the code behind.The Hub App Template employs a design pattern in software called MVVM, or Model-View-ViewModel.  At a high level, MVVM seeks to “separate concerns”, extracting code that is specific to presentation (the View, or rather, the XAML that defines the user interface), the code specific to the domain (the Model, or rather, the SampleDataGroup and SampleDataItem classes), and the code that coordinates the activities of the model and provides the view with access to the model, (the ViewModel, or rather, the SampleDataSource class).MVVM is a slightly advanced topic, and frankly, I’m not sure I’m qualified to provide an exhaustive explanation.  Unfortunately, even some authors and books that have attempted to clarify this topic have not always done a good job doing it either.  But what I can do is show you the basics and how and why they are employed in the Hub App Template, so that you can begin to understand the thought process that influenced the organization and the design of the code in the template.  Obviously, my goal is to help you better make changes to this template, and a fundamental understanding of MVVM should help you build a mental model of the responsibilities for each class, each piece of the puzzle.Let’s start with the Model.  In software architecture, a Model is a representation of a given business or domain problem.  If you were building an Accounting system, your Model might have classes for things like Account, Customer, Credit, Debit, and so on.  If you were building a game, your Model might have classes for things like Planet, Spaceship, Soldier, Weapon and so on.  If you were building a media app, your Model might have classes for Sound of Video, Categories of Sounds and videos, and so on.  In most MVVM implementations I’ve seen, the Model is little more than a data structure … a class defining properties and basically the “state” of the object, but almost no methods to implement business logic.  (Just to provide a little guidance here, many believe this is an anti-pattern, or rather, “a bad idea”, called an Anemic Domain Model in which business logic is typically implemented in separate classes which transform the state of the domain objects.  But we’ll ignore that for now.)  You can see examples of a typical model that utilizes MVVM in our Hub App Template: the SampleDataItem and SampleDataGroup classes.  These have properties, but no real methods the implement logic.Next is the View.  The view has the responsibility of presentation of the Model.  It does this through Binding, a core component of XAML through the binding syntax we’ve seen.  What does the View bind to?  We’ve seen examples of binding to data via the ViewModel, but later in this series we’ll see how the View binds to commands that are implemented in the ViewModel.  Commands are essentially methods that perform logic and respond to the user’s interaction with the View.The ViewModel is the key to making MVVM work.  The ViewModel provides a layer of abstraction between the View and the Model.  We can see this in the SampleDataSource class.  It provides a data source to the View.  It must load data into instances and collections of the Model classes to create an object graph.  When I use the term “object graph” I’m referring to instances of classes that are related.  We see this at work in the GetSampleDataAsync() method.  Then, once the object graph is loaded into memory, there are various ways of returning parts of it based on the needs of a given view.  So, that is the role of the public property Groups, as well as the methods GetGroupsAsync(),  GetGroupAsync() and GetItemAsync().You might wonder whether the code behind (i.e., HubApp.xaml.cs) for the XAML is part of the View or the ViewModel.  After all, (1) it retrieves the appropriate data for the given View in the navigationHelper_LoadState() method, and (2) it exposes the data retrieved from the ViewModel as a property to the XAML (i.e., defaultViewModel).  I think of these are merely helpers to the main job of the View, and therefore I would classify them as part of the View itself.I say all of that to say this … the View should merely observe the data exposed by the ViewModel.  In other words, it should watch the collections (or instances of objects) that were delivered by the ViewModel for changes and react to those changes.  This is called “observability”.  If an instance of an object that is part of a collection managed by the ViewModel is added, removed or updated, then the View should be notified of the change and the View should update itself with that change. Fortunately, all of the “plumbing” required to make this work is baked into XAML.  But from your perspective, as the developer in order to make this work, your classes must implement the INotifyPropertyChanged interface.  By implementing INotifyPropertyChanged, your class says “You can observe me, I’ll let you know when I change.”  I don’t have a complete example to show you, but let me show the simplest example I can think of to show how such an implementation might work:class Sample : INotifyPropertyChanged{  public event PropertyChangedEventHandler PropertyChanged;  public int ID { get; set; }  private string name = String.Empty;  public string Name  {    get    {      return this.name;    }    set    {      if (value != this.name)      {        this.name = value;        NotifyPropertyChanged(”Name”);      }    }  }  private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")  {    if (PropertyChanged != null)    {      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));    }  }}By implementing INotifyPropertyChanged we must agree to raise an event called PropertyChanged.  This is the fundamental wiring that allows other classes (like user interface classes) to be notified that changes to an instance of this class have occurred (so now go update yourself to reflect those changes in your user interface).  This event is triggered in the NotifyPropertyChanged() method, which is called whenever the Set operation is invoked on the Name property.  So, in other words, when a line of code like this is executed:Sample mySample = new Sample();mySample.Name = “Bob”;… the PropertyChanged event is fired and any class that listens to this event (like certain user interface classes / controls in the Phone API) will have an opportunity to refresh the data they display.Having said all of that, the Hub App Template does not have any classes that directly implement INotifyPropertyChanged.  Instead, it uses ObservableCollection<T> (as well as a custom class, ObservableDictionary) which implements the INotifyPropertyChanged interface internally.  So, the moral to the story is that, as long as we’re using ObservableCollection<T> to expose collections of the objects from the ViewModel to the View, we’ll get observability at the COLLECTION level.  ObservableCollection<T> is essentially a List<T> with the added superpower of observability.A couple of important aspects about this.The SampleDataGroup has an Items property which is an ObservableCollection<SampleDataItem>.  Therefore, whenever new SampleDataItems are added or removed from the Items property, the PropertyChanged event will be fired by the collection on any user interface elements that bind to the Items collection.  Unfortunately, this is a bit anticlimactic because we do not see this happen in the template as it stands right now.  In other words, there’s no functionality that requires we remove items from the collection, and therefore we don’t see it in play.The second important aspect I want to point out is that if we want observability at the SampleDataItem level — in other words, if we want user interface elements that bind to the Items collection to update when the properties of an item in that collection are changed, we would need to manually write the code to implement INotifyPropertyChanged in the SampleDataItem class.  Since that is not how the class is currently implemented, if you were to change the value of a property, such as the Title or Subtitle, while the app is running, you would NOT see the user interface update to reflect that change.  Why?  Because the SampleDataItem class doesn’t have the ability (again, as it is currently implemented) to fire the PropertyChanged event and notify any observers of the change.  However, I believe I’ll demonstrate this when we build an application later in this series that works with observable data.RecapIn this lesson we talked about two very important ideas.  Hopefully you can see the larger role of MVVM and its influence on the Hub App Template.  That design pattern shaped and guided the developers of the template to provide an implementation that separated the concerns of the app and delegate responsibilities to certain classes.  Furthermore, hopefully you now understand, at least at a high level, why the Hub App Template is using  ObservableCollection<T>.  It provides a convenient means of updating user interface controls the notification to update itself when the underlying data source has changed. There are more aspects of MVVM that we’ll cover in this series.  I’ll talk Commands later in this series which allows the user interface to bind events like a button click to a method in the ViewModel.
Continuing our examination of the Hub App Template, we’ll learn how the HubPage.xaml page and the ItemPage.xaml binds to the data model we learned about in the previous lesson.Binding, also known as data binding, is common in the programming world. It is a convenient way of tying the presentation layer of your application to the data model. You can declaratively define the data source (most likely a collection of objects) for a given control, say, a grid or a list, and then tell the control to bind to the data source. It then takes care of creating a visual representation of each item in the data source as a row, a list item, etc.When building Phone apps in XAML, you use the Binding syntax we learned about previously. We saw how to bind to a static resource for the purpose of styling. You bind to data in a similar way using a similar syntax.<TextBlock Text="{Binding Title}" … />Let’s start from the top. The Page class, in this case, the HubPage class defines private field called “defaultViewModel”. This will be set to an object graph of Groups and related Items. That private field is exposed publicly through a read-only property called “DefaultViewModel”. The important thing is that we’re creating an instance of an ObservableDictionary<string, object>(). This class is something the template developers added to the template — it is not part of the Phone API. You can see its definition in the \Common folder. It’s not all that important to understand how it works under the hood. All I really care about is what the name implies. We’ve not talked about the term Observable yet, but we will soon. For now, just focus on the fact that we’re working with a dictionary style collection. Recall from the C# Fundamentals for Absolute Beginners series that a dictionary is a specialized collection that allows you to create a key and an associated value. This will be important in just a moment.As we learned about in an earlier lesson regarding the NavigationHelper class, the navigateionHelper_LoadState event handler is triggered when the page is navigated to. Let’s look at how it’s defined in the HubPage.xaml.cs:         private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)        {            // TODO: Create an appropriate data model for your problem domain to replace the sample data            var sampleDataGroups = await SampleDataSource.GetGroupsAsync();            this.DefaultViewModel["Groups"] = sampleDataGroups;        }This code:this.DefaultViewModel[”Groups”]… adds a new item to the dictionary with the key “Groups”.What is going into the dictionary? The Groups” that are retrieved using the SampleDataSource.GetGroupsAsync().You may wonder, why are they using a Dictionary if all they need is one item?  Again, I would remind you this is a template.  You could add more things to the Dictionary, then pull out what you need in the binding expression in XAML.  But you can only set the data context for the page to one object, so you would use this as the container for as much data for the various hub sections as possible.What will we do with this dictionary once it is filled up with data? Our goal is to get the various GridViews in our XAML to bind to this data.Look at the top of the HubPage.xaml page:<Page x:Class="HubAppTemplate.HubPage" . . . DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"Here we’re setting the DataContext of the entire Page, binding it to the DefaultViewModel of the current class (i.e., the {RelativeSource Self} means “you can find this class relative to myself, in my own class definition”).A DataContext is defined by a parent and then utilized by the children. In this example, the parent is the Page class, and the children are the various controls that will take the data from the DefaultViewModel and bind to it.So, given that the DataContext for the Page is set to the DefaultViewModel property, the ObservableDictionary already full of data, we can now revisit the XAML we looked at a couple of lessons ago (I’ll remove all of the XAML that is not important):<HubSection Header="SECTION 2" DataContext="{Binding Groups[0]}" …> <DataTemplate> <GridView ItemsSource="{Binding Items}"             ItemTemplate="{StaticResource Standard200x180TileItemTemplate}"> .. </GridView> </DataTemplate></HubSection>As you can see, I’ve removed A LOT of the XAML in order to clarify this example. Again, we’re working with the second panel, or rather, HubSection. The DataContext for the HubSection is Section2Items, the ItemsSource is the Items property. If you compare this to DefaultViewModel, it has a dictionary element called Section2Items which is of type SampleDataGroup. So, Section2Items (an instance of SampleDataGroup) has an Items property of type ObservableCollection<SampleDataItem>.Now, the ItemTemplate comes into play. The ItemTemplate of the GridView is used to render each item that is displayed in the GridView. So, in our case, each item in the Items property collection of SampleDataItem will be rendered using the Standard200x180TileItemTemplate defined near the top of the file. Again, I’ve removed almost all the XAML except for those parts that are important for this discussion:<DataTemplate x:Key="Standard200x180TileItemTemplate"> <Grid> . . . <Image Source="{Binding ImagePath}"  AutomationProperties.Name="{Binding Title}" />  <TextBlock Text="{Binding Title}" /> </Grid></DataTemplate>For each SampleDataItem in the DefaultViewModel[”Section2Items”]’s Items property, The Image’s Source property is set to the SampleDataItem’s ImagePath. The TextBlock’s Text property is set to the SampleDataItem’s Title.A couple of take aways from this first example:(1) Keep in mind that the DataContext keeps flowing downward. In other words, the Page’s data context flows into the HubSection. The HubSection’s data context flows into the GridView, etc. Understanding the hierarchy of the binding will allow you to keep things straight in your mind.(2) When you’re first getting started, it’s useful to stay close to examples like the ones in this template. If you can merely modify the existing example until you’re comfortable with the hierarchy of controls and settings, you’ll be more productive up front. You’ll see how I am able to utilize this Hub App Template to create an entire app in just a few lessons. Make small changes to these templates — you may even keep the original file in tact and use it for reference. Create a second page and copy parts from the HubPage.xaml into your new page until you’re comfortable with the relationships between the various parts.Let’s take a look at a couple of more examples.I’ll back up to the first HubSection which displays the Groups in a list:Here’s the XAML that accomplishes this, removing all code that doesn’t deal with data binding:<HubSection x:Uid="Section1Header" DataContext="{Binding Groups}"> <DataTemplate>  . . . </DataTemplate></HubSection>The HubSection’s DataContext is set to the DefaultViewModel’s “SectionGroups” property. private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e){ var sampleDataGroups = await SampleDataSource.GetGroupsAsync(); this.DefaultViewModel["Groups"] = sampleDataGroups;GetGroupsAsync() merely returns the list of Groups. Easy enough.What about the DataTemplate?<DataTemplate>  <ListView ItemsSource="{Binding}"            IsItemClickEnabled="True"            ItemClick="GroupSection_ItemClick"            ContinuumNavigationTransitionInfo.ExitElementContainer="True">    <ListView.ItemTemplate>      <DataTemplate>        <StackPanel>          <TextBlock Text="{Binding Title}"                      Style="{ThemeResource ListViewItemTextBlockStyle}" />        </StackPanel>      </DataTemplate>    </ListView.ItemTemplate>  </ListView></DataTemplate>The big differences between the Section 2 and Section 1:(a) Section 1 uses a ListView instead of a GridView, so all items flow vertically in one list, not in rows and columns like we saw in the GridView.(b) In Section 1, each individual item is styled in the body of the DataTemplate, it doesn’t use a StaticResource binding expression.(c) It uses the binding expression {Binding} because it is binding to the same data context as the entire page — the list of Group objects, whereas Section 2 is binding to a subset of the page’s data context, just the first Group object, Groups[0].  More about that in a moment.The rest of the HubSections use similar techniques.  Before I leave the HubPage.xaml, I do want to explain one last curiosity.  How is it that the designer view displays the actual data?  How it is loading what seems to be the actual data from the SampleData.json?  The key is in the Page’s declaration:<Page    . . .    xmlns:d="https://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    xmlns:data="using:HubAppTemplate.Data"    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"    d:DataContext="{Binding Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}"    mc:Ignorable="d">Any time you see the d: prefix applied, think “design time”.  For reasons I don’t want to explain in detail at the moment, that last half of the <HubSection /> snippet (above) loads sample data (from the SampleData.json file) and sets it to the data source.  It’s a convoluted string of binding statements and parameters, but in a nut shell that is what’s happening.  In other words, when you see data in Visual Studio (or another tool like Blend), that is being loaded as a result of that command.  Remember, XAML is used to create instances of data.  At compilation, that XAML is converted into Intermediate Language code and at run time, it is executed just like the other C# code we wrote.  But at DESIGN TIME, Visual Studio (and Blend) need a special set of commands to take the data from our JSON file (or other data source) and use it for display.
In this lesson, we’ll pick back up with the default Hub App Template prior to making any changes to it.  Previously we learned about the Hub control and its Hub Sections, and how each panel of content in the Hub control is arranged using a series of data templates.  In this lesson, we’ll look at where the actual data is coming from.  In the next lesson, we’ll look at how we use the data model to bind the user interface to the underlying data.First, at a high level, the idea of binding is that you have a collection of objects, for example, let’s say a collection of Cars like so:List<Car> cars = new List<Car>();Let’s suppose that the Car class is simple, like the classes we worked with in the C# Fundamentals for Absolute Beginners series.    public class Car    {        public int Id { get; set; }        public string Make { get; set; }        public string Model { get; set; }        public int Year { get; set; }        public string ImagePath { get; set; }    }You can add cars to that collection by retrieving data from a text file, a database, etc.  Suppose you read from a comma delimited file or a JSON (JavaScript Object Notation) file and create a new instance of the Car class for each row of data in that file.At this point, you would have a complete (albeit, a very simple) data model.  In other words, the classes and the code that opens the data file, reads it, and turns it into instances of objects, and adds those objects to a collection, is essentially the data model.And once you have that data model in place, essentially a collection of Cars in memory, you can bind that collection to a GridView or some other list-style control that will allow you to display them in a tabular or grid-like manner.  You could use the ImagePath as the data source for a thumbnail picture of the given car.  You could display the Make and Model in text that appears on top of the image.  Clicking a given item in the GridView would allow you to see more information about the given car in the ItemsDetail.xaml page.  More about that in the next lesson.Hopefully you understand what we’re trying to achieve.  The Hub App Template supplies you with a generic data model including sample data, classes that represent data structures, and classes that provide access to the instances of those data structures.  Ideally you can just modify what they already have and use it for whatever type of data you want to work with.  In fact later in this series, we’ll do exactly that — we’ll modify the Hub App Template to create a complete app that displays images and recipes for cupcakes.The data model created by the Hub App Template is self contained in the \DataModel folder.  There are two files:SampleDataSource.cs - This single file has multiple parts, but it defines a class for sample data items, as well as a class that is used to group the items together.  This gives you a simple hierarchical structure you can wrap your mind around.  If you need to further add another grouping on top of that, you can extend this.  Furthermore, you can scrap this all together.  All you really need is a collection of objects, or some other object graph.  The SampleDataSource.cs also knows how to open a data file, retrieve the results, and create instances of the Item and Group objects.  So, unfortunately, this serves several purposes and as a result, the code may be a bit obscure for beginners.Where does the actual data come from? SampleData.json - JSON stands for JavaScript Object Notation.  I created a lesson in the JavaScript Fundamentals for Absolute Beginner’s series about JSON.  I recommend you watch that for a thorough explanation of the syntax.Now, I get asked the following questions often:(1) Why did the developers of this template choose the JSON format over, say, a comma delimited file format?Well, I don’t have any special knowledge about this, but I suspect two reasons.  First, JSON files can easily represent object graphs, or rather, collections that contain objects (in this case, “Groups”) that have a property (”Items”) which is a collection of an object (”Item”).  You don’t get that structure from a flat comma-delimited file.  Secondly, it’s relatively easy to read and write JSON using built-in classes as we’ll learn throughout the remainder of this series.I realize at first glance, JSON can be a bit intimidating.  However, the good news is that it is quickly becoming a very popular file format and has the added benefit of being easily utilized by JavaScript and some commercial and open source document databases.(2) Can I use some sort of structured relational database instead of JSON?I have not personally done this, but I know some have tried to use a SQL Server Compact or LocalDb.  Others have had success with a local file-based database called SQLite.  I’ve not tried either of these techniques but I suspect it is possible.  Also, you could use some external service such as those available on Windows Azure or Azure Mobile Services.  We don’t cover those in this series, but these are all options depending on the requirements of your application.One final thing I want to address conceptually / generically: what is a “data model”?  This is a term that deals with your application’s architecture, or in other words, how you separate and layer your application’s code.  Typically you want to keep logical layers separated and in most applications that means you keep the persistence code separate from the business rules, or rather, the domain logic, and you keep all of that separate from the presentation logic that displays data to the user.  The benefit of abstracting the various responsibilities of your application into software  layers is that you can manage change more effectively.  I’ll resist the urge to talk about this in more detail.The “data model” is a layer that encapsulates all of the logic required to retrieve data from an underlying data source, such as a JSON file or a database, and put it into an object graph that can be used by the other layers of the software.  In our case, the result of calling into the data model is an object graph that contains the data that we’ll display in our application.As I said earlier, the data model — more specifically the SampleDataSource.cs — has several classes all collected into one file.The SampleDataItem class is the child.  It is what you see in “SECTION 2” of the Hub.  The SampleDataGroup class is the parent.  It has an Items property which is a collection of SampleDataItem.  (Actually, it is a special type of collection called an ObservableCollection<T> which we’ll talk about in another video.  For now, just think of it as a simple List<T> and I’ll explain the difference later.)For the most part, SampleDataItem and SampleDataGroup are just data structures … no methods outside of the constructor, just a set of properties.All of the real heavy lifting in regards to retrieving data and creating instances of the SampleDataItem and SampleDataGroup classes is in the SampleDataSource class.  It looks like there’s a lot going on here, so let’s make sure we understand what it is doing.First this line of code:private static SampleDataSource _sampleDataSource = new SampleDataSource();… is a coding pattern called “Singleton”.  It forces just one instance of the class to be created, never more.  That way you can always make sure you’re working with the same instance of the class.Next:        private ObservableCollection<SampleDataGroup> _groups = new ObservableCollection<SampleDataGroup>();        public ObservableCollection<SampleDataGroup> Groups        {            get { return this._groups; }        }This exposes a Groups property which is a collection of SampleDataGroup.  Exposing this property makes it easy to bind to the Groups and Items using the binding syntax in XAML.  More about that in the next lesson.The next three methods will return ALL groups, one specific group, or one specific item by either returning the _groups, or by performing some LINQ to Objects query on _groups:public static async Task<IEnumerable<SampleDataGroup>> GetGroupsAsync() { … }public static async Task<SampleDataGroup> GetGroupAsync(string uniqueId) { …}public static async Task<SampleDataItem> GetItemAsync(string uniqueId) { … }Notice that they each call the EnsureSampleDataLoaded() method:private static async Task EnsureSampleDataLoaded(){  if (_sampleDataSource == null || _sampleDataSource.Groups.Count == 0)    await _sampleDataSource.GetSampleDataAsync();  return;}In other words, make sure we’ve loaded up the data before continuing.  If Groups is empty, go load that data!  That leads us to the final method in the class, GetSampleDataAsync().  Before I talk about that …I’ve taken a great liberty by ignoring keywords that embellish these methods like “async” and “Task<T>” and even the “await” keyword.  We’ll devote an entire lesson to a high level explanation of these ideas.  Let’s just ignore they exist for now.In pseudo code, the GetSampleDataAsync() method does the following:- Make sure there’s no data in Groups.  If there is, this isn’t necessary.- Open the data file.  - Read the file’s contents into a string, then parse it to JSON (or actually, into an array of JSON)- Loop through the array, creating a Group object- One element of the array contains another JSON array (Items).  - Loop through that array, creating an Item object, add it to the Items collection.- Add the group (and all of its children) to the Groups collection.Now, when the GetGroupsAsync(), GroupGroupAsync(), GetItemAsync() or just the Groups property are accessed, we’ll have data available.So, that’s how the *sample* Data Model works.  However I think it is important to emphasize that you don’t have to follow this exact technique / approach.  You can replace some or all of this.  It’s just a template, not a requirement.  Your application may require a less complex class hierarchy, or perhaps a more complex one.  You may replace the JSON file with some other data
In this lesson, we’ll learn about the Hub App template.  If you’re familiar with the Windows Phone, you’ll have seen instances of the Hub in use.   There is so much here that we’ll spend the majority of the remaining series talking about this template, the technologies it uses, and how to modify it and extend it to get the results we want.  That’s no small matter.As a part of this lesson we will:(1) Create a new Hub App Template project called “HubAppTemplate”(2) Run the app.  Note the navigation.  Tie the navigation to pages in the project.(3) Open the HubPage.xaml and roll up the major sections … they will primarily break down into: DataTemplates and HubSections.Begin by creating a “throw away” project using the Hub App Template.So, let’s talk about a high level about how this app works and then we’ll drill down into each of the pieces.At the highest level is the Hub control which allows you to create a series of panels, or rather, HubSections.  You can see there are five HubSections that correspond to the five panels in our app. Each HubSection is comprised of (a) data and (b) a template that defines how that data should be displayed.  So, two parts, data and a data template.I’ll talk about the source of the data in just a moment.  However, let’s take a look at the data templates.  If we drill into a given HubSection like “SECTION 2”:<HubSection x:Uid="Section2Header"             Header="SECTION 2"             Width="Auto"            DataContext="{Binding Section2Items}"              d:DataContext="{Binding Groups[1],                 Source={d:DesignData                   Source=./DataModel/SampleData.json,Type=data:SampleDataSource}}">  <DataTemplate>    <GridView ItemsSource="{Binding Items}"                                      AutomationProperties.AutomationId="ItemGridView"              AutomationProperties.Name="Items In Group"              ItemTemplate="{StaticResource Standard200x180TileItemTemplate}"              SelectionMode="None"              IsItemClickEnabled="True"              ItemClick="ItemView_ItemClick">      <GridView.ItemsPanel>        <ItemsPanelTemplate>          <ItemsWrapGrid />        </ItemsPanelTemplate>      </GridView.ItemsPanel>    </GridView>  </DataTemplate></HubSection>There’s a lot going on here.  That’s because this is employing a whole framework of templating in order to make it extremely flexible.  The unfortunate trade off to making a technology very flexible is often complexity, at least at first.  However, it’s all logical, so if you can just understand the logic behind it, if you can build a mental model, you can at a minimum be able to command it to do what you need it to by force with a lot of trial and error.Besides the properties of the HubSection itself which I’ll ignore for now because it has to do with the data, the HubSection has a child called DataTemplate.  The DataTemplate is a GridView … similar to a Grid control that we’ve used for layout, but it supports binding to data.  The GridView represents this entire area in “SECTION 2”.  The GridView’s ItemsPanel controls the flow of each individual item in the GridView.  So, you have a collection of items.  Will they flow horizontally or vertically?  In this case, the ItemsWrapGrid by default will position each child elements sequentially from top to bottom. When elements extend beyond the container edge (the bottom, in this case), elements are positioned in the next column. So, The ItemsPanel uses the ItemsWrapGrid to layout each item in our data in a certain flow direction, from top to bottom, then left to right.But what about the layout of each individual item in our data?  The GridView’s ItemTemplate="{StaticResource Standard200x180TileItemTemplate} property dictates that.  As you can see, it is binding to a StaticResource called Standard200x180TileItemTemplate which is defined in the Page.Resources section:<Page.Resources>  <!-- Grid-appropriate item template as seen in section 2 -->  <DataTemplate x:Key="Standard200x180TileItemTemplate">    <Grid Width="180">      <Grid.RowDefinitions>        <RowDefinition Height="Auto"/>        <RowDefinition Height="Auto"/>      </Grid.RowDefinitions>      <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}"               Height="173"               Width="173"               Grid.Row="0"               HorizontalAlignment="Left">          <Image Source="{Binding ImagePath}"                Stretch="UniformToFill"               AutomationProperties.Name="{Binding Title}"                Height="173"                Width="173"/>        </Border>        <TextBlock Text="{Binding Title}"                    Style="{ThemeResource BaseTextBlockStyle}"                   Typography.Capitals="SmallCaps"                    Grid.Row="1"                    Margin="0,12,0,0"                    IsTextScaleFactorEnabled="False"/>      </Grid>    </DataTemplate>Each individual items is made up of a Grid that is 180 pixels wide.  The grid defines two rows.  The first row is filled with an border that contains an image, these gray images we see in the designer.  I think the Border is just there in case the image cannot be displayed, or perhaps it provides a themed background color for transparent images.  I’m not really sure of the purpose, but I think that will be the result.  The second row is filled with a TextBlock, the “Item Title: 1” and so forth.So, now we understand how each item in our data source will be rendered to screen for “Section 2”.  Admittedly, there are many tiny details I’m overlooking, but I can perform a search online for their meaning.  I highly encourage you to do the research when you come across something that is not obvious by just reading it’s name or setting. For example, I refrained from talking about the <TextBlock Typography.Capitals=”SmallCaps” /> because I give you enough credit to be able to look at that and understand what it is doing when you see the results on screen:However, the <TextBlock IsTextScaleFactorEnabled=”False” /> is not, at least to me, quite as obvious.  So, I’ll perform a search online to learn more about it.Back in the GridView definition, there are three properties that affect navigation:<GridView                           . . .   SelectionMode="None"  IsItemClickEnabled="True"  ItemClick="ItemView_ItemClick"></GridView>Setting SelectionMode to none means that we’re not allowing individual items to be selected, as if there were a list of items that we’re selecting for inclusion in some operation.  Instead, we want to allow the user to click a given item and perform a navigation operation.  Setting IsItemClickEnabled=”True” instructs the GridView how we want a tap to be interpreted.  We want a tap on a given item to trigger an event called ItemClick, not a selection event called ItemSelected.  The semantic difference of those two interactions is very important.The ItemClick=”ItemView_ItemClick” wires up an event handler to the ItemClick event.If we navigate to that event handler in our code behind, we find the following definition:void ItemView_ItemClick(object sender, ItemClickEventArgs e){  // Navigate to the appropriate destination page, configuring the new page  // by passing required information as a navigation parameter  var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;  this.Frame.Navigate(typeof(ItemPage), itemId);}The first line of code is retrieving the clicked item from the ItemClickEventArgs and then casting it to an instance of the class that we’re binding to.  This SampleDataItem class is just sample data provided by the Hub App Template so that you can see some data when you run the application.  We’ll investigate that class in the next lesson.  For now, just understand that it has a property called UniqueId.  We’re retrieving that UniqueId that presumably uniquely identifies the specific item that was tapped amongst the dozen or more items that the user could have tapped.The next step is simple … navigate to the ItemPage.xaml page passing in the id of the item that we want displayed on that page.Based on our understanding of the Navigation model and how we can retrieve the object that was passed from one page to the next, we might think we know what happens on the ItemPage.xaml.  We would expect to handle the OnNavigatedTo() method like we’ve done before.However, if we were to look at the ItemPage.xaml.cs file, you’ll find no such method declared.  Instead, we see that the Hub App Template relies on a class called NavigationHelper to perform some repetitive tasks related to navigation and passing data between pages.The NavigationHelper.cs file is located in the \Common folder.  If you’re following along, take a moment to read the lengthy explanation in the comments about what this class does and how to use it.  In a nut shell, it handles state management for you, allowing users to return to the exact page in your app where they left off in their previous session.  I would recommend that you do not make any changes to this class for now.So, I’ll just pluck out the lines of code that are used to enable the use of the NavigationHelper class from within the ItemPage.xaml.cs (in other words, I’m removing all the code that doesn’t deal with navigation in the following code just so you can easily isolate what has been added to work with the NavigationHelper class):    public sealed partial class ItemPage : Page    {        private NavigationHelper navigationHelper;        public NavigationHelper NavigationHelper        {            get { return this.navigationHelper; }        }        public ItemPage()        {            this.navigationHelper = new NavigationHelper(this);            this.navigationHelper.LoadState += navigationHelper_LoadState;        }           private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)        {            var item = await SampleDataSource.GetItemAsync((String)e.NavigationParameter);            this.DefaultViewModel["Item"] = item;   
Download the source code for this lesson at http://absolutebeginner.codeplex.com/In this lesson we're going to take what we've learned previously and we're going to create an entire app, a very silly little game using the WebView App project template featuring the WebView control.  We'll base our game on this app that I've built for the Javascript Fundamentals for Absolute Beginners series on Channel9.  You can find it here:https://channel9.msdn.com/Series/Javascript-Fundamentals-Development-for-Absolute-Beginners/jQuery-Events-16In that lesson I explained jQuery Events and to demonstrate the concepts of that lesson I created the Click-a-Bob game.  It features a little cartoon “bob head” and you keep clicking on the cartoon bob head and it gives you a score.  You can reset the score by hovering over the Start Over button on the right.Important: Make sure you download the assets that are available for this lesson in the Lesson14.zip file.  Inside of that .zip file there should be an Assets folder containing the icons, the images, the source code, etc. required to follow along and complete this lesson.Note: This project was inspired by the Clow Clicker app.  The guy who built it just wanted to parody some of those mindless social games and, to his surprise, it became an instant success.  People just kept clicking the cow to get more click points. http://en.wikipedia.org/wiki/Cow_ClickerOur plan is to take the Click-a-Bob and turn it into a Phone app called Whack-a-Bob.To begin, we’ll create a new (1) WebView App project (2) named WhackABob and (3) clicking OK:The first task is to copy over all of the assets and code from the Assets folder.  To begin I’ll select all of the current files in the project’s Assets folder:… and select the Delete key on my keyboard.  It will ask me to confirm the deletion and I’ll select the OK button.Next, I’ll select all of the numerical bob head images for use as app tiles in Windows Explorer and drag and drop these into the Assets folder in Visual Studio’s Solution Explorer:            Your Assets folder should now look like this:Next, I’ll create a sub-folder called scripts and images.  I’ll right-click on the Html folder and select New Folder:And name the first folder: scriptsI’ll repeat, this time naming the sub-folder: imagesNext, I’ll (1) drag the bobtabor.jpg image from Windows Explorer into (2) the new images sub-folder in Visual Studio:In preparation for copying the HTML from the original web page into the new index.html page in Visual Studio, I’ll right-click the C9JS_16.html file in Windows Explorer and select Open with > Notepad.Next, I’ll (1) drag and drop the script16.js file from Windows Explorer into (2) the new scripts sub-folder in Visual Studio’s Solution Explorer:Finally, I’ll (1) drag and drop the style16.css file from Windows Explorer into (2) the css sub-folder in Visual Studio’s Solution Explorer:When finished, your Solution Explorer should have the same file structure as mine:Next, we’ll begin to edit the index.html page by copying HTML from the original C9JS_16.html page (which we opened in Notepad).  I'll highlight and copy the references to jQuery to our Script16.js and to our style16.css files …… and paste into the head section of the index.html document:(1) I want to make sure I reference the correct locations for these files so to make sure I'm referencing the scripts folder, and (2) I’ll remove the reference to jquery in the CDN.When you're building an app on the phone you don't want to include any references to outside resources even though jQuery is best served up from a Content Delivery Network when building web page consumed by web browsers over the internet.  So, we’;; copy jQuery down into our local project and reference it from there.If you go to:http://jquery.com/download… you can download the compressed version, the production version of jQuery, the latest version that's available. At the time of publication, it is 2.1.0.If you attempt to save this file, Internet Explorer gives you a little warning here.  "Hey, this file can't be verified. Be careful about this."  Click Save:Once saved locally, I’ll drag it into my scripts sub-folder ……  and for ease of working with it I'm just going to rename this, just jquery.js:So then in my HTML what I'll do is reference it as scripts/jQuery.js:Back to my original HTML, I'm going to select all the HTML in the body and copy it from Notepad … … and paste it beneath the title div in the index.html page in Visual Studio:Furthermore, I'm going to edit the head and title div (beneath the body tag), I’ll change all text from "clicked" to "whacked", and I’ll modify the image location to the images/bobtabor.jpg.Before we take our app for a test run, I’ll modify the branding elements.  You’ll recall earlier we copied the sized “cartoon bob head” images into the Assets folder.  To utilize these …(1) Open the package.appxmanifest(2) Select the Visual Assets tab(3) Select the Square 71x71 Logo page on the left(4) Under the Scale 100 image, click the ellipsis button …This will allow you to choose an image from your hard drive.  Navigate to the Assets folder for the project and (1) select the 71x71.png file, then (2) select the Open button.Repeat those basic steps for (1) the 150x150 Logo, (2) the Wide 310x150 Logo, (3) the Square 44x44 Logo, and (4) the Splash Screen.  In each case, make sure to set the “Scale 100” image.Now we’re ready to test what we have so far.  Select to debug the app in the Emulator:And while it’s not perfect (yet) we can see that with minimal changes, we’re able to re-create the majority of the app complete with jquery enabled interactive functionality.However, there are a few annoyances.  For example, I accidentally am selecting text on the Start Over button:… ideally, I would not be able to do that.  Furthermore, if I attempt to drag the entire web page down, I can pull the page away from the edges.  That’s something I want to disable as well.Clicking the emulator’s Start button, then navigating to the Apps page, I can see that my logo appears next to the name of the app.  However, the name is not quite right.  I would like to change the text to: Whack-a-BobIf I hold down on the app’s entry, the context menu appears allowing me to test how the tiles will look when pinned to the start menu:By default, it looks good however I would prefer if the app’s title appeared in text under the logo (like the other apps on my phone).If I hold down on the tile, I can modify the various sizes of the app tile to test those as well.I stop debugging and begin to fix a few of the issues with my app.To begin, I’ll modify the display name that appears on the app and the start page tiles of the phone by going to the package.appxmanifest and modifying the Application tab’s Display name property:To add the display name under the pinned tiles on the Phone’s Start page, on the Visual Assets tab, I’ll (1) select the Square 71x71 Logo page, and (2) put a check mark next to both the Show Name check boxes:Next, I’ll want to modify the index.html’s layout to properly fit everything on the page, modify the text size, etc. Appropriate for a Phone app (as opposed to it’s original purpose as a simple web page).  I’ll modify the #game id, removing the specific width (200px) replacing it with 100%, and floating to the left instead of the right:The Start Over button requires some major changes.  I change virtually every CSS property like so (in  the #startover id’s css definition):Next, in the index.html, I want to move the Start Over button (1) from the bottom, to (2) above the game div:To fix the text selection issue and the drag / movement issue, I’ll modify the phone.css page’s html / body definition adding the -ms-touch-action: none; and -ms-user-select: none; settings like so:This time when I re-run the app, I get the results I desire:Before we conclude, Matthias wanted me to point out that if you're going to do a lot of work with jQuery inside of Visual Studio, you might prefer to install using Nuget package “jQuery vsdoc”.  This will give you IntelliSense for jQuery, syntax highlighting, and other helpful additions inside of Visual Studio.  You'd get the same experience with Javascript and with all the jQuery methods and selectors and things of that nature as you get with XAML and C#.https://www.nuget.org/packages/jQuery/2.1.0
Download the source code for this lesson at http://absolutebeginner.codeplex.com/In my personal opinion, the WebView App template featuring the Web View control, is probably the easiest way to create an app IF you already have basic HTML, CSS and JavaScript knowledge.  In this lesson, we’ll look at the basics, in the next lesson we’ll build an app based on something from the JavaScript and JQuery Fundamentals for Absolute Beginners series just to demonstrate what’s possible and to demonstrate the types of issues you might face when converting an existing JavaScript-based app to the Web View App Template.Consequently, these are the only two lessons in this series that do not primarily use XAML and the Phone API for layout, navigation, etc.  Feel free to skip these lessons if you do not intend to utilize the web-stack of technologies for building apps.(1) I’ll begin by creating a new WebView App project called “WebViewExample”.  You’ll immediately notice the presence of the \Html subfolder along with an index.html file and a \css subfolder with a phone.css file.If you take a look at the MainPage.xaml, it hosts a WebViewControl and a CommandBar with a Forward and Home app bar button.In the MainPage.xaml.cs, there’s a HomeUri referencing the \Html\index.html.  private static readonly Uri HomeUri = new Uri("ms-appx-web:///Html/index.html", UriKind.Absolute);In the OnNavigatedTo() method, the WebViewControl is told to navigate to the HomeUri as well as some event handlers for the physical back button and the forward AppBarButton in the CommandBar.  In fact, most of the code on this page is attempting to manipulate the “page stack” — page that have been visited, going back, going forward, etc.  We’ll see those at work in a moment.  In fact, you may notice that the WebViewControl has a very similar set of Navigate methods as the Frame.  We can leverage what we already know about the Frame to take control of the navigation experience if we want to, but most of that has been taken care of for us already by the WebView project template.(2) The templated index.html has the following definition:<!DOCTYPE html><html><head>    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />    <link rel="stylesheet" type="text/css" href="css/phone.css" />    <title>Windows Phone</title></head><body>    <div>        MY APPLICATION    </div>    <div id="page-title">        page title    </div></body></html>Two items to note: <link> references the \css\phone.css file, and there are two <div> elements to create the now familiar app name and page title.  If we were to run the app right now, we would see the following:Take a look at the phone.css file and match up the styles defined in the CSS with what you see on screen.  Notice the first two @media definitions are to help with orientation, while the remaining styles affect the layout of the page.  You are free to add to this file, but I would recommend that you add additional CSS files and link to them so that, if Microsoft ever updates this file, your changes will not have to be merged.(3) Add a second html page called “Page2.html”.  In my version of the page, it does not have the link to the phone.css nor does it have the the <div> tags.  Instead, you get this:<!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>    <meta charset="utf-8" />    <title></title></head><body></body></html>So, I’ll copy the HTML from index.html into the new Page2.html to make sure they’re consistent.  I’ll then modify Page2.html so that it has the proper app name and page title:<body>    <div>        WEBVIEWCONTROL EXAMPLE    </div>    <div id="page-title">        page two    </div></body>And I’ll modify index.html in a similar way:    <div>        WEBVIEWCONTROL EXAMPLE    </div>    <div id="page-title">        page one    </div>(4) Add these lines to index.html:    <h1>Test H1</h1>    <h2>Test H2</h2>    <h3>Test H3</h3>    <p>This is a paragraph.</p>    <p>This is a <a href="Page2.html">hyperlink to a second page</a>.</p>    <p>This is a <a href="https://www.microsoft.com">hyperlink to Microsoft.com</a>.</p>(5) Test your changes by Debugging the app.You should now see how common tags are styled by default:Additionally, if you click the “hyperlink to a second page”, Page2.html should appear:If you click the back arrow on the Phone’s face, you should be returned to index.html:When back on index.html, you hsould be able to click the Forward arrow AppBarButton on the CommandBar to return to Page2.html:While on Page2.html, you should abe able to click (1) the elipsis to expand the CommandBar, and (2) click the “home” AppBarButton (menu) to return to index.html:And finally, when you’re on index.html, you should be able to click the “hyperlink to Microsoft.com” …… and be able to navigate to Microsoft’s home page:RecapThose are the basics of using the WebViewControl and the Web View Project template.  Note that you’re not limited to just HTML and CSS, you can also add JavaScript and jQuery and I’ll demonstrate how to do that in the next lesson with a more full-fledged example featuring an interactive mini-game.
Download the source code for this lesson at http://absolutebeginner.codeplex.com/In this lesson, we’ll briefly talk about the important moments in the life cycle of your app.  Hopefully this will give you some insight as to what is going on in your app even when it is no longer running.In a nut shell, your app is either running, it is not running (terminated) or it is suspended.  What’s the difference between terminated and suspended?  When a user switches to another program, chances are likely your app will be suspended for a while until the user switches back to your app.  During this time, the app is in hibernation, in other words, the code in your app is not running, but the state of your application’s objects and variables including the Frame and its BackStack is kept in memory.  This allows the user to switch between apps quickly and fluidly.However, it is possible the Phone’s operating system will choose to terminate your app, which means it is removed from memory along with your application’s objects and variables.  This means that the next time the user launches you app, it will have no recollection of the state of the app when it last ran.  This means any work the user was doing is lost (unless you saved it), and it means that the Frame’s last page is forgotten, as is the entire BackStack.  Now, why would the Phone take a suspended app and then terminate it?  There are a couple of reasons why.  Usually this happens because it needs the RAM your app occupies.  But it could also happen if the Phone runs out of battery or the user reboots the phone.  The key is that, as an app developer, your app is notified that it is about to be suspended, however once it is suspended it is not notified about termination.Fortunately, you can handle the Suspending() event to quickly save the state of your app before it is suspended.Most of this work will happen in the App class.  The App class is implemented in App.xaml.cs.  You override those methods of the App class that you want to handle in your app.  The most important is the OnLaunched method that executes each time your app is initially launched, and the OnSuspending() method which gives you a tiny window of opportunity to save the state of the app just in case it is terminated while suspended.The App class provides a few important services that are very low level:1. It’s the entry point for the app2. It performs lifetime management, so when the user uses the physical buttons on the phone, or the operating system tells our app to go away for now, the App class implements methods that handle those events.  3. It manages app-scoped resources, not the least of which is the Frame object for navigation purposes.  More about that in a moment.  You’ll see later where I add a public property to the App class so that I can reference it throughout all pages in the app.  Also, recall from the lesson on styling your app that you can create global resources and styles by defining them in the <Application.Resources> section of the App.xaml file.4. It will also allow you to catch with unhandled exceptions in your app.The operating system provides your app a Window to display in.  Instead of allowing you to work directly with the Window, your app creates a Frame object that represents the Window, but adds navigation features … As we discussed in the lesson about navigation, the Frame object can load and unload objects that derive from Windows.UI.Xaml.Controls.Page (which each of your Pages will derive from).  It also keeps a history of all the pages that were loaded and in which order in the BackStack, an IList<PageStackEntry>.  Much of the setup work for the Window and Frame happens in the OnLaunched event handler.Ok, so honestly, there are many different ways to save your data while your app is running or prior to it going into a suspended state.  I’m going to demonstrate three easy ways to enable this.The first technique is to employ the SuspensionManager.  The second technique is to use Windows.Storage.ApplicationData.Current.LocalSettings.  The third is to use the NavigationHelper.  Now, fair warning, the SuspensionManager and the NavigationHelper are not part of the Phone API.  Instead, they are helper classes that are added to your project via a project or page template.  The Blank App template does NOT include these by default, however I’ll show you how we’ll add them into your project easily.Let’s start with using no state saving techniques just to show you what the problem is.  Then, we can use these three techniques to solve the problem.We’ll create a new Blank App project called “ManagingState”.I’ll delete the MainPage.xaml.  At this point, the project will not compile because the App.xaml.cs needs a page to load at start up.  We’ll fix that later.Add a Basic Page called Page1.xaml:When you click the Add button, you’ll see the following message box:Click “Yes”.  This will add both the Page1.xaml and a folder called \Common with a number of new files in it.  We will not use these files just yet, but soon.  Your Solution Explorer should look like this:Add two more Basic Pages, called Page2.xaml and Page3.xaml, respectively.In all three pages, add the following code inside of the <Grid> named “ContentRoot”:            <StackPanel>                <Button Content="Go To Previous Page"                     Click="previousButton_Click" />                <Button Content="Go To Next Page"                     Click="nextButton_Click" />                <TextBox Name="valueTextBox" />            </StackPanel>Also, change the TextBlock that displays the page title like so, using the appropriate name:            <TextBlock Text="page 1" Margin="0,12,0,0" Style="{ThemeResource HeaderTextBlockStyle}"/>When you’re finished, Page1.xaml should look like this in the designer:… and the other two pages should look similar.Add the following code to Page1.xaml.cs, at the very bottom of the class definition (right after a code region named “NavigationHelper registration”:    private void previousButton_Click(object sender, RoutedEventArgs e)    {      if (Frame.CanGoBack)        Frame.GoBack();    }    private void nextButton_Click(object sender, RoutedEventArgs e)    {      if (Frame.CanGoForward)        Frame.GoForward();      else        Frame.Navigate(typeof(Page2));    }In a similar fashion, add the following code to Page2.xaml.cs:    private void previousButton_Click(object sender, RoutedEventArgs e)    {      Frame.GoBack();    }    private void nextButton_Click(object sender, RoutedEventArgs e)    {      if (Frame.CanGoForward)        Frame.GoForward();      else        Frame.Navigate(typeof(Page3));    }And finally, in a similar fashion, add the following code to Page3.xaml.cs:    private void previousButton_Click(object sender, RoutedEventArgs e)    {      Frame.GoBack();    }    private void nextButton_Click(object sender, RoutedEventArgs e)    {      if (Frame.CanGoForward)        Frame.GoForward();      else        Frame.Navigate(typeof(Page1));    }Unfortunately, all of this prep work was necessary to create a viable scenario.If you attempt to run the application at this point, you’ll get an error:Double-click that entry in the Error List to go to the line of code that references MainPage which no longer exists in our app.Change this line:                if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))… to …                if (!rootFrame.Navigate(typeof(Page1), e.Arguments))and run the application.Click the “Go To Next Page” button until you reach Page 3 … you can even use the “Go To Previous Page” a couple of times if you wish just to see the Frame.GoBack() and Frame.GoForward() methods at work.Next, go back to Visual Studio and select the Lifecycle Events dropdown (which is only displayed while you are debugging you app) and select “Suspend and shutdown”.The app will terminate, you’ll leave Debug mode, and Visual Studio will return to the design time experience.Now, restart the app in Debug mode.  Notice that you will always start back on Page1.xaml.  Attempt to “Go Back”, however the the Frame.BackStack from your previous session is lost because the app was terminated and with it, all session state.We’ll remedy this easily with the SuspensionManager class.  I won’t give into the details of the class, however by inserting a couple of lines of code in the App.xaml.cs file’s OnNavigated and OnSuspending methods, we can at least get the Frame’s BackStack back.In the App.xaml.cs, in the OnLaunched() method, find these lines of code:if (rootFrame == null){  // Create a Frame to act as the navigation context and navigate to the first page  rootFrame = new Frame();Paste this line of code below them:ManagingState.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");In a nutshell, the SuspensionManager.RegisterFrame tells the SuspensionManager which object (rootFrame, the only Frame in our app) that we’ll be suspending.Next, in the OnSuspending event, find this comment:// TODO: Save application state and stop any background activity… and add this line of code:await ManageAppLifecycle.Common.SuspensionManager.SaveAsync();This will force you to add the async keyword into the OnSuspending method declaration like so:private async void OnSuspending(object sender, SuspendingEventArgs e)I devote a lesson to explaining the await and async keywords.  For now, just add the async keyword and continue on.At this point, we’ve registered the Frame with the SuspensionManager class and have called the SaveAsync() method which will save the current state of the Frame each time the app is suspended.Finally, we’ll want to Load the saved Frame when the app has terminated.  Remember: if the app doesn’t terminate, we won’t need to restore the state, but we do not get a notification when the app is about to be terminated.  Therefore, we can’t take any chances and have to save state each time the app is suspended.Back in the OnLaunched() method, locate these lines of code:if (e.PreviousExecu
Download the source code for this lesson at http://absolutebeginner.codeplex.com/We've seen the Windows Phone Emulator at work in this series.  It is a crucial component to developing apps for the Windows Phone platform, so I wanted to spend a little time becoming more familiar with it and point you in the right direction for more information.Our game plan in this lesson ...(1) We'll learn about what the Windows Phone Emulator really is, and how it supplies different versions for different deployment scenarios.(2) We'll learn about the function of the Emulator, including keyboard shortcuts that emulate device buttons.(3) We'll learn about the controls to resize, rotate and simulate the act of handling the virtual device as if it were a physical one, with accelerometer support, GPS support and more.What is the Windows Phone Emulator?In a nutshell, the Windows Phone Emulator is a desktop application that simulates a Windows Phone device, and actually provides similar performance to a physical Windows Phone device. It provides a virtualized environment in which you can debug and test Windows Phone apps without a physical device -- in fact the emulator is running Microsoft's Hyper-V.  Now, while the Emulator is great for development and quick debugging sessions, before you publish your app to the Windows Phone Store, Microsoft recommends that you actually test your app on a real Windows Phone.Choosing different versions of the Emulator for debuggingUp to now, when we clicked the Run / Debug button on Visual Studio's toolbar, we were running the Emulator in its default configuration ... something called WVGA 512MB.What does WVGA and 512MB really mean?The 512MB indicates that we're running in a memory constrained environment ...  The default emulator image in Visual Studio is Emulator WVGA 512MB, which emulates a memory-constrained Windows Phone 8.1 phone.  So, for example, the Lumia 520 is an inexpensive entry level Windows Phone 8 device (which can be updated to 8.1 with the Windows Phone developer preview program) device which sports only 512MB of RAM.  By contrast, the Lumia 1520 has a whopping 2 GB of RAM.  On lower-RAM devices, having multiple apps running at the same time or creating a memory intensive app could cause performance problems.  So, to be sure that your app will run well on lower-RAM devices you can test your app using a realistic Emulator image.There are a number of great articles about RAM usage on MSDN ... let me point out the best starting point to learn more:App performance considerations for Windows Phonehttps://msdn.microsoft.com/en-us/library/windowsphone/develop/ff967560(v=vs.105).aspxOptimizing Apps for Lower Cost Deviceshttp://blogs.windows.com/windows_phone/b/wpdev/archive/2012/03/07/optimizing-apps-for-lower-cost-devices.aspxWhat does "WVGA" as well as those other acronyms stand for?The Emulator allows you to test your app on a unique emulator image for each of the screen resolutions supported by Windows Phone.   This default selection encourages you to target the largest possible market for your Windows Phone 8 app.WVGA (800 × 480)WXGA (1280 × 768)720p (1280 × 720)1080p (1920 x 1080)If you run the default, then go to the Settings app in the About button, you can see this confirmed.How does this translate into the actual phones on the market?Lumia 1520Display Size: 6 inchDisplay Resolution: Full 1080p (1920 x 1080)Lumia IconDisplay Size: 5 inchDisplay Resolution: Full 1080p (1920 x 1080)Lumia 1020 and 920Display size: 4.5 inchDisplay resolution: WXGA (1280 x 768)  Lumia 820Display size: 4.3 inchDisplay resolution: WVGA (800 x 480) Lumia 610Display size: 3.7 ''Display resolution - WVGA (800 x 480)I realize by the time you watch this there may be newer phone models.  The point is that you should be aware of the fact that you'll need to support different screen resolutions and memory constraints.  Like I talked about in the lesson on Layout using XAML, you will want to eliminate specific pixel sizes for layout (except for margins).  Choosing from the different Emulator sizes, you can make sure you're on the right track.Working with the Phone Emulator's special featuresI'll not spend a lot of time on the phone's basic navigation.  A lot of this you'll pick up by using the Emulator throughout the series if you don't already have a physical phone in your possession.  Essentially, you'll have an almost identical experience, complete with the Start and Apps page, search, web browsing, clock, battery, etc.You have the same hardware buttons on the bottom of the Emulator as you would have on a Windows Phone.However, you'll be missing the buttons on the side of the phone.  For example, my Lumia 920 has three buttons on the side ... a volume up and down, a power button, and a camera button.  These can be access in the Emulator with keyboard function keys.There's a list of keyboard mappings here:https://msdn.microsoft.com/en-us/library/windowsphone/develop/ff754352(v=vs.105).aspx#BKMK_KeyboardMappingF6 - Camera button half-wayF7 - Camera buttonF9 - F10 raise and lower the volumeF11 - plays / pauses audio ... it simulates an in-line headphone button that pauses music and answers incoming phone calls.  If you double-tap the button, it'll skip to the next audio track on your playlist or albumF12 - Power button / lock screenF1 - Back buttonF2 - Windows keyF3 - Search buttonPAGE DOWN button - When a textbox is the target input, PAGE DOWN disables the virtualized "hardware" keyboard down, and you can use your physical keyboard for input PAGE UP button - When a textbox is the target input, PAGE UP enables the virtualized "hardware" keyboard.PAUSE/BREAK button - Toggles the keyboard, so you could just use that all the time.  In addition to the "virtualized" phone on screen, there's a floating menu off to the right.  A little experimentation will reveal that the first six buttons, in order:(1) Shuts down the emulator(2) Minimizes the emulator(3) Changes to single-finger selection mode(4) Changes to two-finger selection mode (for pinch gesture)(5) Rotates the emulator 90 degrees counter clockwise(6) Rotates the emulator 90 degrees clockwise(7) Expands the emulator to the largest size that can fit comfortably on your computer screen(8) Brings up the zoom dialog(9) This opens an MSDN page on how to run Windows Phone apps in the emulator.(10) The double chevron at the bottom opens up the additional tools dialog.There are eight tabs on the Additional Tools dialog.  The first is the Accelerometer which can be used to test apps that utilize the accelerometer sensor.(1) You can change the center point of the phone to change its position in 3D space by clicking and dragging the orange dot in the circle.(2) You can change the Orientation to one of the presets(3) You can play recorded data, like a "shake" motion.For more information about the Emulator and the Accelerometer sensor in the Windows Phone SDK, a good starting spot would be this article:How to test apps that use the accelerometer for Windows Phonehttps://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202936(v=vs.105).aspxThe next tab is the Location tab which allows you to set the current location of the phone.  So, even though I'm sitting in Dallas, Texas, I can act like I'm testing my phone in Seattle or any other place in the world.  To do this:(1) I'll perform a search for a particular location, like "Chicago, IL".(2) I'll right-click the map to create a pin in the suburb where I grew up.(3) I'll verify the exact location in the list of pins marked by their latitude and longitude.(4) I can introduce variance to the accuracy.  In some areas, there are fewer ways to determine the exact location because there are fewer physical resources (like cell towers, etc.) to use to triangulate the location of the phone.  The Accuracy profile allows you to adjust this to test your app and how it performs in various less accurate scenarios.The third tab is for creating screen shots, which can be helpful when you're creating documentation or bug reports.The fourth tab is the Network tab.  In addition to  seeing the IP address of the phone on the network (which may be helpful if you’re building some network monitoring app) but also you can throttle the phone’s network access to test your app’s performance when in bandwidth challenged situations.Fifth, you can designate a location on your hard drive that will simulate the use of the SD Card so that you can test whether your app is correctly saving or working with the file system of a removableSD card.The sixth tab allows you to simulate push notifications. The seventh tab allows you to save the current state of the emulator as a checkpoint.  This allows you to test a scenario where the phone is configured in a certain way over and over by restoring the state of the phone to a snapshot of it’s previous state.  Think: virtual machine snapshots, because that is what is happening here.Finally, the Sensors tab allows you to turn on and off certain sensors to test how your app works should it rely on one of those sensors and they don’t exist in the user’s phone.In addition to the Emulator itself, Visual Studio has a Device window with some tooling that can affect how the XAML designer displays the phone ... orientation, theme and color, chrome, etc.So as you see, you have so many ways to test and monitor your app during development time so you gain some confidence in how it will perform when you distribute it on the Store.RecapThe last tip I would give about the emulator is that it's ok to just leave it up and running during development.  There's no need to shut it down.  When you launch and re-launch your app in debug mode from Visual Studio, part of that process is deploying the latest version of the app to the phone.  It's time consuming to re-launch the Emulator each time, and Visual Studio will connect to an existing Emulator instance when it needs to.So to recap, the Emulator is a great tool that allows you to
loading
Comments