This is meant to be the one-stop-shop blog post for creating a very simple web service in PHP that pulls from a MySQL database and displaying the data in Silverlight. Emphasis on the “simple”. Here is an example of the finished product (I reserve the right to clean up the data on a regular basis):
Download all files (PHP & Silverlight)
Download PHP files only
Download Silverlight project only
In Part 1, we created the MySQL tables necessary to store data for a simple to-do list. In Part 2, we wrote a PHP service to deliver the items in our to-do list in JSON format. In Part 3, we’ll create a Silverlight application that can utilize this web service to retrieve, display, and edit the to-do list.
Part 3: Connecting Silverlight To Our PHP Web Service
First, let’s start a new Silverlight project. (You can download the full project here.) In the interest of time, I’m not going to go into the details of the “ideal” implementation for this. I’m just going to show the parts necessary to retrieve, display and interact with the to-do data.
Before we start with the UI, let’s build a model so that we can appropriately bind our data. Add a new folder to the Silverlight project and name it “Models”. Add a new class to it and name the class “ToDoItem.cs”. In this instance, we’re just going to make the model look just like our MySQL table.
ToDoItem.cs
public class ToDoItem
{
public bool isDone { get; set; }
public string toDoDescription {get; set;}
public int toDoID {get; set;}
public ToDoItem() { }
}
Now, we’ll add to our MainPage.xaml a ListBox named “ToDoList” that will hold the to-do items and a Grid to house the UI to add a new to-do. We’ll work on gathering and displaying our items first.
Right-click on the ListBox and go to “Edit Additional Templates –> Edit Generated Items (ItemTemplate) –> Create Empty…”
You’ll love this part… Just add a checkbox to it. That’s all we’ll need, so that’s all we’ll add. Then, go into the XAML and make the checkbox look like this:
<CheckBox Content=”{Binding toDoDescription}”
IsChecked=”{Binding isDone}”
Tag=”{Binding toDoID}” />
This binding is all we’ll need once we gather our to-dos from the web service and attach it to the ListBox. Let’s go ahead and get that data into this ListBox.
Open MainPage.xaml.cs and, at the top of the class, add:
WebClient wc = new WebClient();
ObservableCollection<ToDoItem> myToDoList = new ObservableCollection<ToDoItem>();
string baseURI = “http://<Web_address_holding_your_php_files>”;
You may have to add “using System.Net;” and “using System.Collections.ObjectModel;” to the top of the file. While we’re adding references, right-click on the “References” folder and find the “System.Json” component and add it to the project. Then add “using System.Json;” to the references section in the top. It’ll come in handy in a minute.
In the MainPage() method under InitializeComponent(), type “wc.DownloadStringCompleted += “ and hit TAB twice. This will add an event handler for when the WebClient has finished connecting to the web service we wrote.
The resulting event handler (which should be named “wc_DownloadStringCompleted”), is the code that our application will go to whenever it makes a call to our web service and gets a result. In it, we will do the following things:
- Check to make sure we got a result without error
- Check to see what kind of result we got (did we get all to-do items? or add a new to-do item?)
- Walk through the result, extracting the data we need
- Apply that data to the UI
Let’s add the code to do that for getting all the items. Make your event handler look like this:
- void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
- {
- if (e.Error == null && e.Result!= “”)
- {
- JsonValue completeResult = JsonPrimitive.Parse(e.Result);
- string resultType = completeResult[“returnType”].ToString().Replace(‘”‘, ‘ ‘).Trim();
- if (resultType == “todoItems”)
- {
- myToDoList.Clear();
- JsonArray toDoItemsJson = (JsonArray)completeResult[“results”];
- foreach (JsonValue todoItemJson in toDoItemsJson)
- {
- ToDoItem thisTodo = new ToDoItem();
- if (todoItemJson[“ToDoIndex”] != null)
- thisTodo.toDoID = Convert.ToInt32(todoItemJson[“ToDoIndex”].ToString().Replace(‘”‘, ‘ ‘).Trim());
- if (todoItemJson[“TodoText”] != null)
- thisTodo.toDoDescription = todoItemJson[“TodoText”].ToString().Replace(‘”‘, ‘ ‘).Trim();
- if (todoItemJson[“IsDone”] != null)
- {
- int isDoneInt = Convert.ToInt32(todoItemJson[“IsDone”].ToString().Replace(‘”‘, ‘ ‘).Trim());
- if(isDoneInt == 0){
- thisTodo.isDone = false;
- } else if (isDoneInt == 1){
- thisTodo.isDone = true;
- }
- }
- myToDoList.Add(thisTodo);
- }
- ToDoList.ItemsSource = myToDoList;
- }
- }
- }
With this in place, all we need to do is make a call to the get_todo_items.php, which we can do by adding this code just below the wc.DownloadStringCompleted line in the MainPage() method.
wc.DownloadStringAsync(new Uri(baseURI + “get_todo_items.php”));
When we run the project, we should get all objects from our database and the results should show up just the way we want in our Silverlight application. We will follow the exact same model to add new to-do items and update the to-do items we already have.
I’m in the process of separating out the final part of this tutorial (adding and updating the items) into a supplemental post so that I can wrap this post up. I encourage anyone walking through this to try to complete those parts by yourself and refer to the last bit only if you get stuck.
Finally, a little bit of warning. I structured this project to get it working in as straightforward a manner as possible. It is not in any way the ideal architectural example for a data-driven Silverlight application. It’s just a good way to get started using Silverlight in an environment that isn’t 100% Microsoft technologies.