Over a million developers have joined DZone.

How to use WCF services to access SQL Azure Database from Windows Phone 7 app – Part 3

· Mobile Zone
This is part three in a series of four and will step by step explain how to use WCF services to access SQL Azure Database from Windows Phone 7 app. As an example I will develop a Windows Phone app where the user can create an account and later on log in to the account by user name and password. The accounts are saved in SQL Azure and I am using WCF for communication between the WP7 app and SQL Azure Database.

The book Beginning Windows Phone 7 Development has a very detailed chapter about using SQL Azure Database.

Part 1: Signing up to Windows Azure and create your SQL Azure Database

Part 2: Creating a cloud service (WCF service) to connect to the SQL Azure Database

Part 3: Creating a Windows Phone 7 app using WCF to connect to the SQL Azure Database

Part 4: Deploying the WCF service to Windows Azure

Creating the Windows Phone project in Visual Studio 2010

Click “New project”, select the “Silverlight for Windows Phone” template, select “Windows Phone Application”, give the project a name and click “OK”.

The application we are going to make are quite simple with only two pages. The first page (MainPage) will display a login screen where the use can log in with user name and password or select to create a new account. The new account screen (AddAccount) lets the user register a new account with full name, user name and password. Please note that this application is just an example on how to use SQL Azure from WP7 app and is not the recommended way to handle login. To keep the complexity in this example to a minimum I have taken several short cuts:Passwords are sent and saved in clear text, no error handling for empty fields etc. and I’m not using a pattern (you should use a pattern like MVP or MVVM).

Adding a reference to the service you created in Part 2

Before you do this make sure that the service created in Part 2 is running. In the solution explorer right click “References” and select “Add Service Reference”. In the address field you enter the url from the browser window you got when starting the service (typically something like this: http://127.0.0.1:82/Service1.svc) , enter a name in the “Namespace” field (f.ex. CloudExampleProxy) and click “GO”. Now you should see your service in the Services windows and if you expand it you will see the operations AddUser and LoginUser which we created in part 2. Click “OK” to add the service reference.

In your solution explorer you will now see the service reference that you added.

Creating the MainPage UI

After creating the project you can see in the solution explorer that you have MainPage.xaml and MainPage.xaml.cs. We will use this class for our main page where the user can log in or select to create a new account. The UI will be created in MainPage.xaml and the code behind will be in MainPage.xaml.cs. I’m using the graphical designer to add buttons, labels and input boxes to the main page.

My MainPage.xaml code is displayed below.

<phone:PhoneApplicationPage
x:Class="CloudExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

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

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

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox Height="72" HorizontalAlignment="Left" Margin="29,124,0,0" Name="userNameTxtBox" Text="" VerticalAlignment="Top" Width="400" />
<TextBlock Name="textBlock1" Style="{StaticResource PhoneTextNormalStyle}" Text="User name" Margin="46,88,41,479" FontSize="26" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="28,231,0,0" Name="passwordTxtBox" Text="" VerticalAlignment="Top" Width="400" />
<TextBlock FontSize="26" Margin="45,195,42,372" Name="textBlock2" Style="{StaticResource PhoneTextNormalStyle}" Text="Password" />
<Button Content="Login" Height="72" HorizontalAlignment="Left" Margin="223,324,0,0" Name="loginBtn" VerticalAlignment="Top" Width="197" Click="loginBtn_Click" />
<Button Content="Create New Account" Height="72" HorizontalAlignment="Left" Margin="68,459,0,0" Name="newAccountBtn" VerticalAlignment="Top" Width="320" Click="newAccountBtn_Click" />
</Grid>
</Grid>

</phone:PhoneApplicationPage>

MainPage

Creating the AddAccount UI

We will create a page where the user can create a new account. Right click you project and select “Add”, “New Item”, select “Windows Phone Portrait Page”, give it the name “AddAcount.xaml” and click “OK”. In this page the user can create a new account with full name, user name and password.

My AddAccount.xaml code is displayed below.

<phone:PhoneApplicationPage
x:Class="CloudExample.AddAccount"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">

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

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

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox Height="72" HorizontalAlignment="Left" Margin="29,162,0,0" Name="userNameTxtBox" Text="" VerticalAlignment="Top" Width="400" />
<TextBlock FontSize="26" Margin="46,126,41,441" Name="textBlock1" Style="{StaticResource PhoneTextNormalStyle}" Text="User name" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="28,269,0,0" Name="passwordTxtBox" Text="" VerticalAlignment="Top" Width="400" />
<TextBlock FontSize="26" Margin="45,233,42,334" Name="textBlock2" Style="{StaticResource PhoneTextNormalStyle}" Text="Password" />
<Button Content="Add Account" Height="72" HorizontalAlignment="Left" Margin="223,362,0,0" Name="addAccountBtn" VerticalAlignment="Top" Width="197" Click="addAccountBtn_Click" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="30,54,0,0" Name="fullnameTxtBox" Text="" VerticalAlignment="Top" Width="400" />
<TextBlock FontSize="26" Margin="47,18,40,549" Name="textBlock3" Style="{StaticResource PhoneTextNormalStyle}" Text="Full name" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>

AddAccount

MainPage code behind

In the MainPage.xaml.cs I have placed all the logic for MainPage.  I am using the WCF service that we have referenced to LoginUser and have added an EventHandler so I know when the LoginUser request is completed.

My MainPage.xaml.cs code is displayed below.

using System;
using System.Windows;
using Microsoft.Phone.Controls;
using AudioCoach.AudioCoachServiceProxy;
using System.ComponentModel;

namespace CloudExample
{
public partial class MainPage : PhoneApplicationPage
{
private Service1Client _serviceClient;
// Constructor
public MainPage()
{
InitializeComponent();
_serviceClient = new Service1Client();
_serviceClient.LoginUserCompleted += new EventHandler<LoginUserCompletedEventArgs>(_serviceClient_LoginUserCompleted);
}

private void loginBtn_Click(object sender, RoutedEventArgs e)
{
_serviceClient.LoginUserAsync(userNameTxtBox.Text, passwordTxtBox.Text);

}

private void newAccountBtn_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new Uri("/AddAccount.xaml", UriKind.Relative));
}

private void _serviceClient_LoginUserCompleted(object senter, LoginUserCompletedEventArgs e)
{
if (e.Error == null && e.Result != null)
{

MessageBox.Show("Welcome " +e.Result +"!");
}
else
{
MessageBox.Show("Could not log in. Please check user name/password and try again.");
}
}
}
}

AddAccount code behind

The AddAccount.xaml.cs is quite similar to MainPage.xaml.cs. I have functionality to LoginUser (checks if the database have a user with the same username and password).

My AddAccount.xaml.cs code is displayed below.

using System;
using System.Windows;
using Microsoft.Phone.Controls;
using AudioCoach.AudioCoachServiceProxy;
using System.ComponentModel;

namespace CloudExample
{
public partial class AddAccount : PhoneApplicationPage
{
private Service1Client _serviceClient;

public AddAccount()
{
InitializeComponent();
_serviceClient = new Service1Client();
_serviceClient.AddUserCompleted += new EventHandler<AsyncCompletedEventArgs>(_serviceClient_AddUserCompleted);
}

private void addAccountBtn_Click(object sender, RoutedEventArgs e)
{
_serviceClient.AddUserAsync(fullnameTxtBox.Text, userNameTxtBox.Text, passwordTxtBox.Text);
}

void _serviceClient_AddUserCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("User account created. Please login");
this.NavigationService.GoBack();
}
else
{
MessageBox.Show("User account could not be added, Please try again");
}
}
}
}

Next step

We have now created a Windows Phone 7 app that consumes the WCF services we created in part 2. We can now create accounts and login users in the SQL Azure Database. The next step now is to deploy the service to Windows Azure so that we don’t have to run it locally. Part 4: Deploying the WCF service to Windows Azure.

 

Topics:

Published at DZone with permission of Per Ola Sæther, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}