Friday, February 10, 2012

Connecting Windows Phone to Database using WCF Services

Windows Phone is a fantastic creation of the decade. The capabilities that it provides with the Mango update are really cool. One solution of a person who would need storage in Windows Phone application is either to choose the Isolated Storage or connect to an external service with a service provider like Windows Communication Foundation. If you try connecting a database to the mobile app in Android or iPhone, it will take hours for you to create the connection and get it connected. One common method in Android is to use JSON objects, which will take a lot of time.
In windows phone, it can connect with a running WCF service(may be on the web) by simply adding a service reference. This is quite simple.

First you will have to create a Solution with a WCF Service Application. I do create it named as UserService. By default, the project creates a Service named Service1 and the Interface named IService1. Delete those two files. Then right click on the project and select Add New Item. Select WCF Service under the Web templates installed. Name the service as User. Now you will get two files created as IUser.cs and User.svc. Open those two files.
Replace the DoWork Operation Contract in the IUser.cs file with coding below.
1
2
3
4
5
[OperationContract]
int CreateUser(string username, string Password,string FullName);
[OperationContract]
int DeleteUser(int RegistrationID);
In WCF, an Operation Contract defines a sort of an operation needed to be done by the Service. For this example, I took creating a new user and deleting an existing user as two scenarios.
Replace the DoWork method in the User.svc.cs
1
2
3
4
5
6
7
8
9
10
11
public int CreateUser(string username, string Password,string FullName)
{
    //Database insertion logic goes here
    return 0;
}
public int DeleteUser(int RegistrationID)
{
    //Database deleting logic goes here
    return 0;
}
Now try running the application when you are in the User.svc.cs file. Make sure you have opened that file on top, else the WCF Test client will not work. Once WCF Test client is opened, you can see two methods in the left side of the window. Once you run and give inputs to it, it returns 0. That is the set returning value. Now what we do need to do is to create a sample database and add a table to store user data.
Here I do have the App_Data folder created in the Solution explorer. Add a new database named UserDB by right clicking on the folder and Add New Item–>Data–>SQl Server Database. Then create tabel named User with columns, Username(varchar), Password(varchar) and FullName(varchar). Now lets create a simple insertion query and a connection string.
I create a new connection string in the web.config named MainConnection. Then I modify the content in the CreateUser method of User.svc.cs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int CreateUser(string username, string Password,string FullName)
{
    //Database insertion logic goes here
    ConnectionStringSettingsCollection collections
= ConfigurationManager.ConnectionStrings;
    string connectionString = collections["MainConnection"].ConnectionString;
    SqlConnection sqlconn = new SqlConnection(connectionString);
    sqlconn.Open();
    SqlCommand insertCommand = sqlconn.CreateCommand();
    insertCommand.CommandText
= "INSERT INTO UserInfo VALUES('"+username+"','"+Password+"','"+FullName+"')";
    int sucess = insertCommand.ExecuteNonQuery();
    sqlconn.Close();
    return sucess;
}
Now try the WCF Test Client and Invoke the three fields in it by giving 3 values. Then check the database. You will see the records inserted.

If it works, it does mean the WCF service ready to do perform the Database Operation. Now we do have to create the Windows Phone 7.1 Application. I do add a Windows Phone Application named UserManager to the same solution.
Once I create Windows Phone 7.1 Application, I will have to add the Service Reference to the service that I created earlier. Right click on the Windows Phone App (UserManager) and select Add Service Reference. 

Once you click on the Discover Button of the Add Service Reference window, it will automatically find the available services. Then click Ok.

Once you are done with the Service Reference, your Solution Explorer will have the two Projects completed. Since I do plan to add use the Main Page of Windows phone application as the user input window, there will not be any additional changes.
Now the easiest level comes. Its time to design the UI and add a Button click event to pass the values of three fields to WCF Service.
I simply add the following xaml scripts to the ContentPanel Grid.
1
2
3
4
5
6
7
8
9
<StackPanel>
    <TextBlock Height="30" Name="UsernameTBL" Text="Username" />
    <TextBox x:Name="UsernameTXT" />
    <TextBlock Height="30" Name="PasswordTBL" Text="Password" />
    <PasswordBox x:Name="PasswordTXT" />
    <TextBlock Height="30" Name="FullNameBL" Text="Full Name" />
    <TextBox x:Name="FullNameTXT" />
    <Button Content="Add New User" Click="Button_Click" />
</StackPanel>
Add the Button_Click method and the method that will be called once operation was completed in the MainPage.xaml.cs file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private void Button_Click(object sender, RoutedEventArgs e)
{
    ServiceReference1.UserClient sr = new ServiceReference1.UserClient();
    sr.CreateUserCompleted += new EventHandler(sr_CreateUserCompleted);
    sr.CreateUserAsync(UsernameTXT.Text,
PasswordTXT.Password,FullNameTXT.Text);
}
void sr_CreateUserCompleted(object sender,
ServiceReference1.CreateUserCompletedEventArgs e)
{
 //It replies the matchingness of credentials
    if (e.Result == 1)
    {
        MessageBox.Show("User Created Successfully.");
    }
    else
    {
        MessageBox.Show("User was not Created.");
    }
}
Now you must start both the application and Service at a single instance. To set it up, right-click on the solution, and then select Set StartUp Projects… A new windows will be created. Change the settings as available in the last image.

Now try running the applications and click the Add New User button of MainPage.xaml file. So the database will get updated. Like this, you can perform all the CRUD operations.
Solution I created for this article is available here: UserService

1 comment:

  1. I am having trouble connecting to my database from a remote wcf. I want to consume my services in my windows phone app

    ReplyDelete