Creating a WebService with WebMatrix and Consuming it with a Windows 7 Phone Application

In this tutorial you will see how to create a Web Service with WebMatrix and a Windows 7 Phone App that will consume your Web Service. Microsoft WebMatrix is a free tool that allows you to create, customize and publish web sites on the Internet.

This may sound like a daunting task but with WebMatrix and the Windows Phone Developer Tools, this task can be easier. WebMatrix makes it easy to create websites and web services. Before you start, you must download and install WebMatrix and the Windows Phone Developer Tools.

Create a Website with WebMatrix

If you are having problems installing WebMatrix, step by step instructions can be seen in Getting Started with WebMatrix. Steps for downloading and installing the Windows Phone Developer Tools can be seen later on in this article.

Once you launch WebMatrix, you'll see the Welcome Screen. Here you have many options on creating your website. For this tutorial, we will be using an Empty Site template. Click the "Site from Template" option.

Here you will see all of the template options WebMatrix gives you. Click the "Empty Site" template and give your site a name.

Clicking "OK" will cause WebMatrix to create you new website. You will be taken to your Workspace. This contains information about your local host as well a provides resources on developing your site.

You’ll notice that WebMatrix allows you to move between different workspaces by selecting the buttons on the left hand side. At present the Site button is selected which gives you details on your web site, such as the URL of the site, and other tools that you can use such as monitoring your site requests. You can look into this workspaces as you work but for this article, we will be working with our Files workspace. To get to your Files workspace, click the “Files” tab on the lower left hand of WebMatrix.

Once in your Files workspace you can see all your files. Since we chose the Empty Site template, we do not have any files. Let’s create a new file for our website. The "new" button on the menu ribbon allows us to create new folders and files for our website.

Since we are creating a web service we will need to create a class that will supply data. Similar to ASP.NET, the App_Code folder contains classes. Since we chose to create an Empty Site, our site does not contain an App_Code folder. Certain templates come with this folder but the Empty site template does not. Create a new folder and name it App_Code.

Any file in our App_Code folder can be accessed by FileName.FunctionName(Parameters). This means that we can create functions in our class and can call them in other files.

Create a Database

One of the ways to use a Web Service is to pull data from a database. Our Web Service will retrieve information from our database. Before we can write this code, we must first create our database. One of the nice things about WebMatrix is the fact that we can create and insert data into our database, all within WebMatrix.

Creating a WebMatrix is easy. Click the "Database" workspace on the lower left of WebMatrix. Here you can manage your databases or create new ones.

Once in the Database Workspace, you can create a new database by clicking the "new database" button on the menu ribbon or by clicking the "add database to your site" link in the middle of the page.

WebMatrix will create a new database for you with the same name of your website. This database can be seen in the files explorer on the left.

Now that we have our database set up, we can create a new table. On the menu ribbon, select "new table." If the icon is not able to be selected, make sure the database is selected on the left.

If you have any prior experience with databases, you may know the best practices for structuring your tables. For this tutorial, we will be using a simple Product table with three columns: id, name, and price.

Click the "new table" icon. Here we can enter our table's columns. The first column we need to make is the id column. Since it's not really necessary to have an id in such a basic table, you do not have to include this but it is best practice to include ids.

After you've added the id column, add a Name column and a Price column. Name should be an nvarchar and Price should be an int. When you've added all of your table columns, you database table should look similar to this.

Save your table and give it a meaningful name. Your table will appear on the left under your database.

Now we can add data to our database. You can either double click on the table on the file explorer, or if your table is still open, you can click the "data" icon on the menu ribbon. Either method will take you to your empty table.

Here you can enter information into your table. Once you're done, your table should look similar to this.

Now that we have our database with our product table and data we can get started writing our web service code. Click the "files" tab on the lower left to get back to your files workspace.

Create your Web Service

A web service is a communication between two different devices. One device sends a request to the other device and receives a response. The device then uses the received response to do something. This request is done in the form of an url. This url consists of the web services' address and parameters to request certain information from the service. Services can be based on XML or Json responses. For this tutorial we will be dealing with Json responses since WebMatrix has a nifty built in Json encode and decode helper.

Our Web Service will consist of two different .cshtml files. One file, which will go into our App_Code file, will contain our class and function that retrieves data from our database. Our other file will be the file that will receive the web request and will return the information. This file will call our function from the other file. This may sound kind of confusing but it will become more clear as we go along.

Firstly, we need to create our class and function. Make sure your App_Code folder is selected and create a new .cshtml file.

With your new file open, remove all of the <html> tags. These are not needed in our file. Add to your now empty file:

@functions {

}

This is the way to signify that this code contains functions with Razor code. Code between these {} brackets will be treated as a class or function. Now let's add our class. Our web service is going to get information about a product from our database. This means that we should create a Product object. Since our database is super simple, our product will only have 2 attributes: name and price. We can create a very simple, succinct Product class in our file. Within the @functions {} brackets, add:

    public class Product {
        public string Name {get; set; }
        public int Price {get; set; }
    }

Now that we have our Product object, let's create our function that the requests product information from our database. This function will open our database, query our database, and place the information from our database into our product object. We then return our product object.

Add to between @functions{}:

    public static Product GetProducts(string price) {
        var db = Database.Open("WebService");
        var selectQueryString = "SELECT Name, Price FROM Products WHERE Price >= " + @price;
        var data = db.Query(selectQueryString);
        Product product = new Product(); 
        foreach (var row in data) {
            product.Name = @row.Name;
            product.Price = @row.Price;
        } 
        return product; 
    }

We must loop through the rows in our sql response in order to place our values into our product object. If we don't then we are simply returning an empty Product object. Also, you cannot implicitly convert a sql statement into a product. Looping through the response allows us to capture the row values and place them into our product object.

Now that we have our product class and getproduct function, we can write the code that will deal with the web request. Having our function call in this page will allow users to make requests to the file's url.

One important thing we need to do in this file is to convert our product object into a format that can be consumed by other devices, especially a Windows 7 Phone application. We can do this by calling our getproduct method which returns our product object. We can then use WebMatrix's json helper to encode our product response to a json format and print it out on our webpage. You may have noticed that our getproduct function takes in a string parameter of price. This means that we must supply a price variable or we will not get any results.

Create a new .cshtml file in the root folder of your website. You can take out all of the default html code. Add to your file:

@{
        var price = Request.QueryString["price"];
        if (price == null || price == string.Empty) {
            <p>Please enter a Price value</p>
        }  else {
            var product = getProduct.GetProducts(price);
            Json.Write(product, Response.Output);
        }
}

The price variable will contain the requested price in the url. There is code to handle a missing price variable so our code will compile properly. This means that if the price variable is not supplied, the user will receive a message instead of an error page. If a price is supplied, we call our getproduct function with our price variable and store the return product object into a variable. We then use the WebMatrix json helper to encode our product object to the json format and print it to the page. We could use the json encode method but since we want to encode and write to a response stream, we can simply use the Json.Write method. If another device makes a request to our page they will receive a json formatted string which can be decoded.

Now that we have our simple web service, we can either make requests in the browser to this page or we can use another device to make requests. First, let's try out our service in the web browser to make sure it is working properly. Run your file by clicking "run" on the menu ribbon. Because we are running it this way, we won't be supplying a price variable. Our page should display our error message.

Now we can add our price variable by adding ?price=number. If I were to enter http://localhost:22769/jsonRequest.cshtml?price=12 then my page should print out the json object.

Now that we have our web service working we can begin working on our Windows 7 Phone application.

Download the Windows 7 Phone Development Tools

Microsoft offers some great resources to get started on developing Windows 7 Phone applications. For this tutorial we will be using the Visual Studio 2010 Express for Windows Phone software. This can be downloaded for free at create.msdn.com/en-US.

create.msdn.com/en-US Also offers great resources on getting started developing phone applications. If you are an absolute beginner it provides a wonderful set of videos to get your orientated with the software and coding for a phone application. I strongly suggest checking out some of these videos before you continue on with this tutorial as we use some of these concepts.

To download the development tools, click the three links near the middle of the page on the create.msdn.com/en-us/home/getting_started page. Listed here are the three different downloads you must complete in order to use the software package.

Clicking on the first link you will be asked if you wish to run or save the file. Choose to run it.

Next you must agree to the license terms. Click the "accept" button.

Once you agree you will be asked to install now or customize the installation settings. Choose "install now."

The software will begin installing. This may take more than a couple minutes.

Once that is completed you will need to install the January 2011 Update. A dialog will pop up. Once it is finished downloading it will close automatically.

After that is done you must download and install the Windows Phone developer tools fix. Clicking the link will open the installation wizard. Click the "next" button to continue.

You will be once again asked to agree to license terms. Select the check box and click the next button. You will not be able to continue on until the box is selected.

The tools fix will begin installing. This also may take up to a few minutes to complete.

You will be notified once the installation is complete. Click the "finish" button to close the installation wizard.

With all these components installed we are now ready to begin working on our Windows 7 Phone application.

Build your Windows 7 Phone Application

Now that we've easily created our web service, let's see how easy it is to create a phone application that consumes this service. Silverlight has a class called WebClient that allows use to easily make HTTP requests and receive responses. We can then use the DataContractJsonSerializer class to decode our web response. But, before we write our code behind, let's add some elements from the toolbox to our phone application.

First things first, open Visual Studio 2010 Express for Windows Phone and create a new Windows Phone Application project. Give your project a name and hit ok.

You will now have a new phone application project. Your project .xaml file will be open. This is the front facing code of your project. A nice thing about this software is that you can click and drag elements from the toolbox onto the windows phone. This way you can add, edit and remove features on your application without having to write the code for it.

Let's give our application a title. To do this we can remove the "page name" text and add our own. To do this click on the page name text. This will select the textblock that contains the text.

With the textblock selected, we can now change the text. You can change the text in the properties window.

Now let's add some elements to our application. Let's add a text block, a text box, a button, and another text block. You can have these arranged any way you wish on your phone. We will use the first text block to print some text instructing the user what to do. We will use the text box as a way for the user to enter input. We will use the button to fire an event when it is clicked by the user. We will use the last text block to print out our json web response that we have decoded. With all these elements on your phone, it should look similar to this:

Now that we have all the elements we need, let's create some code behind. First, let's add our event when the button is clicked. You can quickly do this by double clicking on the button. This will open the open behind and make the button event for you. Your code behind can be found in the .xaml.cs file of your project.

Since we are going to use a stream object as well as the json serializer class, we need to add these namespaces to our project. To use the json serializer we need to add a reference to our application as well as the namespace. To do this, right click your application root in the solution explorer on the right. Select "add reference" on the menu.

Clicking add reference will open a pop up box with all the different references that we could add. Choose the System.Servicemodel.Web option. Click ok to add the reference to your application. If you were going to use XML instead of json you would use the System.Runtime.Serialization reference.

All of there references in your application can be found under the "references" folder in the solution explorer. Now let's add the namespaces to the top of our code behind file. Add to your file:

using System.Runtime.Serialization.Json;
using System.IO;

Now let's add our web request code. Firstly, let's add our WebClient as a global variable. At the top of the page, directly after public partial class MainPage : PhoneApplicationPage {, add:

WebClient productClient;

Now we have our WebClient as a global variable but we still need to initialize it before we use it. We could place our WebClient in our page so it made the request as soon as the page loaded but since we want to add user input to our web request, we should make our request on the button click event.

Add the following code to your button_click event:

        public void myButton_Click(object sender, RoutedEventArgs e)
        {
            int num;
            if (myTextBox.Text != string.Empty && int.TryParse(myTextBox.Text, out num))
            {
                string price = myTextBox.Text;
                productClient = new WebClient();
                productClient.OpenReadCompleted +=
                new OpenReadCompletedEventHandler(productClient_OpenReadCompleted);
                GetProduct(price);
            }
            else
            {
                myTextBlock.Text = "Please enter a valid price. This number should be an integer.";
            }
        }

Our code first checks if the button was clicked and the text box was empty. If the user did not enter text into the box before clicking the button, our second text block will prompt the user to enter a price. If they did enter text and the text was an integer (we use the TryParse method to check this), then we place the text they entered into a variable. We then initialize our WebClient. We also attach an event handler to our OpenReadCompleted event. We do this so that we can make our web request without blocking the rest of the application. This is a good practice to use in case your web request runs into an error. When our request is completed our event handler will be called. We then call the method that makes our web request. Let's add that method now.

        private void GetProduct(string price)
        {
            string requestUri = "http://localhost:22769/jsonRequest.cshtml?price=" + price;
            Uri uri = new Uri(requestUri);
            productClient.OpenReadAsync(uri); 
        }

Our GetProduct method creates a string that we will use as our request uri with the value the user has entered into the textbox. We then create a uri object with our request string. With our request uri assembled we make a class to the OprenReadAsync method of our webclient object.

We now need to write our OpenReadCompleted method that we called earlier in our code. This method is where we will receive our web response, deserialize our json response and print out our response to our second textblock. Add to your page:

void productClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                myTextBlock.Text = "An Error Occurred";
                return;
            }
            var serializer = new DataContractJsonSerializer(typeof(Product));
            var s = (Product)serializer.ReadObject(e.Result);
            string name = s.Name;
            string price = s.Price;
            if (name == null)
            {
                myTextBlock.Text = "There is no product with a price equal or greater than " + myTextBox.Text;
            }
            else
            {
                myTextBlock.Text = "Our " + name + " is $" + price;
            }
        }

The first thing we check in our method is whether we received any errors during our web request. If we ran into an error, we print an error message in our textblock. If all went well with the web request we can deal with our response. We first create a new DataContractJsonSerializer with the type of set to a Product object. You may be getting red squiggly lines under this part of your code because we haven't added our Product class yet. This class will be the same class that we had in our WebMatix code. We will add this next. We then use our serializer to read and decode our json web response, which we store into a variable. We then set the name and price variables of our Product object equal to the information we received from our web response. We next check if we actually received valid data from our response. If the user enters a number that doesn't match any of our database data, our web response will return an empty name and a price equal to 0. We can easily check if this was the case. If it is true, we print out a message to our textblock. If our response contained good information we then print out our information to our textblock.

The last thing we need to do is add our Product class. This is really simple to do. Add to your file:

        public class Product
        {
            public string Name { get; set; }
            public string Price { get; set; }
        }

That's it! That's all the code we need to consume the web service we created with our WebMatrix application. Let's debug our phone app to make sure it is working properly. Make sure "Windows Phone 7 Emulator" is select on the toolbar. To run your app click the green triangle.

Your app will now run. The Windows 7 Phone Emulator will open. If it is not already open it make take a minute or two before it's ready. The Emulator acts as if you are using your live app.

You can submit a blank textbox, enter a string, or enter a number to see if your app is working properly. You should see the corresponding message to whatever action you choose. If we were to enter 9 then our app would look like this:

So that's it. We successfully create a web service with WebMatrix and created a Windows 7 Phone application that consumes our web service. Although this was a very simple approach, understanding the fundamentals is important to creating bigger, more complex applications.

Additional Resources

Download webmatrix http://www.microsoft.com/web/webmatrix/

Learn how to Download and Install WebMatrix http://www.microsoft.com/web/post/web-development-101-part-1-getting-started-with-webmatrix

Learn more http://www.microsoft.com/web/post/Web-Development-101-using-WebMatrix

Create a website with a WebMatrix site template http://www.microsoft.com/web/post/create-a-website-from-a-webmatrix-site-template

Publish your website http://www.microsoft.com/web/post/how-to-publish-a-web-application-using-webmatrix

Learn to download, edit and republish your website http://www.microsoft.com/web/post/download-edit-and-republish-your-website-with-webmatrix

Learn more about Windows Phone development http://create.msdn.com/en-us/education/quickstarts

You can discuss this article using the adjacent Facebook talkback.

For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!