Archive for the ‘Tutorial’ Category

Tutorial: Logging Into Facebook with Windows Phone 7 (Silverlight)

No Comments »

So, you want to use Facebook to sign into something or in some way integrate Facebook with your Windows Phone 7 app. You are in luck because it is almost hilariously easy.

I’ve uploaded this tutorial as a zip file. I tried to github it, but I’m inching up on 1 hour of trying to figure out what the hell I’m doing wrong.

Download this Tutorial Project

I’ve tried to make this a full featured tutorial, so if you just want to get to the code, head down to the “Let the User Login To Facebook” section.

Get Your Facebook Key

Go to http://developers.facebook.com and log in with your Facebook account. Give them the permissions they need and go to the “Apps” tab. Click on “Create new App”

Fill in the App Display Name and the App Namespace and do the verification. Then you’ll get to a page that gives you your App ID and App Secret.

image

Don’t worry about anything else here… you don’t need to select anything in the “how your app integrates with Facebook” section to do this tutorial. If you’re using Facebook integration to do some basic login and simple posting, you could probably just use the Website option.

Also, click the “Graph API Explorer” on the left and keep that open. We’ll come back to that in a moment.

Add Facebook C# SDK

Download the Facebook C# SDK and extract it. Go to the “sl3-wp” folder and unblock the Facebook.dll file (right-click => Properties=>click “Unblock”)

Open up your project (for the example, I used the Visual Studio 10 “Windows Phone Databound Application” template) and right-click on “References => Add References…”. Click “Browse” and navigate to the Facebook.dll and add it to your project.

Build Facebook Login UI

We’ll do this quick here (no MVVM, no bindings) but in later versions I’ll integrate this into a more formal project.

Open your project in Blend. For this quick-and-dirty tutorial, we’ll just add another page title and another panel for the UI we want to show when the user is logged in and set the Visibility to Collapsed on those. Our visual tree should look like this.

image

In our loginPanel, we’re going to add a button and a WebBrowser to our panel. Set the button (containing “sign in using facebook” in the content) to the top and the WebBrowser to fill the panel. For a little flare, I’m going to add “ShowFacebookLogin” and “HideFacebookLogin” animations. My login screen now looks like this (the WebBrowser will animate in when we press the button).

image

When we get our data back, we’re going to tell the user it worked by showing their name and their Facebook avatar. So we’ll add a Grid with an Image and a TextBlock to display the user, along with a friendly “Hello”. (Make sure to name all these things so that we can update them from the code.)

OK… out UI is simple, but ready to roll. Now let’s do something when the user clicks the sign-in button. Go to the “Click” event and add a method like “StartFacebookLogin”.

image

Let the User Login to Facebook

Add “using Facebook;” to your references at the top of your MainPage.xaml.cs file. Now, add the following properties:

private FacebookClient _asyncFbClient;
private string _appID = "get from your facebook app page";
private string _appSecret = "get from your facebook app page";

Now go to your StartFacebookLogin method and add the following (explained at the end).

private void StartFacebookLogin(object sender, RoutedEventArgs e)
{
    string[] extendedPermissions = new[] { "user_about_me", "publish_stream" };

    var oauth = new FacebookOAuthClient { AppId = _appID, AppSecret = _appSecret };
    var parameters = new Dictionary<string, object>
                    {
                        {"response_type", "token"},
                        {"display", "touch"}
                    };
    if (extendedPermissions != null && extendedPermissions.Length > 0)
    {
        var scope = new StringBuilder();
        scope.Append(string.Join(",", extendedPermissions));
        parameters["scope"] = scope.ToString();
    }

    var loginUrl = oauth.GetLoginUrl(parameters);
    webBrowser.Navigated += new EventHandler<NavigationEventArgs>(CheckForAuth);
    webBrowser.Navigate(loginUrl);
}

Remember how I told you to keep the Graph API open? Here is why. It has a big list of all the extendedPermissions that you can tell Facebook you want from the user. Here, we’ve asked for basic user information and the ability to publish to the user’s stream. Ask for only the permissions you need. The user can see the details of your permission request and may reject it if you ask too much.

Next, we create our OAuth client using out AppID and AppSecret and create a Dictionary of parameters communicating to Facebook the details of our request (for example, setting “display”, “touch” tells Facebook that we want the mobile interface.

We write out permission request into our parameters and then get a login url, which we will direct to our webBrowser. Here is what we will should get.

image

At the point Facebook walks the user through their login and, when they are done, it hands us back the access token we’ll need to get the user info and let the user make posts through our app.

This is why we attached the CheckForAuth event handler to our webBrowser. When we navigate to a new page, we’ll check to see if we got an access token using this code:

private void CheckForAuth(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    FacebookOAuthResult result;
    if (FacebookOAuthResult.TryParse(e.Uri, out result))
    {
        if (result.IsSuccess)
        {
            IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
            if(Settings.Contains("MyFacebookAccessToken"))
                Settings["MyFacebookAccessToken"] = result.AccessToken;
            else
                Settings.Add("MyFacebookAccessToken", result.AccessToken);
            Settings.Save();
            _asyncFbClient = new FacebookClient(result.AccessToken);
            _asyncFbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(_asyncFbClient_GetCompleted);
            _asyncFbClient.GetAsync("/me");
        }
    }
}

If the Uri does contain a Facebook OAuth result and it is a success, we save the access token to our settings and then immediately use it to get the most basic user information.

The problem we have right now is that we have no class to structure the data that comes back. So get that all squared away.

First, right-click on “References” and select “Add Reference…”. Select “System.Runtime.Serialization”.

Next, add a class to your project (I added mine in a folder called “Models”) and name it FacebookUser.cs.

image

In that class, add the following code

[DataContractAttribute]
public class FacebookUser
{
    public FacebookUser() { }

    private string _id;
    [DataMember(Name = "id")]
    public string ID
    {
        get { return _id; }
        set { _id = value; }
    }

    private string _name;
    [DataMember(Name = "name")]
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
}

The sample project has a much larger (although still incomplete) version of this model. But this one will do for our purposes.

We’ll make our “GetCompleted” event handler (remember that?) look like this:

void _asyncFbClient_GetCompleted(object sender, FacebookApiEventArgs e)
{
    FacebookUser _fbUser = e.GetResultData<FacebookUser>();

    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        fbName.Text = _fbUser.Name;
        BitmapImage bi = new BitmapImage(new Uri("https://graph.facebook.com/" + _fbUser.ID + "/picture"));
        fbAvatar.Source = bi;
        HideFacebookLogin.Begin();
    });
    _asyncFbClient.GetCompleted -= _asyncFbClient_GetCompleted;
}

What we’ve done here is shove our data into a FacebookUser model. Then we use BeginInvoke to bring ourselves back to the UI thread and set all the properties we want.

Finally, we start the animation that hides the login data and shows that our Facebook login was a success.

Boom!

image


Windows Phone 7 Push Notification For Beginners–The Device

2 Comments »

OK… it’s been almost 2 months since I tried to start this series and now I’m going to finish it. A brief warning: this is done with pre-Mango bits so it won’t have all the latest, greatest most exciting things like the back-tile functionality or deep linking. (Here’s a good blog post on all that.) But it remains a good introduction.

Windows Phone 7 Push Notification Project Files (github)

The goal of this post is to provide a sample Push Notification application that is

  • easy to test
  • good architecture
  • provides a sample web app for testing your push code (part of the delay has been because I’ve been trying to be a perfectionist on that web app. I’ve decided I’m never going to get around to making it perfect so this is the best I can do with the time I have)

Too many of the sample apps I’ve seen shove the push notification code in the xaml code-behind, leaving it to us to separate out the bits and translate it into a real project. This project uses MVVMLight binding and an event-driven architecture to get the push stuff working.

So… let’s dig into it.

I created a class called PushNotificationService that held a number of helpful little variables and objects. The most important variable here is

private static string _pushChannelName = "SampleAppNotification";

This name will delineate our push service from other services. If something weird happens and your push service stops working, the first thing you should do is change this string.

Next, we have a method that allows us to control when we get the push notification Uri. As an overview of what we’re doing,

  1. See if we already have a valid HttpNotificationChannel (the object that will control the push permissions and handle information from the Microsoft Push server)
  2. If we do have a valid HttpNotificationChannel, make sure we got the channel Uri correctly (the uri we will send out push notifications to). If we did, SUCCESS! Otherwise, go to step 3.
  3. Set the event handlers so we can handle when we get a new channel Uri back from the Microsoft Push server.
  4. Ask the Microsoft Push server for a new channel Uri.
  5. Set the HttpNotificationChannel up to handle the right kind of push notifications.
  6. Handle the returned uri from the Microsoft Push server & send it to the rest of the app.

Step 1

_notificationChannel = HttpNotificationChannel.Find(_pushChannelName);

Step 2

if (_notificationChannel.ChannelUri != null)
{
      // Success! We run the event to send that info back to our ViewModel 
      RaiseGotPushUri(_notificationChannel.ChannelUri);
}

Step 3

else
{
    _notificationChannel = new HttpNotificationChannel(_pushChannelName);
    _notificationChannel.ChannelUriUpdated +=
         new EventHandler<NotificationChannelUriEventArgs>(_notificationChannel_ChannelUriUpdated);
    _notificationChannel.HttpNotificationReceived +=
         new EventHandler<HttpNotificationEventArgs>(_notificationChannel_HttpNotificationReceived);
    _notificationChannel.ErrorOccurred +=
         new EventHandler<NotificationChannelErrorEventArgs>(_notificationChannel_ErrorOccurred);
}

Step 4

_notificationChannel.Open();

Step 5

BindNotifications(_notificationChannel);

Binding Details

In the pre-Mango push notifications, there are 3 kinds of push notifications and we have to announce what kind of notifications we plan on handling.
First, there are toast notifications, which look like this (stolen from Shawn Wildermuth):
image

Toast notifications consist of

  • a title (“Toast Message” in the example above)
  • a message (“This is from the server”)

To bind them, we simply type:

_thisChannel.BindToShellToast();

Tile notifications will only show up if the user has pinned the application to the front application tile board on the phone. I like to split Tile notifications into two types because we have to handle them differently in the code.

The first kind of tile notification is what I call “simple” Tile notifications. With simple Tile notifications, we can change a number and title on our app tile. The new title will show up where the title always shows up (at the bottom left) and the number will show up in a black circle at the top right.

image

Doing this much is simple:

_thisChannel.BindToShellTile();

But then there are Live Tiles, which allow us to send a whole new image to the tile to change it in a more holistic way to represent some push data. (We can still update numbers and titles too.) Live Tiles, however, require that we whitelist all the websites that might want to send an image to our phone. So we need to create a collection of whitelisted domains and add that to our tile binding.

System.Collections.ObjectModel.Collection<Uri> permittedImageHosts = new System.Collections.ObjectModel.Collection<Uri>();
permittedImageHosts.Add(new Uri("http://www.designersilverlight.com"));
_thisChannel.BindToShellTile(permittedImageHosts);

If you’re going to use my handy-dandy WP7 Push Tester, make sure you whitelist the exact domain above.

And that’s it… that’s all we need to do to get everything bound and ready to go! All we need now is to get the Uri from the Microsoft Push server so we know where to send our Push Notifications to.

Step 6

void _notificationChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
      RaiseGotPushUri(e.ChannelUri);
}

This will run when we get the updated Uri back and we just send it in our event, which the ViewModel is listening to.

I’ve really streamlined the code in this blog post to deal with just the bare essentials. If you want to look at the project in detail, you can download it here.

Now, all we have to do is start testing it.

You can test it using my WP7 Push Notification web app. I’m also working on another post that walks through creating a push notification system using PHP, but in the meantime you might want to check out this PHP library that I used.


Using WrapPanel and DockPanel in Windows Phone 7 With Blend

5 Comments »

I’m currently working on porting the run-away hit mobile application ShopSavvy to Windows Phone 7 (sign up to be a beta tester) and one of the things I really wished I had was the WrapPanel.

(For those who are new to Silverlight/WPF/Windows Phone 7, the WrapPanel stacks UI elements either horizontally or vertically like the StackPanel except that, when it hits the panel limit it… wait for it… wraps and starts stacking in a new column/row. Handy.)

I found a way to add it with the Silverlight Toolkit, but doing that added 140 Kb to my application. Maybe I’m just stuck in the world of J2ME, but adding 140 Kb to my mobile app isn’t OK if I can help it. I found this post from Jeff Wilcox on adding the WrapPanel and that didn’t seem to work for me. (My comments are the whiny ones at the end of the post.)

But I finally got it working and I’ll tell you how.

Or I could just taunt you. That would be fun too.

Naw, I’m just kidding. Here’s the stuff you need.

Windows Phone 7 WrapPanel and DockPanel (Source)

Windows Phone 7 WrapPanel and DockPanel (DLL)

All you have to do is download the DLL, unzip and reference in your app like so:

Right click on the “References” section of your project.

image 

Select the WP7Panels DLL from whatever folder you put it in and see it show up in your References

image

Open up the “Assets” section and type “wrap” or “dock” the wrap-or-dock panel should show up. Double click it or drag it onto the canvas to add it to your app. Blend will take care of the rest of the namespaces and everything.

image 

And start adding items to your panel. It should work the way it’s supposed to work.

image image

One note with the DockPanel… items placed in the DockPanel need to have the attached property

[xmlns]:DockPanel.Dock=”[something]

if you want them to do something other than align in the center. The [xmlns] name should be the same thing that is before the “DockPanel” in the XAML. It will most likely be “WP7Panels”. Therefore, the following XAML:

<WP7Panels:DockPanel>
    <Button Content="Button" WP7Panels:DockPanel.Dock="Bottom" />
    <Button Content="Button" WP7Panels:DockPanel.Dock="Top" />
    <Button Content="Button" WP7Panels:DockPanel.Dock="Right" />
    <Button Content="Button" WP7Panels:DockPanel.Dock="Left" />
    <Button Content="Button" />
</WP7Panels:DockPanel>

…should look like this:

image

If you want to add the actual files to your Windows Phone 7 app instead of just referencing the DLL (perhaps you are crazy or you have a deep and desperate need to fully understand absolutely everything you touch or you are a C++ developer), you can download the source. I’ve consolidated the DockPanel code into a single file (DockPanel.cs), but you’ll need the following files to get the WrapPanel working (all included in the source).

  • LengthConverter.cs
  • NumericalExtensions.cs
  • OrientedSize.cs
  • TypeConverter.cs
  • WrapPanel.cs

Finally, if you need something else for Windows Phone 7 from the Silverlight Toolkit, you can either add the entire toolkit (explained here) or download the source for the latest Silverlight 3 build and open it in Visual Studio 2010 (for some reason, I couldn’t get it to open in Visual Studio 2008). It should update and you should be all set playing around in there to extract the stuff you need.

Good luck!


PHP, MySQL, and Silverlight: The Complete Tutorial (Part 3)

14 Comments »

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):

Part 1: MySQL

Part 2: PHP

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…
clip_image001
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:

  1. Check to make sure we got a result without error
  2. Check to see what kind of result we got (did we get all to-do items? or add a new to-do item?)
  3. Walk through the result, extracting the data we need
  4. 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:

wc_DownloadStringCompleted
  1. void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
  2. {
  3. if (e.Error == null && e.Result!= “”)
  4. {
  5. JsonValue completeResult = JsonPrimitive.Parse(e.Result);
  6. string resultType = completeResult["returnType"].ToString().Replace(‘”‘, ‘ ‘).Trim();
  7. if (resultType == “todoItems”)
  8. {
  9. myToDoList.Clear();
  10. JsonArray toDoItemsJson = (JsonArray)completeResult["results"];
  11. foreach (JsonValue todoItemJson in toDoItemsJson)
  12. {
  13. ToDoItem thisTodo = new ToDoItem();
  14. if (todoItemJson["ToDoIndex"] != null)
  15. thisTodo.toDoID = Convert.ToInt32(todoItemJson["ToDoIndex"].ToString().Replace(‘”‘, ‘ ‘).Trim());
  16. if (todoItemJson["TodoText"] != null)
  17. thisTodo.toDoDescription = todoItemJson["TodoText"].ToString().Replace(‘”‘, ‘ ‘).Trim();
  18. if (todoItemJson["IsDone"] != null)
  19. {
  20. int isDoneInt = Convert.ToInt32(todoItemJson["IsDone"].ToString().Replace(‘”‘, ‘ ‘).Trim());
  21. if(isDoneInt == 0){
  22. thisTodo.isDone = false;
  23. } else if (isDoneInt == 1){
  24. thisTodo.isDone = true;
  25. }
  26. }
  27. myToDoList.Add(thisTodo);
  28. }
  29. ToDoList.ItemsSource = myToDoList;
  30. }
  31. }
  32. }

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.


PHP, MySQL, and Silverlight: The Complete Tutorial (Part 2)

6 Comments »

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):

Part 1: MySQL

Part 3: Silverlight

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’ll write some PHP code that will give us the ability to grab the data out of the database and send it, in JSON format, to our Silverlight application.

Part 2: Writing the PHP Web Service

We’re going to create 4 PHP files (download php files):

  • mysql_vars.php – holds all the information for connecting to the MySQL database
  • get_todo_items.php – for getting all the to do items
  • add_todo_item.php – adds a to do item
  • change_status.php – changes a to-do item from “not done” to “done” or vice versa

Since all these projects will be using the information in mysql_vars.php, we’ll write that first.

mysql_vars.php

<?php
$dbUsername = “[my_database_username]“;
$dbPassword = “[my_database_password]“;
$db = “[my_database_name]“;
$server = “[my_database_server]“;

//To Do Table and Column Names
$mysql_todoTable  = “to_do_data“;
$mysql_todoIndexCol = “index_key“;
$mysql_isDoneCol = “is_done“;
$mysql_todoTextCol = “to_do_text“;

$connection = mysql_connect($server, $dbUsername, $dbPassword);

function formatInput($rawURLData)
{
$returnString = urldecode($rawURLData);
$returnString = mysql_real_escape_string($returnString);
return $returnString;
}
?>

We’ve added the to-do table and column names so that, if we decide to change anything later, we can just go to this file and update the table or column once.

Just for good measure, we’ve added a function we’ll want to use across our php files. The function “formatInput” will be used to make sure all our data is decoded from the URL that calls our web service (the urldecode method) and then try to block any SQL injections (the mysql_real_escape_string method).

Now, let’s write the basic “Get the data” file. What we’re going to do is write it so that the we can choose to get:

  • all the to-do items
  • all the to-do items that are “done”
  • all the to-do items that are “not done”

This range of functionality isn’t even close to ideal. In a perfect world, we would want a wider range of options in gathering items (for example, items that contain a certain word or one item in particular or limit the number of items we call by a date range). However, for our very simple purposes, this will do.

The way our web service will work is that we have a URL that we’ll call from Silverlight when we want to get some data. When we calls this web service, we may want only the “not done” items or only the “done” items. We’ll handle that option by adding “?itemStatus=done” or “?itemStatus=notDone” to the end of the URL.

Example: if our base URL is

http://www.mywebsite.com/

the call to

http://www.mywebsite.com/get_todo_items.php

will get all items, regardless of their completed status while

http://www.mywebsite.com/get_todo_items.php?itemStatus=done

will get all the to do items that are complete. So we need to make sure that our web service responds appropriately to both calls.

There are comments in the code, but I’ll just explain the basic concept in picture form:

We take in a URL, extract the variables from it, create the MySQL query based on the variables, execute the MySQL query, extract the results, and then send back the php object encoded as a Json object. Each one of our files will follow this same pattern.

get_todo_items.php

<?
include ‘mysql_vars.php’;

//    set up the “itemStatus” URL option and build a query addition
//        to account for the itemStatus variable
$itemStatus = $_GET['itemStatus'];
$itemQueryAddition = “”;

if($itemStatus != NULL)
{
if($itemStatus == “done”)
{
$itemQueryAddition = “WHERE `$mysql_isDoneCol` = 1″;
} else if ($itemStatus == “notDone”)
{
$itemQueryAddition = “WHERE `$mysql_isDoneCol` = 0″;
}

// Construct our MySQL query
$todoQuery = “SELECT * FROM `$mysql_todoTable` $itemQueryAddition ;”;

// execute the query and gather the results…
mysql_select_db($db, $connection);
$todoResult = mysql_query($todoQuery);
$todoArray = array();

while($itemRow = mysql_fetch_array($todoResult))
{
$todoArray[] = array( “ToDoIndex” => $itemRow['index_key'],
“IsDone” => $itemRow['is_done'],
“TodoText” => $itemRow['to_do_text'] );
}
mysql_close($connection);

// … then encode the results as JSON Text…
// we’re using a “returnType” field so that our Silverlight application can differentiate between
// the kind of return values it recieves and parse the Json object appropriately

$returnItems = array( “returnType” => “todoItems”,
“results” => $returnItems);
$JSONResult = json_encode($todoArray);

// … and print the results so that our app can read them
echo $JSONResult;
?>

The other two files, add_todo_item.php and change_status.php use exactly the same structure to add a new item and change the status of an existing item (respectively). I won’t put all the code here in this post that is already too long, but you can download all the files here.

Update the mysql_vars.php file to fit your needs and you should be able to just upload these files and have your running to-do web service all ready for Silverlight to call it for data, which is something we’ll deal with in Part 3.


PHP, MySQL and Silverlight: The Complete Tutorial (Part 1)

3 Comments »

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”. This tutorial is geared toward someone who has never done databases or web services.

Here is an example of the finished product (I reserve the right to clean up the data on a regular basis):

This tutorial will walk through the steps to create a simple to-do list. Our to-do list will hold text of what it is we need to do and a value indicating if the task has been done. In this tutorial, we will create a MySQL table to hold our data, a PHP service to call the data and a Silverlight application to display and interact with the data.

Part 2: PHP

Part 3: Silverlight

Download all files (PHP & Silverlight)
Download PHP files only
Download Silverlight project only

Part 1: The MySQL Database

First, let’s create the table we need for our data.

If you don’t have or don’t like phpMyAdmin, the MySQL query to create the table described below is:

CREATE TABLE `[your_database_name]`.`to_do_data` (
`index_key` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`is_done` TINYINT( 4 ) NOT NULL DEFAULT ’0′,
`to_do_text` TEXT NOT NULL ,
FULLTEXT ( `to_do_text` )
) ENGINE = MYISAM

If you have phpMyAdmin, I highly suggest using it if you’re a MySQL novice. In phpMyAdmin, go to your database and enter the name of the table you want to create in the “Create new table on database [your_db_name]” section.

clip_image001[5]

We’ll call our table “to_do_data” and give it 3 fields.

  • index_key – identifies the to-do item uniquely
  • is_done  – true/false value indicates the status of the to-do item
  • to_do_text – a short text to describe what needs to be done

In phpMyAdmin, it will look like this:

clip_image001

A couple of notes about the fields:

index_key

This is the primary key of the table and is used to uniquely identify the given row. As such, it cannot be null and it auto-increments as rows are added to the table.

is_done

We use “TINYINT” type for this value because using BOOLEAN is basically the same thing. It is not null because every item must either be “done” or “not done”. “Done” = true = 1 and “not done” = false = 0. We are going to default to “0” (false) because we’re assuming that users aren’t going to make a to do list of stuff that is already complete.

to_do_text

We have artificially limited the text size to 1024 because we assume that this will be a set of short to-dos to, not a set of journal entries. We’ve also turned on “Fulltext” which lets the MySQL database index our entries for quick searching.

Now we just click the “Save” button at the bottom and we have our table.

clip_image001[7]

Now our database system is in place and we’re ready to write a PHP webservice to implement all the CRUD (create, read, update, delete) capabilities our system will need.

If you want to learn more about MySQL, I highly recommend “A Visual Introduction to SQL“. This is the book I have, a left-over of my grad school years and it is an exceptional book for picking your way through various database scenarios.

If you’re looking for something a bit less costly, “MySQL Crash Course” is a fine book on the subject as well.


New Silverlight Posts at Veracity Blogs

No Comments »

I’ve started a series of posts on Silverlight and other topics over at the Veracity Solutions Blog.

Veracity Solutions is the software consulting firm where I work and we’ve decided that it would be a good idea to do some sponsored posting there.

Blog posts up so far are:

More are coming, including tutorials on behaviors and paths.


Adventures with JSON and Silverlight (and the New York Times)

4 Comments »

Summary: In this post, I walk through the basics of using Silverlight to query the New York Times Article API and display the results of the query. You can see the final result below.

You can also download source code for this project here.

JSON/Silverlight/New York Times project files

Huge thanks to Josh Holmes, whose JSON/Silverlight tutorial was the base of much of this project.

This project is somewhat code-intensive (and kind of long, expect 30-60 minutes), so if you just want the utility provided here without any of the work, you can skip over to my post on displaying the results, which is strictly a Blend tutorial.

However, I recommend walking through this one since it will help get you to a point of pulling real data from an API, which I’ve found to be a wonderful help as I practice putting together data-based designs. One of the things I’ve been wanting to be able to do as a designer is to explore a data set easily and quickly so that I can have data to play with in my interfaces. I found exactly what I wanted in the New York Times API, but then I found out I had to learn JSON.

“Oh great,” I said to myself, “another technology for me to learn.” But it turned out that I didn’t actually have to learn that much, because Visual Studio does nearly all the work for me.

Super Quick Introduction to JSON

If you’re not interested and you want to get to the business of grabbing New York Times data, you can skip it . It is helpful, but not strictly necessary.

JSON stands for JavaScript Object Notation and is basically just a really handy way to pass data along in a web service. It is very simple… within a set of curly brackets, you will have name/value pairs separated by a colon with each piece of data.
Example:
{
    FirstName : “Matthias”,
    LastName : “Shapiro”,
    Blog : “Designer WPF”
}

This is a JSON object. Arrays are created by using square brackets and JSON obejcts can be placed into a Javascript var. These things are not really related in anyway, but putting them in the same sentence allows me to only write one more example instead of two

Example:
{
    FirstName: “Matthias”,
    LastName: “Shapiro”,
    Siblings : [
    {Name : “Abby”},
    {Name : “Joel”},
    {Name : “Anna”},
    {Name : “John”},
    {Name : “Nate”}
    ]
}

And there we have the basics of JSON.

End of Super Quick Introduction to JSON

What is so awesome about JSON and Silverlight is that Visual Studio 2008 has a set of JSON-friendly classes that make working with JSON a breeze. Which is really handy because the New York Times, which is a dream come true for the new data-gatherer, delivers JSON results. So let’s walk through making a call to the New York Times Article API, handling the data we get back, and putting it into a Listbox for viewing.

First, go to the New York Times Developer site, log in (or register) and get your API key.

Next, start a new Silverlight project in Visual Studio 2008. I named mine “JSONNewYorkTimesTutorial”.

clip_image001[9]

Open your new project in Blend, pull up Page.xaml and add a TextBlock, ListBox, a TextBox and a Button. Name the ListBox “ResultsDisplay” and the TextBox “SearchText”.

clip_image001[13]

Now, my Page.xaml looks like this.

clip_image001[11]

OK… now let’s go to the code-behind for our project go to the event section of the button in Blend and type “PerformQuery” into the “Click” event.

clip_image001[15]

This will automatically insert the necessary code into the code-behind, so pull up Visual Studio. Before we implement a call to the NYT API, lets add some useful stuff. If you have not yet gone to get your Developer key, do so now.

private string myApiKey;
private WebClient callNYT;

public Page()
{
    InitializeComponent();
    myApiKey = “&api-key=(put your api key here. No, you may not have mine)”;
    callNYT = new WebClient();
    callNYT.OpenReadCompleted += new OpenReadCompletedEventHandler(callNYT_OpenReadCompleted);
}

In the code above, we’ve created a string that we can use to apply our unique NYT API key and we’ve created an instance of WebClient to call and receive information from the NYT API. When an object from the NYT API has been received , it will call the OpenReadCompleted event, which will be handled by our callNYT_OpenReadCompleted method.

(By the way, if you’re not getting the proper intellisense for the “Web Client” part, add “using System.Net;” to the top of your file.)

Now on to our button method. There are tons of things we can add to our query to find the exact information we want. But in the interest of simplicity, this post will deal only with a simple text search. To that end, let’s go to our PerformQuery method and turn it into this:

private void PerformQuery(object sender, RoutedEventArgs e)
{
    string NYTQueryBase = “http://api.nytimes.com/svc/search/v1/article”;
    string SearchTerm = “?query=”+ SearchText.Text;
    Uri queryUri = new Uri(NYTQueryBase + SearchTerm + myApiKey);

    callNYT.OpenReadAsync(queryUri);
}

We’ve done two things here. The first is that we built our search query using the query base, the query string and our API key. That was simple enough.

Next, we’ve going to use the WebClient we created to call our new query. When the query has been completed, our program will run the callNYT_OpenReadCompleted method with its result, which will be a JSON object constructed by the NYT servers. We will get back a JSON object with the following:

  • offset – We will get 10 results per page. The offset tells us which page of the results we’re on. The default is 0, which gives us results 0 – 9.
  • tokens – this is a array of our search terms.
  • total – this is an integer indicating of how many results there were for our search.
  • results – this is an array of results with the following format
    • body – a portion of the beginning of the article
    • byline – the article byline, usually including the author name
    • date – the date the article appeared, in a “yyyymmdd” format. For example, today would be “20090225”.
    • title – the article title
    • url – a url link to the article

A quick note: The NYT API is extremely flexible and we can actually define how we want our results to come back. This is just the default result format for the purposes of demonstration.

Before we handle this object, we want to create a class for the results. Right click on your project and go to “Add –> Class…”. Name your new class “NYTResult.cs” and make sure it looks like this:

public class NYTResult {
    public string Body { get; set; }
    public string Byline { get; set; }
    public DateTime Date { get; set; }
    public string Title { get; set; }
    public Uri Url { get; set; }
}

I added the following method to the class to handle the date conversion from the NYT format to a .NET DateTime object.

public DateTime formattedDateTime(string NYT_Time)
{
     int year = Convert.ToInt32(NYT_Time.Substring(0, 4));
    int month = Convert.ToInt32(NYT_Time.Substring(4, 2));
    int day = Convert.ToInt32(NYT_Time.Substring(6, 2));
    DateTime finalDateTime = new DateTime(year, month, day);
    return finalDateTime;
}

OK… now we’re really ready to handle the JSON object. Right click on the references in your project and select “Add Reference…”

clip_image001

In  your “Add References” box, select “System.Json” and click “OK”.

clip_image001[5]

Add “using System.Json;” to the references in your Page.xaml.cs file. And, just for good measure, add “using System.Collections.ObjectModel;” as well.

Go to the callNYT_OpenReadCompleted method and enter the following. I’ve tried to comment the code so that I don’t need to further explain it. Side note: I’m not always the best at understanding what is self-explanatory and what I need to elaborate on. If there are any additional questions, post them in the comments and I’ll answer as quickly as I can.

void callNYT_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    //grab our result and make a JSON Object out of it
    
//    then extract the results array from that object
    
JsonObject completeResult = (JsonObject)JsonObject.Load(e.Result);
    JsonArray resultsArray = (JsonArray)completeResult["results"];

    //an observable collection to hold the data and attach it to our ListBox

     ObservableCollection<NYTResult> resultCollection = new ObservableCollection<NYTResult>();

    //iterate through the results and transfer the data from a
    
//   JSON object into our nice pretty .NET object
    
foreach (JsonObject NYTRawResult in resultsArray)
    {
        NYTResult singleResult = new NYTResult();

        //don’t forget to check your results… an article might not have a
        
//  byline or a link
         if (NYTRawResult.Keys.Contains(“body”))
            singleResult.Body = NYTRawResult["body"];
        if(NYTRawResult.Keys.Contains(“byline”))
            singleResult.Byline = NYTRawResult["byline"];
        if (NYTRawResult.Keys.Contains(“date”))
            singleResult.Date = singleResult.formattedDateTime(NYTRawResult["date"]);
        if (NYTRawResult.Keys.Contains(“title”))
            singleResult.Title = NYTRawResult["title"];
        if (NYTRawResult.Keys.Contains(“url”))
            singleResult.Url = new Uri(NYTRawResult["url"]);

        //add our new result to the collection
        
resultCollection.Add(singleResult);
    }

    //assign the result as the source for our ListBox
    
ResultsDisplay.ItemsSource = resultCollection;

    //take the overall article count and display it
     resultCount.Text = “Number of articles: ” + completeResult["total"].ToString();
}

Now, we can run our project. Type something into the TextBox and hit the button and we get this:
clip_image001[7]

Not exactly the most readable thing ever. So let’s add the following to the ListBox XAML:

DisplayMemberPath=”Title”

Now we get something a little more like this (go ahead and give it a whirl):

Much better. Remember, this is a simple query, so it’s only looking for items that have that word in the article… it might not be in the title.

My next post builds on this one and I walk through building a more useful display for our results. It will be far less code intensive and far more designer centric.

I’ve made the source available for this project. I’ve taken out my NYT API key, so it will not run unless you get your own and put it in.

JSON – Silverlight – New York Times Tutorial Part 1 project files


Mask Animations (Clipping Path Animations) In Silverlight Without a Line of Code

1 Comment »

Last night I submitted my MIX 10K Challenge piece, so I’m just killing time while I wait for it to get accepted. Please keep me in mind if you plan on voting.

OK… I’ve been excited about this for some time now. I found out (almost completely by accident) that you can animate a mask (also known as a clipping path) in Silverlight without writing code or even typing (much). This is exciting because I think it’s something that might interest our Flash friends who, late at night and in the privacy of their own homes, take a peek to see if Silverlight is worth looking into. When I worked with Flash, mask animations were my bread and butter and they seemed so hard to do in Silverlight.

But they’re not.

First open up your project in Blend. (I always create my project in Visual Studio and then open it in Blend because visual Studio has so much better project debugging and makes testing a breeze.)

Find the item you want to clip (in my case this is an image) and select the pen tool from the toolbar.

clip_image001

And start drawing.I’m a poor artist, so the star I drew looks pretty bad. If you need to change any of the points, use the direct selection tool (the light arrow, second from the top).

clip_image001[4]

OK… now the fun part. Add a storyboard to your project

clip_image001[6]

and you can animate the clipping mask using all the normal animation tools. Use the direct selection tool above to animate the vertices. You’ll get something like this:

Now… if you’re not interested in the details, just skip ahead a little bit. Something important happened the moment we started animating the path. Normally, path data is kept in a single string format that looks something like this:

Data=”M159.67175,104.26108 L177.91812,28.328932 L195.51648,104.43327 L255.0802,102.6104 L206.86984,151.82758 L225.8029,226.56477 L179.0616,179.17046 L129.73396,229.29906 L147.97842,150.63879 L98.650803,101.53297 z”

This is actually a “powerful and complex mini-language that that you can use to describe geometric paths in XAML.” Microsoft uses it by default to handle path data. But it doesn’t work very well for animating paths, so the second you animate a single vertex in your path, it changes the format you see above to the format you see below:

<Path.Data>
<PathGeometry>
<
PathFigure IsClosed=”True” StartPoint=”91.0527648925781,84.0121078491211″>
<
LineSegment Point=”118.057907104492,0.549586236476898″/>
<
LineSegment Point=”144.103973388672,84.2013778686523″/>
<
LineSegment Point=”232.259979248047,82.1977386474609″/>
<
LineSegment Point=”160.907287597656,136.2958984375″/>
<
LineSegment Point=”188.928756713867,218.444961547852″/>
<
LineSegment Point=”119.750289916992,166.350433349609″/>
<
LineSegment Point=”46.7439804077148,221.450408935547″/>
<
LineSegment Point=”73.7462997436523,134.989212036133″/>
<
LineSegment Point=”0.740016639232636,81.0134506225586″/>
</
PathFigure>
</
PathGeometry>
</
Path.Data>

Same data, but only this latter format is appropriate for animation. Remember this, it will come in handy in a second.

OK… now right click on your path and go to “Path –> Make Clipping Path”

clip_image001[10]

You’ll get a dialog pop-up that will ask you which item in the visual tree you would like to clip. I chose my image, but it will work with anything.

clip_image001[12]

And… poof! You have clipping animation.

LIMITATIONS: Here are the limitations to this method:

  1. You need to animate before you make your path into a clipping path. – Remember that little bit above about the data string format vs. path geometry? If you don’t animate before hand, Blend will convert all your beautiful line segments into the un-animate-able data string. Animating the path tells Blend to leave your formatting alone.
  2. Once you make your path a clipping  path, animation gets a lot harder – Basically, you can change the time by dragging the key frames around and change the easing. Any other alterations require entering values by hand. So do all your animation first before setting the path. The easiest work around to this is to copy and paste your path out of the Control.Clip section and back into your main XAML and tweak animation from there. But your best option is to just take the time to make your clipping animation perfect before you make it a clipping path.

How To Give a Silverlight 2 Gadget a Transparent Background

2 Comments »

Warning: This is a poor solution if your gadget has any level of dragging interaction in it. The “windowless=true” step will make it so that any dragging interaction will be interrupted by the gadget, which will interpret such a move as an attempt to drag the gadget off the side bar.

Giving your Silverlight gadget a transparent background is actually quite simple. First, follow the directions from Chris Szurgot’s post on Silverlight gadgets. No point in duplicating his work.

When you’re done, create a transparent png file. Or download this one.

Now, head over to your html file. Get rid of all CSS background information. Add the following just below the body tag:

<g:background id=”background”
src=”transparent.png”
style=”position:absolute;top:0;left:0;z-index:-999;no=repeat; />

Finally, change the following params in the Silverlight object host.

<param name=”background” value=”transparent” />
<
param name=”windowless” value=”true” />

And that’s it.

Additional Warning: It looks like there is no solution yet for the pink halo around any anti-aliased pixels in a Silverlight gadget.

clip_image001

clip_image001[4]

This is a problem that transparent Silverlight gadgets have had for some time now. If that doesn’t bother you then you’re all set.


Follow me: matthiasshapiro