preload
Feb 13

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.

Follow me on twitter @PerOla

Share & enjoy
You can subscribe to my comments feed to keep track of new comments.

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

  1. Mark says:

    I am having problems getting this to work
    private Service1Client _serviceClient;
    the IDE does not recognize Service1Client also I am having problems finding anything to reference : using AudioCoach.AudioCoachServiceProxy;

    Thanks

  2. Hi Mark,
    To be able to use the Service1Client you must add a reference to the service as described in this post.
    You need to do the following steps:
    1. Create and deploy (or run locally) a WCF service
    2. Add the service created in step 1 as a service reference in your Windows Phone project
    3. Use the referenced service in your Windows Phone project.

    Hope this helps you a bit further on.

  3. Kris says:

    Hi,

    I’m having an issue with the _ServiceClient.AddUserAsync and _ServiceClient.GetUserListAsync where it is giving me an error:
    No overload for method ‘AddUserAsync’ / ‘GetUserListAsync’ takes 3 / 2 arguments.

    I have tried both retyping out all the code and direct copy paste, yet I still get this one error.

    Could you possibly advide me as to what I have done wrong here.

    Thanks,

  4. Hi Kris,

    It is hard for me to give you any direct advice based on the info you provided. You should go back to part 2 and check the WCF contract you created. You need to call these methods with the same arguments as defined in the WCF (service).

    Good luck!

  5. jun says:

    Hi
    It cant recognize this…
    using AudioCoach.AudioCoachServiceProxy;

    what can i do?

    Basically, i have done the steps for
    1. Create and deploy (or run locally) a WCF service
    2. Add the service created in step 1 as a service reference in your Windows Phone project
    3. Use the referenced service in your Windows Phone project.

  6. jun says:

    Hi ,

    there is a problem occur when i click on the login button

    {“The EntitySet ‘myUser’ is not defined in the EntityContainer ‘trial1Entities’. Near simple identifier, line 1, column 50.”}
    any suggestion?

  7. Jon says:

    Hey Per, the article is very good…..but yet i still encounter some problems…
    Basically, how we going to add the reference of “AudioCoach” so that we can use the reference….
    And what is the purpose of adding the AudioCoach?

  8. Hi Jun and Jon,
    I now see that the code I pasted are using a reference to AudioCoach, this is my fault. I changed the code to a real life project and by mistake pasted that code.

    You should just use the service reference that you have added (explained in the beginning of this article). The AudioCoachServiceProxy was just the name I gave my service. So just reference the service you have created and named.

    Sorry about this mistake, hope you will get a step further now.

  9. Jon says:

    Hi Per,
    Thank you for replying…Now i have done all four parts….
    Sorry i’m stil new in windows phone and windows azure….
    i encounter some problems in invoking the service for LoginUser. I used WCF test client to invoke the LoginUser service and now i’m having the following error…

    The EntitySet ‘User’ is not defined in the EntityContainer ‘Entities’. Near simple identifier, line 1, column 42.

    is it any coding problem with the LoginUser function?

  10. Bharat says:

    I tried to add a reference to my WCF service which is deployed on Azure. But there is an error on detection of the service when I click on ‘Go’. The error is ‘Content Type UTF-8 not supported…Binding Mismatch’. I’ve tried changing the bindings but still no success.
    The service runs perfectly well locally but on Azure, this issue comes up.
    Any help would be great.

  11. Hi guys,

    It has been quite a while since I did this now and unfortunately I do not have the answer to your issues. The tutorial should work if you follow it step by step, maybe try starting from scratch again?

  12. Kenneth says:

    Hi Jon, I.ve been looking whole day…
    instead of this as the query in part 2
    @”SELECT value User.FullName FROM CloudExampleEntities.User AS User WHERE User.UserName = @username AND User.Password = @password”;

    Change it to this, notice the User>Users
    The database table name and entity name may not be the same. For instance; if you are using ADO.Net the default settings; table names in the database are generated with a “set” or an “s” suffix.

    @”SELECT value User.FullName FROM WCFExampleEntities.Users AS User WHERE User.UserName = @username AND User.Password = @password”;

  13. Kgosi says:

    Hi Per

    I successfully hosted the service on Azure and managed to test if the service works with the Wcf Test Client and it worked perfectly. I don’t know if it’s VS2012, when I add the service reference in the Windows Phone app, it does pick up the service, all well and good. But as soon as when I try to create an instance of the service, intellisense doesn’t recognise the service. Please help.

  14. Kgosi,

    This sounds a bit odd. Unfortunatley I can not help you much on this issue. The article is 2 1/2 year old so I guess some implementation details might have changed.

  15. Kgosi says:

    Managed to fix the problem. I created the project in .NET Framework 4.5. I think that was the problem. But thank you for replying.

  16. Kgosi,

    I am glad to hear that you were able to fix the problem.

    Cheers

  17. Tangela says:

    Hi,Everyone should listen to this call over and over. I have learned so much from this and can’t wait to put it into practice over the next few days. In the past I have been so guilty of biting the pro#uct&d8217;s hook rather than the prospect bite mine!You certainly are a mind reader Dani. My posture has obviously fluctuated. This is something I will be working on.Thanks again

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

Leave a Reply

Subscribe to my comments feed

Subscribe to my feeds Follow me on Twitter
DZone MVB