Archive for the ‘c#’ Category

Fixing the ListPicker / ScrollViewer Problem in Windows Phone 7

2 Comments »

I’m working on a new project in which I need multiple ListPickers in a ScrollViewer.

The ListPicker is available via the Silverlight Toolkit for Windows Phone 7. If you don’t have it, you should get it. Get the source as well, for reasons that will be clear in one more sentence.

The only problem is that I can’t scroll if I do this because I run the risk of accidentally opening the ListPicker (which should be a tap interaction) when swiping (which is a gesture interaction):

I posted this as a work item on codeplex, so it will probably be fixed in a couple months (sometime in early 2011), but if you’re having a problem with it, do the following:

Open up the source, go to the Microsoft.Phone.Controls.Toolkit project, the ListPicker folder and open the ListPicker.cs file. Go down to the OnManipulationCompleted event and after the line

base.OnManipulationCompleted(e);

add the following conditional for the rest of the code in the method:

if ((Math.Abs(e.TotalManipulation.Translation.X) < 20) && (Math.Abs(e.TotalManipulation.Translation.Y) < 20)){
[Other code]
}

This catches manipulations that are less tap-y and more scroll-y and lets them slide by without opening the ListPicker. If you wanted to be really careful, you could probably change the conditional to 10 or even 5. Most of the taps I checked had pretty small (single digit) manipulation deltas.


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.


Code for MIX10 Information Visualization Talk Demos

7 Comments »

As promised, I’m posting my code for the demos from my MIX10 “Creating Effective Information Visualization in Silverlight” talk.

Unemployment Data Demo Code

Bing Maps Twitter Demo Code

In case you want to take a look at the unemployment visualization, I’ve added it below. I’m looking for a place to do ASP.Net hosting because my Bing Maps visualization is driven using Twitter data called and served through a WCF service, so if you have a recommendation for a noob ASP.Net guy, let me know. I’d love to host that as well.

(Apparently some people are having trouble with my demo below. I’ll try to get a more compatible version up soon.)


Get Microsoft Silverlight

You can copy the code for to embed this with the text below:


Info Vis, Snapping Behaviors, Illustrator Guidance and Custom Control Stuff

No Comments »

I’ve been a busy blogger over at Veracity Blogs the last couple weeks. Here’s a list of my new posts:

  • Florida Crime Rate Visualization – My attempts to use Silverlight for information visualizations are going pretty well. In this post, I visualize the Florida crime rate by county over almost 20 years. There are project files availalbe for anyone who wants to dig into how I did it a little more.
  • Adobe Illustrator to XAML Conversion Options – This post walks through the pros and cons of two methods for taking an SVG file (or Adobe Illustrator) file and pulling it into Blend as a XAML file. It also has a XAML copy of a vector map of the US by county for download.
  • Create A Snapping Slider In Blend Using Behaviors – This provides a downloadable behavior for getting a slider to snap to integers (or an integer multiple based on certain settings). I’ve provided project files as well as a tutorial for how to do it.
  • How To Create a PART in Your Silverlight Custom Control – Because there are about a dozen tutorials on building a custom control, but I keep forgetting exactly how to do this part of it.
  • How To Animate a Changing Property in a Custom Control in Silverlight – Have you ever wanted your property to animation automatically when it changes in your Silverlight Custom Control. I say, “Who hasn’t!?” at which point my wife forces me out into the fresh air and sunshine (or, as I call it, the Blinding Day Star). After I scurry back inside, I wrote this blog post.
  • How To Build a Storyboard Animation for Silverlight in C# – Because sometimes you want to enjoy the benefits of the Silverlight animation engine but you really need to build the animation in the code instead of the XAML.

INotifyPropertyChanged Snippets (And Why You Should Use These Instead of DependencyProperties)

4 Comments »

First things first, here are my INotifyPropertyChanged snippets.

INotifyPropertyChanged snippet (PropertyChangedEventHandler and RaisePropertyChanged method)

INotifyPropertyChanged Property snippet

Just download them into your "Visual Studio 2008CodeSnippetsVisual C#My CodeSnippets" folder and they should work. Just type "notify" and intellisense should show you "notifyo" (for NotifyObject) and "notifyp" (for NotifyProperty). Hit tab twice and the code should dump into your project.

This is definitely a "use at your own risk" project.

You see, there I was, minding my own business and trying to build some data to use with some XAML comps I was playing with and I was having some of the strangest things happen with my data. I had a DependecyProperty ObservableCollection in my ViewModel and I put a couple different views in my screen. (I was using an MVVM pattern, because that’s what all the kool kids are doing.)

Then, it suddenly seemed as if all my Views were sharing the same ObservableCollection, even though every other DependencyProperty they were bound to had unique values. So I did what I always do when I have problems like this… I ask Joe McBride.

It turns out I had gotten confused. I understood that DependencyProperties were good for the following:

  • Providing callbacks when the property is changed
  • Binding to stuff
  • Animations

I figured that this is the kind of behavior I wanted from my data. I was wrong. As it turns out that is the kind of behavior I want out of the properties that I use in my WPF and Silverlight controls. It seems that DependencyProperties are meant to be used with controls and not for stand-alone data.

For stand-alone data, I should have used INotifyPropertyChanged, which is an interface for… well… notifying things when a property changes. I already had handy snippets for creating DependencyProperties (thanks to Robby Ingebretsen). So I tweaked his snippets so that they work for INotifyPropertyChanged properties.

Because it seems silly to implement the PropertyChangedEventHandler in every class that needs notify-able properties, I like to create a "NotifyObject" class:

class NotifyObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if(handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }       
}

Then, I can make my new class inherit from NotifyObject and away I go creating my bindable, notify-able data:

public class MyNotifyableData : NotifyObject
{
    public MyNotifyableData()
    {
    }

    #region MyProperty (INotifyPropertyChanged Property)
    private string _myProperty;

    public string MyProperty
    {
        get { return _myProperty; }
        set
       
{
            _myProperty = value;
            RaisePropertyChanged("MyProperty");
        }
    }
    #endregion
}

This property was created using my snippet above. Hope it helps.


Latest SlapDash Version of Wiimote/WPF Visualizer

1 Comment »

I’ve been meaning to totally overhaul my Wiimote WPF visualizer for weeks now and I simply haven’t been able to find the time. But in the meantime, people keep having problems with my old version.

So… my solution is to get my semi-updated version out there. This version works with the latest version of Brian Peek’s Wiimote Library (as of March 10, 2009).

Download Wiimote Visualizer (03_10_09)

Download Wiimote/WPF Binding Library (03_10_09)

Warning: This project WILL break if you try to use the Wii Fit balance board with it. That’s one of the things I’m trying to fix.

Let me know if you have any problems. I will try to address them, but with MIX coming up in a week, it might be a little while. In the meantime, I’m trying to do a complete revamp of all this stuff.


Source Code For Presidential Candidate Tracker Visualization

4 Comments »

Due to repeated requests for the source code (and the fact that I apparently can’t brag about it on Silverlight.Net without a link to the source code), I’m putting it up for download.

Presidential Candidate News Tracker Source Code

JSON Data File With Candidate Data (Note: Apparently, WordPress likes to uncapitalize file names for me, you may have to re-name the file to “CandData.json” to get it to work with the app.)

Warning: This code is a disaster. I was having strange problems getting my custom controls to work and, after a couple hours fighting with it, I gave up and ended up writing the exact same layout and code for 14 separate candidates. Same problem with the “dates-of-note” along the timeline.

Not pretty, but it works. Have fun.


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


InfoViz Project For Tim Heuer – Presidential Candidate Tracker

7 Comments »

UPDATE: I’ve made the source code available for download here.

Yeah, yeah… I know it’s long past the time when anyone want to revisit the wonders of the 2008 presidential campaign, but the stars aligned for me to build this thing.

Star #1: I’m been meaning to learn JSON forever because everyone is talking about it.

Star #2: I’ve been meaning to get into pulling data from a publicly available API using a Silverlight application.

Star #3: I’ve been meaning to do something with information visualization in Silverlight ever since I got Ben Fry’s terrific book on Visualizing Data.

Star #4: Tim Heuer challenged his readers to create a Silverlight infoviz application with a time constraint of six days.

And so, due to several late nights and the infinite patience of my wonderful wife, I’ve finished my first data driven Silverlight information visualization. An explanation follows below the app.


Get Microsoft Silverlight

The application visually displays how many stories in the New York Times in a given week mentioned one of the presidential candidates. If your favorite candidate does not appear, I apologize. I chose the seven most frequently mentioned candidates in each party.

My journey of exploration began at the New York Times developer site where I got my developer key and started exploring the data from their brand new Article Search API, with which you can search articles in the New York Times as far back as 1981.

Because the NYT API returns a JSON result, that meant I had to learn JSON. I highly recommend it. Super easy. I ended up scraping the data I needed and parsing it into a custom JSON file of my own so I wasn’t making a couple hundred calls to their servers every time I wanted to run my application.

From there, it was actually a simple matter to pull the idealized data into my application and start visualizing it. In case you’re wondering, the placement on the map doesn’t represent anything at all… I was just looking for a good way to show the data and I liked this one.

A special thanks to my wife, the math genius, for reminding me to take the square root my data so that my circles ended up with proportional areas (instead of exponential ones).

There are, of course, several things I would change about this if I had the time. The slider can be flaky, the fonts could use some more work and the code in general is a bit of a disaster. But this is all the time I had and I think it works pretty well.


How To Write a Custom Event in Silverlight

1 Comment »

Ha, fooled you! This is actutally how to write a custom event (with event handlers and everything!) in C#, but it turns out that you don’t need to change a damn thing about it to get it to work in Silverlight. (It’s always the “what do I have to change?” question that stumps me.)

I know that this is old hat for you seasoned developers out there, but it was news to me… and vitally important for updating my color picker project.

Anyway, it unsurprisingly comes from O’Reilly. If you are so inclined, you can go check it out.