Overview
This lab will provide some key learnings for Azure Mobile Services:
How to create a universal project that is designed to share code between Windows store applications and Windows phone applications
How to implement push notifications that result in toast messages appearing on the device
How to work with databases to add tables, columns, and data.
How to add code to the Windows phone application enabling you to retrieve records and display them in a list view control.
Prerequisites
The following is required to complete this hands-on lab:
A Windows Azure subscription - sign up for a free trial
A Windows Phone Developer Account
Windows 8.1 and Visual Studio 2013 Update
Exercises
This hands-on lab includes the following exercises:
Estimated time to complete this lab: 90 minutes.
Exercise 1: Creating a universal project
In this exercise, you will provision the three Windows Azure Virtual Machines used throughout the lab. Specifically you will
Task 1 - Creating a Universal Application
A universal application allows you to share code between tablet and phone applications. Visual Studio solution contains three projects. One project is for Windows 8 desktop, noteboo, or tablet-based applications. The second project is for phone applications. the third project is the shared code base between the other two.
You will create a new phone project. From the File menu, choose New / Project.
Creating new phone project
From the template pane on the left, choose Universal apps as seen below. Next, choose the Hub App template, then provide a name for your project.
Creating and naming your project.
Task 2: Adding push notifications
This task was about adding push notification capabilities into the phone application. You will end up reserving a name for your phone application. You will also modify and/or create a mobile service hosted in the Microsoft data center that supports push notifications.
Your project is now created. Your next step is to add push notification services. You will now ad support for push notifications. Right-mouse click on the phone project in solution explorer and choose ** Add / Push Notification **.
Adding push notification
The wizard will inform you about what will take place: (1) A push notification channel URI will be created. This is a mechanism used by client apps to listen for and process push notifications; (2) The phone project will also be modified with code to process incoming push notifications; (3) Your mobile services account will be modified to support push notifications. We will create a new mobile service to support this application.
Understanding the changes that will be made
You will need to sign into the Windows Phone Developer Portal. This step assumes you have an active Windows Phone developer phone account to use. If you don't have an Windows Phone Developer account, you can sign up here: http://www.windowsphone.com/account. You will now indicate a name for your phone application. This is the name that will appear in the Windows Phone store. It will need to be unique.
Reserving a phone application name
You will now create a service, meaning that a new Azure Mobile Service will be created using your Windows Azure account. This means you are signed up to use Windows Azure already.
Creating a new Azure Mobile Service
You will now provide a name for your Azure Mobile Service. You will also choose a Runtime, Region, Database, user name, and password. We will choose to Create a Billed SQL Database. Yours will be different from universal-push_notif. You can leave the default runtime of JavaScript , but you can choose your region.
Creating a mobile service
Enter a Server user name.
Providing a user name
You will now notice that your Azure Mobile Service has been created. Your name will be different.
Validing the newly minted Azure Mobile Service
You will now validate the summary page. You can see that both your phone application name as well as the Azure mobile service have been created. You are also notified here that your project source code in Visual Studio will be modified.
Viewing the Visual Studio Wizard summary
You can now see the completed project in Visual Studio.
Viewing the completed project in Visual Studio
Task 3: Testing push notifications
In task 3 you will verify that push notifications operate correctly. You will run the phone application in the emulator and verify the to see the text Sample Toast.
Right mouse click on the phone project and choose "set as a startup project."
Setting the startup project
From the toolbar run the application and the emulator
Starting the application and the emulator
Now that the application you will be able to see the toast notifications appear
Viewing the push notification and the application
The Sample Toast message will now appear.
Viewing the toast message
Exercise 2: Leveraging relational data in your application
In this exercise we will leverage SQL Server data in a phone application.
Task 1: Adding a table and inserting data
In this task we will add a table, insert a column, and then insert data.
From the left pane, select mobile services. The service we previously created was called universal-push-notif. Drill into the service by clicking on the arrow.
Drilling into universal-push-notif
You will now select data from the menu.
Selecting data from the menu
You will add a table.
Adding a table
Name the table ViewStatus.
naming the new table
You can now verify the table has been created. The next few steps will involve adding a column and then inserting some data. Click on the arrow to drill into ViewStatus.
Drilling into the ViewStatus table
Notice that the table comes with some default columns. Click columns, followed by on the add column selection at the bottom.
Adding a new column
The new column name will be statustext. Leave the default the data type of string.
Naming the new column that you are adding
You can now verify that the new column has been added. In the next couple of steps we will add data to this newly modified.
Verifying the table structure
You will now navigate to a different part of the portal. On the left menu and choose SQL database. You should see the name of your database. Mine was called universal-push-notif. Yours will be different. Click on the arrow to drill into the details for this database.
Drilling the database to enable the insertion of data
To be able to insert data you will need to manage the database. From the bottom menu select Manage.
Managing the database for data insertion
You will need to confirm that your current IP address will be added to the list of existing firewall rules, enabling your current computer to connect to the database. The developer defines which IP addresses are allowed to reach the database.
Adding a new IP address to the firewall rules
Notice that you can now build a new query. Select new query from the menu bar above.
Building a new query for data insertion
You will now type in 4 sql insert statements as seen below. Notice that the database name has been replaced with underscores where there was dashes. Select Run from the top menu bar after typing in 4 insert statements.
Typing in 4 insert statements and running them
Task 2: Adding code to view the data
The Windows Phone application already has much of the infrastructure needed to retrieve the data from the database. In this task we will add the necessary C# and XAML code to retrieve and display the data.
Open the file HubPage.xaml.cs. You will add code to connect to the database. Add the code below that will allow you to retrieve the list of records from the ViewStatus table.
Retrieving data from the ViewStatus table
At the top of the file add the following using statements.
Adding using statements
You will now perform the actual lookup of the database records. You will modify the NavigationHelper_LoadState() method. Add the code as seen below.
Adding code to perform the lookup
You will now add a collection the source, which will act as a container for the database records. The list you control that you will add in the next step will reference this collection as the source.
Adding a collection source
You will now modify the HubPage.xaml markup code. You will be adding a list view control to display the records. The complete code provided at the end of this post.
Adding code to HubPage.xaml
We will now run projects that you can test the database records getting retrieved. Run the project.
Running the project
You can now see that the records were successfully retrieved. You can also see that the sample toast message also worked.
Viewing the correct results.
Summary
This quick walkthrough demonstrated some key concepts:
How to create a universal project that is designed to share code between Windows store applications and Windows phone applications
How to implement push notifications that result in toast messages appearing on the device
How to work with databases to add tables, columns, and data.
How to add code to the Windows phone application enabling you to retrieve records and display them in a list view control.
Code Listings
HubPage.xaml | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | <Page x:Class="UniversalPushNotif.HubPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UniversalPushNotif" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}" d:DataContext="{Binding Source={d:DesignData Source=../UniversalPushNotif.Shared/DataModel/SampleData.json, Type=data:SampleDataSource}}" xmlns:data="using:UniversalPushNotif.Data" mc:Ignorable="d"> <Page.Resources> <ResourceDictionary> <ResourceDictionary.ThemeDictionaries> <ResourceDictionary x:Key="Default"> <ImageBrush x:Key="HubBackgroundImageBrush" ImageSource="Assets/HubBackground.png"/> </ResourceDictionary> <ResourceDictionary x:Key="HighContrast"> <ImageBrush x:Key="HubBackgroundImageBrush" ImageSource="{x:Null}"/> </ResourceDictionary> </ResourceDictionary.ThemeDictionaries> <!--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> <DataTemplate x:Key="StandardTripleLineItemTemplate"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Height="99" Width="99" Grid.Column="0" HorizontalAlignment="Left"> <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="99" Width="99"/> </Border> <StackPanel Grid.Column="1" Margin="12,0,0,0"> <TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}"/> <TextBlock Text="{Binding Subtitle}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/> <TextBlock Text="{Binding Description}" Style="{ThemeResource ListViewItemContentTextBlockStyle}"/> </StackPanel> </Grid> </DataTemplate> <DataTemplate x:Key="StandardDoubleLineItemTemplate"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Height="99" Width="99" Grid.Column="0" HorizontalAlignment="Left"> <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Height="99" Width="99"/> </Border> <StackPanel Grid.Column="1" Margin="12,0,0,0"> <TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}"/> <TextBlock Text="{Binding Subtitle}" Style="{ThemeResource ListViewItemContentTextBlockStyle}"/> </StackPanel> </Grid> </DataTemplate> <CollectionViewSource x:Name="viewStatusCollection" Source="{Binding Items}"/> </ResourceDictionary> </Page.Resources> <Grid x:Name="LayoutRoot"> <Hub x:Name="Hub" x:Uid="Hub" Header="application name" Background="{ThemeResource HubBackgroundImageBrush}"> <HubSection x:Uid="HubSection1" Header="SECTION 1"> <DataTemplate> <ListView x:Name="ListView2" Margin="0,0,0,4" Width="520" Height="405" Background="#FF1D1D1D" ShowsScrollingPlaceholders="False" BorderThickness="0" VerticalAlignment="Stretch" HorizontalAlignment="Left" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding Source={StaticResource viewStatusCollection}}" FontFamily="Global User Interface"> <ListView.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel VerticalAlignment="Top"/> </ItemsPanelTemplate> </ListView.ItemsPanel> <ListView.ItemContainerTransitions> <TransitionCollection> <EntranceThemeTransition/> </TransitionCollection> </ListView.ItemContainerTransitions> <ListView.ItemTemplate> <DataTemplate> <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" Background="#FF1D1D1D" Margin="5,5,5,5"> <Grid VerticalAlignment="Center" Background="#FF1D1D1D"> <StackPanel Orientation="Vertical" VerticalAlignment="Center"> <TextBlock Text="{Binding StatusText}" FontSize="14.667" FontFamily="Segoe UI" Margin="5,0,0,0"/> </StackPanel> </Grid> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </DataTemplate> </HubSection> <HubSection x:Uid="HubSection2" Header="SECTION 2" Width="Auto" DataContext="{Binding Groups[0]}"> <DataTemplate> <GridView ItemsSource="{Binding Items}" AutomationProperties.AutomationId="ItemGridView" AutomationProperties.Name="Items In Group" ItemTemplate="{StaticResource Standard200x180TileItemTemplate}" SelectionMode="None" IsItemClickEnabled="True" ItemClick="ItemView_ItemClick" ContinuumNavigationTransitionInfo.ExitElementContainer="True"> <GridView.ItemsPanel> <ItemsPanelTemplate> <ItemsWrapGrid/> </ItemsPanelTemplate> </GridView.ItemsPanel> </GridView> </DataTemplate> </HubSection> <HubSection x:Uid="HubSection3" Header="SECTION 3" DataContext="{Binding Groups[1]}"> <DataTemplate> <ListView AutomationProperties.AutomationId="ItemListViewSection3" AutomationProperties.Name="Items In Group" SelectionMode="None" IsItemClickEnabled="True" ItemsSource="{Binding Items}" ItemTemplate="{StaticResource StandardTripleLineItemTemplate}" ItemClick="ItemView_ItemClick" ContinuumNavigationTransitionInfo.ExitElementContainer="True"> </ListView> </DataTemplate> </HubSection> <HubSection x:Uid="HubSection4" Header="SECTION 4" DataContext="{Binding Groups[2]}"> <DataTemplate> <ListView AutomationProperties.AutomationId="ItemListViewSection4" AutomationProperties.Name="Items In Group" SelectionMode="None" IsItemClickEnabled="True" ItemsSource="{Binding Items}" ItemClick="ItemView_ItemClick" ContinuumNavigationTransitionInfo.ExitElementContainer="True"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Title}" Style="{ThemeResource ListViewItemTextBlockStyle}"/> <TextBlock Text="{Binding Subtitle}" Style="{ThemeResource ListViewItemContentTextBlockStyle}"/> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </DataTemplate> </HubSection> <HubSection x:Uid="HubSection5" Header="SECTION 5" DataContext="{Binding Groups[3]}"> <DataTemplate> <ListView AutomationProperties.AutomationId="ItemListViewSection5" AutomationProperties.Name="Items In Group" SelectionMode="None" IsItemClickEnabled="True" ItemsSource="{Binding Items}" ItemTemplate="{StaticResource StandardDoubleLineItemTemplate}" ItemClick="ItemView_ItemClick" ContinuumNavigationTransitionInfo.ExitElementContainer="True"> </ListView> </DataTemplate> </HubSection> </Hub> </Grid> </Page> |
HubPage.xaml.cs | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | using UniversalPushNotif.Common; using UniversalPushNotif.Data; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel.Resources; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Graphics.Display; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using Microsoft.WindowsAzure.MobileServices; using Newtonsoft.Json; // The Universal Hub Application project template is documented at http://go.microsoft.com/fwlink/?LinkID=391955 namespace UniversalPushNotif { /// /// A page that displays a grouped collection of items. /// public sealed partial class HubPage : Page { private readonly NavigationHelper navigationHelper; private readonly ObservableDictionary defaultViewModel = new ObservableDictionary(); private readonly ResourceLoader resourceLoader = ResourceLoader.GetForCurrentView("Resources"); // Add this code // An asynchronous data source that can wrap the results of a Mobile Services query // in a way that's easily consumed by Xaml collection controls like ListView, // GridView or ListBox. private MobileServiceCollection<ViewStatus, ViewStatus> viewStatusList; // Get a list of records from the ViewStatus table private IMobileServiceTable<ViewStatus> tableViewStatus = App.universal_push_notifClient.GetTable<ViewStatus>(); public HubPage() { this.InitializeComponent(); // Hub is only supported in Portrait orientation DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait; this.NavigationCacheMode = NavigationCacheMode.Required; this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += this.NavigationHelper_LoadState; this.navigationHelper.SaveState += this.NavigationHelper_SaveState; } /// /// Gets the <>"NavigationHelper"/> associated with this <>"Page"/>. /// public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } /// /// Gets the view model for this <>"Page"/>. /// This can be changed to a strongly typed view model. /// public ObservableDictionary DefaultViewModel { get { return this.defaultViewModel; } } /// /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// /// <>"sender"> /// The source of the event; typically <>"NavigationHelper"/> /// /// <>"e">Event data that provides both the navigation parameter passed to /// <>"Frame.Navigate(Type, object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited. 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; viewStatusList = await tableViewStatus.ToCollectionAsync(); viewStatusCollection.Source = viewStatusList; } /// /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <>"SuspensionManager.SessionState"/>. /// /// <>"sender">The source of the event; typically <>"NavigationHelper"/> /// <>"e">Event data that provides an empty dictionary to be populated with /// serializable state. private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e) { // TODO: Save the unique state of the page here. } /// /// Shows the details of a clicked group in the <>"SectionPage"/>. /// /// <>"sender">The source of the click event. /// <>"e">Details about the click event. private void GroupSection_ItemClick(object sender, ItemClickEventArgs e) { var groupId = ((SampleDataGroup)e.ClickedItem).UniqueId; if (!Frame.Navigate(typeof(SectionPage), groupId)) { throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage")); } } /// /// Shows the details of an item clicked on in the <>"ItemPage"/> /// /// <>"sender">The source of the click event. /// <>"e">Defaults about the click event. private void ItemView_ItemClick(object sender, ItemClickEventArgs e) { var itemId = ((SampleDataItem)e.ClickedItem).UniqueId; if (!Frame.Navigate(typeof(ItemPage), itemId)) { throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage")); } } #region NavigationHelper registration /// /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// /// Page specific logic should be placed in event handlers for the /// <>"NavigationHelper.LoadState"/> /// and <>"NavigationHelper.SaveState"/>. /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. /// /// /// <>"e">Event data that describes how this page was reached. protected override void OnNavigatedTo(NavigationEventArgs e) { this.navigationHelper.OnNavigatedTo(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { this.navigationHelper.OnNavigatedFrom(e); } #endregion } } |