1

I am downloading some XML from a twitter feed in the background, using HttpWebRequest, and Deployment.Current.Dispatcher.BeginInvoke() to process the results, and set them as the ItemsSource of my ListBox. What I want to do now, is gather the XML from multiple twitter feeds, combine them into a collection, and assign that to the ItemsSource property.

I figured I'd use a counter in the class, and a collection in the class, and update both each time a request completes, and when the counter hits the feed count (7), set the ItemsSource accordingly. Problem is, I'm very new to C# / WP7, and am having some issues here. This is what I have working now, which is obviously wrong, because whichever request finishes last overwrites the ItemsSoure, AND, I'm not sure how to stick them into a 'global' container, because it seems like the Dispatcher has a different scope:

string[] feeds = { "badreligion",
                "DoctorGraffin",
                "BrettGurewitz",
                "jay_bentley",
                "brtour",
                "GregHetson",
                "theBRpage" };

// invoked in the constructor
private void StartTwitterUpdate()
{
    foreach (string feed in feeds)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + feed));

        request.BeginGetResponse(new AsyncCallback(twitter_DownloadStringCompleted), request);
    }
}

// the AsyncCallback
void twitter_DownloadStringCompleted(IAsyncResult asynchronousResult)
{
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

    using (StreamReader streamReader1 =
        new StreamReader(response.GetResponseStream()))
    {
        string resultString = streamReader1.ReadToEnd();

        XElement xmlTweets = XElement.Parse(resultString);

        // here I need to add to a collection, and if the max is hit, set the ItemsSource
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            TwitterListBox.ItemsSource = from tweet in xmlTweets.Descendants("status")
                                            select new TwitterItem
                                            {
                                                CreatedAt = tweet.Element("created_at").Value,
                                                Id = tweet.Element("id").Value,
                                                ImageSource = tweet.Element("user").Element("profile_image_url").Value,
                                                Message = tweet.Element("text").Value,
                                                UserName = "@" + tweet.Element("user").Element("screen_name").Value
                                            };
        });
    }
}

EDIT Also, if it matters, I'll have to sort the final collection before sending it to ItemsSource, via TwitterItem.CreatedAt, so if someone could suggest an optimal data structure for sorting and easy ItemsSource assignment, that'd be great!

1
  • 1
    I think any simple data structure like List<T> or ObservableCollection<T> is updatable "across Dispatchers" or from a background thread, the problem is that if it is bound to a UI element - the UI element might not like being accessed from a background thread, so you should only update your bound collections from background threads using Dispatcher.Invoke(() => updatecall); Nov 16, 2011 at 4:33

2 Answers 2

2

What you need to do is create a persistent, bindable collection object somewhere in your view and assign that to ItemsSource once. As new items are received, just add them to the collection.

You'll want to either choose an existing collection type that supports notifications when the collection is modified or implement one yourself. In Silverlight, I think that your best (only?) bet is the System.Collections.ObjectModel.ObservableCollection. The other option is to implement System.Collections.Specialized.INotifyCollectionChanged in a custom class that inherits from a different type of Collection.

As for sorting, if your arriving data will always be later than your existing data, then you can just sort the new items prior to adding them to the collection (you may want to insert them in the front of the collection if you want to display them with the newest on the top).

However, if the entire collection needs to be sorted each time new records are added, then you will need to implement System.IComparable on your item class. In this case, I would recommend the following approach:

Create a new collection class based on System.Collection.Generic.List (this contains a native Sort() method).

Implement INotifyCollectionChanged in this class and raise its CollectionChanged event with the NotifyCollectionChangedAction.Reset action after your records are added and sorted.

Implement IComparable on your item class to get the items sorted according to your rules.

Update with implementation of INotifyCollectionChanged

Most of the suggestion is pretty straightforward, but the implementation of the INotifyCollectionChanged is a little tricky, so I am including it here:

<NonSerialized()> _
Private m_ListChangedEvent As NotifyCollectionChangedEventHandler

''' <summary>
''' This event is raised whenever the list is changed and implements the IBindingList ListChanged event
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Public Custom Event ListChanged As NotifyCollectionChangedEventHandler Implements INotifyCollectionChanged.CollectionChanged
    <MethodImpl(MethodImplOptions.Synchronized)> _
    AddHandler(ByVal value As NotifyCollectionChangedEventHandler)
        m_ListChangedEvent = DirectCast([Delegate].Combine(m_ListChangedEvent, value), NotifyCollectionChangedEventHandler)
    End AddHandler

    <MethodImpl(MethodImplOptions.Synchronized)> _
    RemoveHandler(ByVal value As NotifyCollectionChangedEventHandler)
        m_ListChangedEvent = DirectCast([Delegate].Remove(m_ListChangedEvent, value), NotifyCollectionChangedEventHandler)
    End RemoveHandler

    RaiseEvent(ByVal sender As Object, ByVal e As NotifyCollectionChangedEventArgs)
        If m_ListChangedEvent IsNot Nothing Then
            m_ListChangedEvent.Invoke(sender, e)
        End If
    End RaiseEvent
End Event

To raise this event so that consumers are aware of changes to the list:

Call RaiseListChangedEvent(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))
4
  • Sounds difficult (but fun)! I'm assuming that looking through MSDN will give me what I need to know to do such a thing? If not, do you have any good tutorial / links for general Notification implementations and so on?
    – Josh
    Nov 13, 2011 at 2:08
  • 1
    The INotifyCollectionChanged implementation is the most challenging, but I included my solution in the answer. The rest should be easily discoverable (sorry, I don't have any specific links since we implemented this last year sometime). Nov 13, 2011 at 2:16
  • No problem, I really appreciate all you've given me. I'm a professional developer, but have only been doing MS / C# coding for about 5 days now!!!
    – Josh
    Nov 13, 2011 at 2:18
  • 1
    Sorry, forgot this was a C# question; the code I added was VB, but there should be translations out there. The one important note is that if the item class is serialized, you don't want to serialize the event with it since it is technically a serializable member, which I have never really understood. Nov 13, 2011 at 2:21
1

A simply solution would be to use an ObservableCollection as your ItemsSource:

TwitterListBox.ItemsSource = new ObservableCollection<TwitterItem>().

Whenever you receive more items to add - simply do:

var itemsSource = (ObservableCollection<TwitterItem>)TwitterListBox.ItemsSource;

foreach(var twitterItem in newTweets)
{
    itemsSource.Add(twitterItem);
}

If you want these sorted - you need to do itemsSource.Insert(twitterItem, i) after you figure out where to insert the new item. There are probably a few ways to do that, but assuming you parse your created_at like this:

CreatedAt = DateTime.ParseExact(createdAt, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture)

This is roughly how you could do it:

int i = 0; // insert index
int j = 0; // new items index

while (j < newTweets.Count)
{
    while (i < itemsSource.Count &&
        itemsSource[i].CreatedAt >= newTweets[j].CreatedAt)
    {
        i++;
    }

    itemsSource.Insert(i, newTweets[j]);
    j++;
}

Or a fancier solution:

public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        var itemsSource = new ObservableCollection<TwitterItem>();
        var initialTweets = new[]
                                {
                                    new TwitterItem
                                        {CreatedAt = DateTime.Now.AddMinutes(-3)},
                                    new TwitterItem
                                        {CreatedAt = DateTime.Now.AddMinutes(-2)},
                                    new TwitterItem
                                        {CreatedAt = DateTime.Now.AddMinutes(-1)}
                                };
        itemsSource.Merge(initialTweets.OrderByDescending(ti => ti.CreatedAt));

        var newTweets = new List<TwitterItem>();
        newTweets.Add(new TwitterItem {CreatedAt = DateTime.Now.AddMinutes(-3.5)});
        newTweets.Add(new TwitterItem {CreatedAt = DateTime.Now.AddMinutes(-2.5)});
        newTweets.Add(new TwitterItem {CreatedAt = DateTime.Now.AddMinutes(-1.5)});
        newTweets.Add(new TwitterItem {CreatedAt = DateTime.Now.AddMinutes(-0.5)});
        itemsSource.Merge(newTweets.OrderByDescending(ti => ti.CreatedAt));

        foreach (var twitterItem in itemsSource)
        {
            Debug.WriteLine(twitterItem.CreatedAt.ToString());
        }
    }
}

public class TwitterItem
{
    public DateTime CreatedAt;
}

public static class ObservableTwitterItemsExtensions
{
    public static void Merge(
        this ObservableCollection<TwitterItem> target, IEnumerable<TwitterItem> source)
    {
        int i = 0; // insert index

        foreach (var newTwitterItem in source)
        {
            while (i < target.Count &&
                target[i].CreatedAt >= newTwitterItem.CreatedAt)
            {
                i++;
            }

            target.Insert(i, newTwitterItem);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.