Advertisement

Getting started with Silverlight: Part 3 – Accessing Data

This is part 3 in a series on getting started with Silverlight.  To view the index to the series click hereYou can download the completed project files for this sample application in C# or Visual Basic.

Now that we have our initial layout outlined and some controls to work with, let’s start getting the data.  Since we’re going to use Twitter search, we’ll be leveraging their web service API.  In our application we won’t be hosting our own database or anything but I did want to point out the various ways you can access data via Silverlight before we go to work on ours.

Data access options

One of the bigger beginner misconceptions about accessing data in Silverlight is people looking for some ADO.NET class library in Silverlight.  Stop looking, it isn’t there.  Remember, Silverlight is a client technology that is deployed over the Internet.  You wouldn’t want a browser plug-in to have direct access to your database…as you’d have to expose your database directly to the web.  We all know that is generally a big no-no.

So the next logical step is to expose data via service layers.  This is how Silverlight can communicate with data.  Here are the primary means:

  • Web services: SOAP, ASP.NET web services (ASMX), WCF services, POX, REST endpoints
  • Sockets: network socket communication
  • File: accessing static content via web requests.

Sockets

Sockets are probably the most advanced data access endpoints.  These require a socket host to exist and, at the time of this writing, also require communication over a specific port range.  If this is acceptable for you, this can be a very efficient and powerful means of communication for your application.  I don’t think, however, that this is going to be the norm if your application is public facing on the web – I see sockets right now being more for business applications.  Some resources for Sockets:

Working with Sockets requires you to really understand your deployment scenario first before you jump right in and think this will be the best method.

File Access

Silverlight can communicate with local data or data on the web.  For local data access, the application does not have direct access to the file system, but rather can read/write data via user-initiated actions using the OpenFileDialog and SaveFileDialog APIs to request and save streams of data to the local user’s machine.

Additionally, you can use plain text files or XML files on the web and have your Silverlight application use standard HTTP commands to read/write that information.  Here’s some helper information on using some of these methods:

You may find yourselves using these techniques to save settings-based data or use very simple data access.

Web Services

This is the heart of accessing data in Silverlight – through a service layer.  Silverlight supports accessing standard ASP.NET web services (ASMX) or WCF-based services using the familiar Add Service Reference methods in Visual Studio that will generate strongly-typed proxy code for you.

Additionally you can use the standard HTTP verbs to access more POX (Plain old XML) or REST-based endpoints.  Understanding how to consume these various service types is probably the best time spent a developer can educate themselves on understanding what will be right for their scenario.  Here’s some resources:

The third point there, .NET RIA Services, is a new framework that aims to make accessing data simpler and more familiar.  The link to the video will walk you through an introduction of that topic.  RIA Services is best when you own the database and are hosting services in the same web application that will be serving up the Silverlight application.

Asynchronous access

All data access in Silverlight is asynchronous.  This is perhaps another area that gets typical web developers tripped up initially.  For example in the server world it would be reasonable to see something like this:

   1: MyWebService svc = new MyWebService();
   2: string foo = svc.GetSomeValue();
   3: MyTextBox.Text = foo;

In Silverlight you wouldn’t be able to do that synchronous call.  To those who haven’t done asynchronous programming before this can be confusing, but it is well worth the learn and will make you a better developer.  Using the above pseudo code, in Silverlight you’d do something like this:

   1: MyWebService svc = new MyWebService();
   2: svc.Completed += new CompletedHandler(OnCompleted);
   3: svc.GetSomeValue();
   4:  
   5: void OnCompleted(object sender, EventArgs args)
   6: {
   7:     MyTextBox.Text = args.Result;
   8: }

Notice that you use the result of the service call in a completed event handler.  This is the pattern that you will see over and over again with basic service access.

Cross-domain data access

Since Silverlight is a web client technology, it operates in the browser’s secure sandbox area and are limited to certain access policies.  One of these restrictions is referred to as cross-domain access.  That is that your application hosted in one domain cannot access services in another domain unless the service says you can.  This “opt-in” approach is commonly known as cross-domain policy files.  Silverlight, like other rich client plug-ins, conforms to these policies.  This is an area that you as a Silverlight developer will likely hit at some point.  Educate yourself sooner than later.  Here are some pointers:

In our Twitter application, we actually will be accessing a service hosted elsewhere and will need to conform to these policies.  Luckily, the search API for Twitter enables this access through their cross-domain policy file (http://search.twitter.com/crossdomain.xml). The other areas of Twitter do NOT, which is why, for now, you would not be able to access them directly through Silverlight.  In this situation you would proxy those service calls through your own service that you could enable cross-domain access via a policy file for Silverlight.  Confusing?  It’s simpler than it sounds.

COMMON MYTH: You need the Silverlight and the Adobe cross-domain policy files in your service to enable access.  This is NOT TRUE and I see it to often people saying I have crossdomain.xml and clientaccesspolicy.xml and it still doesn’t work.  If you are building a service for Silverlight consumption via cross-domain, you only need the clientaccesspolicy.xml file format – that is what we look for first and is the most flexible and secure for Silverlight.

Now that we have a high-level overview, let’s start accessing our data!

Calling the Twitter API

The Twitter search API is a simple REST-based API that we’ll only really be calling GET requests on in our application.  The format they provide is the Atom specification which makes our job a lot easier because it is a standard format and Silverlight has framework libraries that support direct consumption of that format.

We will initiate calling the API when the user clicks the SEARCH button in our application and there is content in the search input box.  Let’s wire up an even to the click button like we did in step 1 in our Hello World application.  In our Search.xaml I’m adding the click event to our SearchButton.  Add the Click event handler to the SearchButton and use the name SearchForTweets as the function name:

   1: <Button x:Name="SearchButton" Width="75" Content="SEARCH" Click="SearchForTweets" />

In Visual Studio, if you right-click now on the function name, you can Navigate to Event Handler and it will generate the stub code for you in the code page.  In this function we’re going to search the Twitter API for postings matching our criteria.  Since the API is a simple REST GET call, we’re going to use the simple WebClient Silverlight API.  This is the simplest networking API to use and allows you to read/write data via GET/POST commands as long as you don’t need to alter headers.  Before we do that I’m going to set up some member variables for some tracking that we’ll use to monitor our search terms:

   1: const string SEARCH_URI = "http://search.twitter.com/search.atom?q={0}&since_id={1}";
   2: private string _lastId = "0";
   3: private bool _gotLatest = false;

Now we can wire up our SearchForTweets function.  Remember that I mentioned that network activity is asynchronous in Silverlight?  This is where we will start experiencing this.  We’re going to use the OpenRead API on WebClient.  Because the function will be asynchronous, we’ll need to wire up a Completed event handler to receive the response and do whatever we need with it.  Here’s what we have so far:

   1: private void SearchForTweets(object sender, RoutedEventArgs e)
   2: {
   3:     WebClient proxy = new WebClient();
   4:     proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
   5:     proxy.OpenReadAsync(new Uri(string.Format(SEARCH_URI, HttpUtility.UrlEncode(SearchTerm.Text), _lastId)));
   6: }
   7:  
   8: void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
   9: {
  10:     throw new NotImplementedException();
  11: }

Notice we first create a new WebClient instance.  Then we set up the completed event handler, and finally call the OpenReadAsync funciton with a formatted URI.  The result in our completed handler (e.Result) will be a stream.  Because we are going to manipulate the response a bit and do some databinding, we’re going to create a local class to represent the structure of our search result.  I called mine TwitterSearchResult.cs and is just a class file in my project under a folder called Model:

   1: using System;
   2: using System.Windows.Media;
   3:  
   4: namespace TwitterSearchMonitor.Model
   5: {
   6:     public class TwitterSearchResult
   7:     {
   8:         public string Author { get; set; }
   9:         public string Tweet { get; set; }
  10:         public DateTime PublishDate { get; set; }
  11:         public string ID { get; set; }
  12:         public ImageSource Avatar { get; set; }
  13:     }
  14: }

With our model in place we can shape the result and do some data binding.

Other networking options: HttpWebRequest and ClientHttp

There are two other network APIs we could have used to access the Twitter API: HttpWebRequest and ClientHttp.  HttpWebRequest is essentially what we *are* using with WebClient as it is a simple wrapper around that API.  If you needed more granular control over the headers in the request, you’d want to use HttpWebRequest.  Both WebClient and HttpWebRequest make use of the browser’s networking stack.  This presents some limitations, namely not being able to receive all complete status codes or leverage some expanded verbs (PUT/DELETE).  Silverlight has also introduced a ClientHttp option and uses a custom networking stack that enables you to use more verbs as well as receive status code results beyond 200/404.

More information:

As an example if we wanted to use ClientHttp, our call would look like this:

   1: private void SearchForTweets(object sender, RoutedEventArgs e)
   2: {
   3:     bool httpBinding = WebRequest.RegisterPrefix("http://search.twitter.com", 
   4:                 WebRequestCreator.ClientHttp);
   5:     WebClient proxy = new WebClient();
   6:     proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
   7:     proxy.OpenReadAsync(new Uri(string.Format(SEARCH_URI, HttpUtility.UrlEncode(SearchTerm.Text))));
   8: }

Note that we *are not* using this method, but just wanted to point these out for you.  The call to RegisterPrefix denotes that we registered it to use the ClientHttp networking stack instead of the browser’s networking stack.  In the above sample we registered only calls to the Twitter search domain, but we could have enabled it for all HTTP requests as well.

These are additional options for you to consider in your applications.

Start simple binding some data with smart objects

Because our application is going to ‘monitor’ search terms in Twitter, we want to really just set up binding to an object collection once, and then just manipulate that collection (in our case, add to it).  To do this we are going to use two helpful objects in Silverlight: ObservableCollection<T> and PagedCollectionViewObservableCollection is a collection type that automatically provides notifications when items are modified within the collection (added, removed, changed).  PagedCollectionView will be used to help us automatically give some sorting to our objects. 

We’ll create these as member variables in our project:

   1: ObservableCollection<TwitterSearchResult> searchResults = new ObservableCollection<TwitterSearchResult>();
   2: PagedCollectionView pcv;

Now that we have the member variables, let’s initialize the PagedCollectionView in the constructor of the control so it will be available quickly.  We also want to bind our UI to our elements in the XAML.  It is good practice not to do anything to your UI in the constructor of your UserControl (in our case Search.xaml).  Because of this we’ll add a Loaded event handler in the constructor and set up the initial binding in that handler.  Our combination of constructor and Loaded event handler now looks like this:

   1: public Search()
   2: {
   3:     InitializeComponent();
   4:  
   5:     pcv = new PagedCollectionView(searchResults);
   6:     pcv.SortDescriptions.Add(new System.ComponentModel.SortDescription("PublishDate", System.ComponentModel.ListSortDirection.Ascending));
   7:  
   8:     Loaded += new RoutedEventHandler(Search_Loaded);
   9: }
  10:  
  11: void Search_Loaded(object sender, RoutedEventArgs e)
  12: {
  13:     SearchResults.ItemsSource = pcv;
  14: }

Notice that in the loaded handler we set the ItemsSource property of our DataGrid (SearchResults) to be the PagedCollectionView that is sorted (see the SortDescription we added in line 6 above).  Now our UI is bound to this PagedCollectionView…so we should probably populate it.  Remember that it is actually a view of the data in our ObservableCollection<TwitterSearchResult> – so that is what we need to add items to in order for some data to be seen.

Populating our ObservableCollection

Now go back to the OnReadCompleted function we had before that will fire after our network request to the search API.  We now are going to populate our ObservableCollection in this function.  Here’s the code we’ll use to do that:

   1: void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
   2: {
   3:     if (e.Error == null)
   4:     {
   5:         _gotLatest = false;
   6:         XmlReader rdr = XmlReader.Create(e.Result);
   7:  
   8:         SyndicationFeed feed = SyndicationFeed.Load(rdr);
   9:  
  10:         foreach (var item in feed.Items)
  11:         {
  12:             searchResults.Add(new TwitterSearchResult() { Author = item.Authors[0].Name, ID = GetTweetId(item.Id), Tweet = item.Title.Text, PublishDate = item.PublishDate.DateTime.ToLocalTime(), Avatar = new BitmapImage(item.Links[1].Uri) });
  13:             _gotLatest = true;
  14:         }
  15:  
  16:         rdr.Close();
  17:     }
  18:     else
  19:     {
  20:         ChildWindow errorWindow = new ErrorWindow(e.Error);
  21:         errorWindow.Show();
  22:     }
  23: }
  24:  
  25: private string GetTweetId(string twitterId)
  26: {
  27:     string[] parts = twitterId.Split(":".ToCharArray());
  28:     if (!_gotLatest)
  29:     {
  30:         _lastId = parts[2].ToString();
  31:     }
  32:     return parts[2].ToString();
  33: }

A few things are happening here.  First, the e.Result matches the Stream of response we’ll get from a successfull search.  If an error occurs, we’ll use the ErrorWindow template which is provided for us in the navigation application template we chose.  The _gotLatest member variable helps us track the whether or not we need to reset the max value (which is so future queries request only the latest since the previous query).  After we get the stream we load it into an XmlReader for ease of parsing with our SyndicationFeed class.  SyndicationFeed is a class in the System.ServiceModel.Syndication library that you’ll have to add a reference too in your project.  It has built-in functions for parsing known syndication formats, like RSS and Atom.

NOTE (Here be dragons): System.ServiceMode.Syndication brings with it other dependency assemblies.  It is not a small library, but convenient to have.  Take caution in using it for your project and know when and why you need it.  We are using it here so you can be aware of the features and productivity benefits.  An alternative method (especially for just reading syndicated feeds) would be to actually just use LINQ to XML and query the resulting XDocument after loading it.  Again, for demonstration purposes, I wanted to point out the productivity use of SyndicationFeed as a strongly-typed class available to you. 

More information about reading Syndication data can be found here:

Once we have the SyndicationFeed data loaded, we simply iterate through it and add a new TwitterSearchResult to our ObservableCollection<TwitterSearchResult> object.  You’ll notice we’re doing some conversion on the Image URI to an ImageSource for easier binding later.  Additionally, we’re parsing out the ID of the tweet so we can set the first result (which is the latest) as the most recent ID for later querying (_lastId).

Giving feedback back to our users

In our final step here, we want to make sure we are giving some feedback to our users that we are doing something (searching).  Luckily we have something easy for you in an ActivityControl.  At the time of this writing, the ActivityControl was a part of the .NET RIA Services templates, but you can get it here on David Poll’s blog.  You’ll have to build the control and then add a reference to it in your project (if you download the source to our projects the binary is already included in the Libraries folder for you).

UPDATE NOTE: While the contents of this tutorial remains unchanged, the ActivityControl is now called the BusyIndicator and is released as a part of the Silverlight Toolkit.  Following the same techniques you can get the official control from the toolkit and have it deployed with your application.  No more need to compile on your own.

Once you have the reference, then you’ll add the same xmlns notation in your Search.xaml like we did with the DataGrid in step 2.  Then add the control as the root control and the Grid as it’s child.  My resulting Search.xaml now looks like this:

   1: <navigation:Page 
   2:            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   3:            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   4:            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   5:            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   6:            mc:Ignorable="d"
   7:            xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
   8:            xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="TwitterSearchMonitor.Views.Search"
   9:            xmlns:activity="clr-namespace:System.Windows.Controls;assembly=ActivityControl"
  10:            d:DesignWidth="640" d:DesignHeight="480"
  11:            Title="Twitter Search Page">
  12:     <activity:Activity x:Name="ActivityIndicator">
  13:         <Grid x:Name="LayoutRoot">
  14:             <Grid.RowDefinitions>
  15:                 <RowDefinition Height="32"/>
  16:                 <RowDefinition/>
  17:             </Grid.RowDefinitions>
  18:  
  19:             <StackPanel HorizontalAlignment="Left" Margin="0,-32,0,0" VerticalAlignment="Top" Grid.Row="1" Orientation="Horizontal">
  20:                 <TextBox x:Name="SearchTerm" FontSize="14.667" Margin="0,0,10,0" Width="275" TextWrapping="Wrap"/>
  21:                 <Button x:Name="SearchButton" Width="75" Content="SEARCH" Click="SearchForTweets" />
  22:             </StackPanel>
  23:             <data:DataGrid x:Name="SearchResults" Margin="0,8,0,0" Grid.Row="1"/>
  24:         </Grid>
  25:     </activity:Activity>
  26: </navigation:Page>

In our code for starting the search (SearchForTweets) simply add the line:

   1: ActivityIndicator.IsActive = true;

and when the OnReadCompleted event is done add the line:

   1: ActivityIndicator.IsActive = false;

And you’ll have visual progress to the end user.  At this point we can run our application (F5) and enter a search term.  You’ll see the activity control:

ActivityControl view

And then the resulting view of results in the DataGrid:

Search result view

Add some monitoring via timers

Now since we call this a monitoring service, we want the search to automatically refresh for us.  Silverlight provides a few different ways to trigger automatic activity.  We’re going to use a DispatcherTimer for our application.  This is nothing more than a timer that fires a Tick event handler at our defined interval.  We’ll add another member variable:

   1: DispatcherTimer _timer;

and then in the constructor initiate our timer with adding an event handler:

   1: double interval = 30.0;
   2:  
   3: _timer = new DispatcherTimer();
   4: #if DEBUG
   5: interval = 10.0;
   6: #endif
   7: _timer.Interval = TimeSpan.FromSeconds(interval);
   8: _timer.Tick += new EventHandler(OnTimerTick);

Now we want to refactor some code, because we want the SearchForTweets to be fired on the timer tick event.  We’re going to use Visual Studio refactoring tools to extract the method function code from SearchForTweets into a new method SearchForTweetsEx which we’ll call in our Tick event handler OnTimerTick.  We’ll also modify our Loaded event to actually start the timer and start the initial search for us (note our Timer is going to have a DEBUG interval of 10 seconds, otherwise 30 seconds).  Our refactored complete Search.xaml.cs now looks like this:

   1: using System;
   2: using System.Collections.ObjectModel;
   3: using System.Net;
   4: using System.Net.Browser;
   5: using System.ServiceModel.Syndication;
   6: using System.Windows;
   7: using System.Windows.Browser;
   8: using System.Windows.Controls;
   9: using System.Windows.Data;
  10: using System.Windows.Media.Imaging;
  11: using System.Windows.Navigation;
  12: using System.Windows.Threading;
  13: using System.Xml;
  14: using TwitterSearchMonitor.Model;
  15:  
  16: namespace TwitterSearchMonitor.Views
  17: {
  18:     public partial class Search : Page
  19:     {
  20:         const string SEARCH_URI = "http://search.twitter.com/search.atom?q={0}&since_id={1}";
  21:         private string _lastId = "0";
  22:         private bool _gotLatest = false;
  23:         ObservableCollection<TwitterSearchResult> searchResults = new ObservableCollection<TwitterSearchResult>();
  24:         PagedCollectionView pcv;
  25:         DispatcherTimer _timer;
  26:  
  27:         public Search()
  28:         {
  29:             InitializeComponent();
  30:  
  31:             // set interval value for Timer tick
  32:             double interval = 30.0;
  33:  
  34:             _timer = new DispatcherTimer();
  35: #if DEBUG
  36:             interval = 10.0;
  37: #endif
  38:             _timer.Interval = TimeSpan.FromSeconds(interval);
  39:             _timer.Tick += new EventHandler(OnTimerTick);
  40:  
  41:             // initialize our PagedCollectionView with the ObservableCollection
  42:             // and add default sort
  43:             pcv = new PagedCollectionView(searchResults);
  44:             pcv.SortDescriptions.Add(new System.ComponentModel.SortDescription("PublishDate", System.ComponentModel.ListSortDirection.Descending));
  45:  
  46:             Loaded += new RoutedEventHandler(Search_Loaded);
  47:         }
  48:  
  49:         void OnTimerTick(object sender, EventArgs e)
  50:         {
  51:             SearchForTweetsEx();
  52:         }
  53:  
  54:         void Search_Loaded(object sender, RoutedEventArgs e)
  55:         {
  56:             SearchResults.ItemsSource = pcv; // bind the DataGrid
  57:             _timer.Start(); // start the timer
  58:             SearchForTweetsEx(); // do the initial search
  59:         }
  60:  
  61:         // Executes when the user navigates to this page.
  62:         protected override void OnNavigatedTo(NavigationEventArgs e)
  63:         {
  64:         }
  65:  
  66:         private void SearchForTweets(object sender, RoutedEventArgs e)
  67:         {
  68:             SearchForTweetsEx();
  69:         }
  70:  
  71:         /// <summary>
  72:         /// Method that actually does the work to search Twitter
  73:         /// </summary>
  74:         private void SearchForTweetsEx()
  75:         {
  76:             if (!string.IsNullOrEmpty(SearchTerm.Text))
  77:             {
  78:                 _timer.Stop(); // stop the timer in case the search takes longer than the interval
  79:                 ActivityIndicator.IsActive = true; // set the visual indicator
  80:  
  81:                 // do the work to search twitter and handle the completed event
  82:                 WebClient proxy = new WebClient();
  83:                 proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
  84:                 proxy.OpenReadAsync(new Uri(string.Format(SEARCH_URI, HttpUtility.UrlEncode(SearchTerm.Text), _lastId)));
  85:             }
  86:         }
  87:  
  88:         /// <summary>
  89:         /// Method that fires after our SearchForTweetsEx runs and gets a result
  90:         /// </summary>
  91:         /// <param name="sender"></param>
  92:         /// <param name="e"></param>
  93:         void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
  94:         {
  95:             if (e.Error == null)
  96:             {
  97:                 _gotLatest = false; // reset the latest detector
  98:                 XmlReader rdr = XmlReader.Create(e.Result); // load stream into a reader
  99:  
 100:                 SyndicationFeed feed = SyndicationFeed.Load(rdr);  // load syndicated feed (Atom)
 101:  
 102:                 // parse each item adding it to our ObservableCollection
 103:                 foreach (var item in feed.Items)
 104:                 {
 105:                     searchResults.Add(new TwitterSearchResult() { Author = item.Authors[0].Name, ID = GetTweetId(item.Id), Tweet = item.Title.Text, PublishDate = item.PublishDate.DateTime.ToLocalTime(), Avatar = new BitmapImage(item.Links[1].Uri) });
 106:                     _gotLatest = true; // reset the fact that we already have the max id needed
 107:                 }
 108:  
 109:                 rdr.Close();  // close the reader
 110:             }
 111:             else
 112:             {
 113:                 // initialize our ErrorWindow with exception details
 114:                 ChildWindow errorWindow = new ErrorWindow(e.Error);
 115:                 errorWindow.Show();
 116:             }
 117:             ActivityIndicator.IsActive = false; // reset the UI
 118:             _timer.Start(); // reset the timer
 119:         }
 120:  
 121:         /// <summary>
 122:         /// Parses out the Tweet ID from the tweet
 123:         /// </summary>
 124:         /// <param name="twitterId"></param>
 125:         /// <returns></returns>
 126:         private string GetTweetId(string twitterId)
 127:         {
 128:             string[] parts = twitterId.Split(":".ToCharArray());
 129:             if (!_gotLatest)
 130:             {
 131:                 _lastId = parts[2].ToString();
 132:             }
 133:             return parts[2].ToString();
 134:         }
 135:     }
 136: }

The flow will be that our Search page will load, start the timer and start the initial search.  After the interval time fires, the search will be executed again, but remember it will use the last known ID to start from as not to load all the repeats again.  This future search data will be added to our ObservableCollection and since the DataGrid is already bound to that, it will be automatically represented in the UI in the appropriate sort order.

We also added some checking to make sure the search term is there and we’re not searching for a blank value.

Summary

At this point of step 3 we’ve made a lot of progress.  We’ve wired up a service call to a 3rd party service, hooked it up to a DataGrid using binding, and added a timer to automatically fetch the service.  We could be done, but we’re not – the DataGrid isn’t exactly how we want to represent the final UI,  Let’s move on to part 4 where we actually do some data templating and introduce you to the XAML binding syntax.

This work is licensed under a Creative Commons Attribution By license.

  1. 10/6/2009 5:02 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Heya, nice tutorial. The "Working with Data in Sockets" link is dead though.
  2. 10/6/2009 5:51 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Ross - I just clicked on it and it came up for me?
  3. 10/6/2009 8:09 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    I'm working through this, but I'm running to a problem with HttpUtility.

    VS 2008 is not recognizing it. I try to add System.Web under the using statements, but when I type in "using System." intellisense doesn't see "Web". So I check my references. System.Web.dll is not referenced. I go to add it from the .NET tab. It's not there. When I do find a copy of system.web.dll, vs 2008 pops up with an error message telling me that it was not built against silverlight runtime.

    I ran across a blog on msdn concerning the release of .net 3.5 and I read this:

    The following assemblies are included in the beta release of the Client Profile but will be removed in the RTM release:

    jsc
    Microsoft.JScript
    Microsoft.Vsa
    System.DirectoryServices.Protocols
    System.Management
    System.Messaging
    System.ServiceProcess
    System.Web
    System.Web.Extensions
    System.Web.RegularExpressions

    link blogs.msdn.com/.../...ofile-justin-van-patten.aspx

    I'm not sure what to do. Up to this point, the project built and ran fine.
  4. 10/6/2009 11:27 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Ok, after hours of trying to fix this, it seems I was looking at the wrong HttpUtility class.

    The one found in System.Web.dll is part of .net framework
    The one found in System.Windows.Browser is for silverlight.

    I'll attempt this again in a few days when I get a chance.
  5. 10/7/2009 7:50 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    John -- if using Visual Studio, SHIFT+ALT+F10 is your friend. When a class name doesn't resolve, put your mouse cursor near it and you'll see a little smart tag. You can either click that or SHIFT+ALT+F10 and it will add the using statements for you. However, if an assembly reference is needed (in this case it wasn't) you'll have to have that in place.
  6. 10/10/2009 12:27 AM | # TO:John
    i met the same problem today, finally i found HttpUtility in System.Windows.Browser
  7. 10/10/2009 6:58 AM | # re: Expressions 3
    Will expressions be integrated into VS2010?

    Just wondering....
  8. 10/10/2009 10:25 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    after clicking the SEARCH button, the following error occured:
    at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
    at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
    at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
    at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)
    what is that problem?
  9. 10/14/2009 6:41 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    > Will expressions be integrated into VS2010?
    Great question - seems odd not to have at least minimal visualizer built in.
  10. 10/15/2009 12:47 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    after clicking the SEARCH button, the following error occured:

    Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

    proxy.OpenReadAsync(new Uri(string.Format(SEARCH_URI, HttpUtility.UrlEncode(SearchTerm.Text))));

    Please advise
  11. 10/16/2009 3:05 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Barak -- Expression Blend will continue to be a separate product. Some XAML editable design surfaces will exist in VS2010 for Silverlight though but not the ability to do animations, etc.

    Bruce/Andy - are you running it from an HTTP instance? Bruce what term are you using, perhaps there are no results (and we should better indicate error viewing).
  12. 10/17/2009 5:08 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    the void OnReadCompleted() never get fired. I am using IE8. Is there any settings that I have to configure?
  13. 10/20/2009 12:42 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Great series of tutorials, very much appreciated.
  14. 10/21/2009 5:52 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Good tutorial, but not for beginners.
  15. 10/21/2009 11:23 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Denis -- how could this be better for beginners? This is part 3 of a 7 part series...and this is the basics of simple data access.
  16. Gravatar
    10/22/2009 11:25 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    He probably means not for beginner programmers/"csharpers" or something, I'm new to Silverlight and this tutorial is great.
  17. 10/26/2009 10:41 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Man, I don't really know C#. How am I supposed to understand all this? I thought this was for beginners i.e. no c# experience and no silverlight experience.
  18. 10/26/2009 10:49 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Oluwaseun - You'll have to understand .NET programming in order to understand this. I should make that clear. This is definitely for beginners *to Silverlight* but not to .NET. I would consider checking out http://msdn.microsoft.com for other basic .NET information or picking up a good text on C# or Visual Basic.
  19. 10/27/2009 12:36 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Thanks Tim. I'll take a break from this particular tutorial and get a good C# book. Meanwhile, I'll look at other silverlight videos and continue to learn. Thanks again for the advise. Cheers.
  20. 10/27/2009 8:56 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    this was my first silverlight experience ans i was amazed at what i created after i did your "course". thanx for getting me going.
  21. 10/28/2009 7:30 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hey tim, good tutorial. But when i try a new search the previous result returns.
    Maybe im doing smt wrong.
  22. 10/28/2009 10:08 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Dimeji - hard to tell -- if you download the final project does it exhibit that behavior as well?
  23. 11/3/2009 9:18 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi Tim,

    Great tutorial!

    I have VS2010 Beta 2 installed and I'm trying to follow your tutorial but I've come up against a showstopper. I cannot resolve PagedCollectionView. It is neither in System.Windows.Data as stated in http://msdn.microsoft.com/en-us/library/cc645049(VS.95).aspx. Nor is it in System.ComponentModel where it used to be. Do you know where I might find this class in VS2010 Beta 2
  24. 11/3/2009 9:22 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi Tim,

    I'm trying to follow this tutorial in VS2010 Beta2 but I cannot resolve the reference to PagedCollectionView. It isn't in System.Windows.Data where it is said to be now and neither is it in System.ComponentModel where it used to be. Any ideas?
  25. 11/3/2009 9:23 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Shaun - it is in the System.Windows.Data namespace. Make sure you have a refernce to that assembly. See the completed downloadable project.
  26. 11/3/2009 9:33 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi Tim,

    Phew that was quick. You are absolutely right. Sorry, I'm having a stupid day today.

    Many thanks! Great article!!
  27. 11/4/2009 3:03 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi Tim. I also get an exception when clicking the search button. This also happens for me with the downloadeded project file.


    at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
    at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
    at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
    at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)

    On examining e.Error in OnReadCompleted, there is an inner exception which is a security error exception. Is there any security config which needs to happen to get this working? Cross-domain access? Firewalls? Thanks.
  28. 11/4/2009 3:38 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    BTW, I don't seem to be able to access http://search.twitter.com/crossdomain.xml. I will try to switch to using RIA Services if I can figure it out.
  29. 11/4/2009 4:48 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi there,

    Encountered the same error and while watching one of Tim's tutorial on Silverlight security, he mentioned the best practice where to put the cross domain policy - Twitter moved theirs here:

    http://api.twitter.com/crossdomain.xml

    But can't still get mine working :)

  30. 11/4/2009 7:54 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Toby, make sure you are marking the WEB project as startup -- sounds like you might be just running the Silverlight application.
  31. 11/4/2009 8:01 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Rosa/Toby -- it does appear that there is an issue with the Twitter search API -- I don't see any announcements of them changing it but have started contacting their support to find updates.
  32. 11/4/2009 11:51 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    I get a security violation when I go to twitter. Any ideas?
  33. 11/4/2009 12:56 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Eugene - See note above your comment -- Twitter appears to be having an issue with their search API at the moment.
  34. 11/4/2009 2:22 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hey Tim:

    I have an error when try tu search any word in my application, this an exception security in if (e.Error == null) e.Error have an exception security.

    How i can resolv this?
  35. 11/4/2009 2:24 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Jose -- see previous notes -- Twitter is having a problem with their API today (4-Nov-2009)
  36. 11/4/2009 3:34 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Thank you for your Great tutorial!
    would you please replace tweeter with another search API so we can see the result?
  37. 11/4/2009 3:37 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    behdad -- I used Twitter because it was a) a publically available API and b) didn't require any setup and c) used a response format that is common (RSS). You can replace this with other services. For example, Bing.com has an API that you could use this for, but you have to register, sign up for the API and specify an API key in your call. I tried to keep this as simple as possible to set up.

    Unfortuantely I don't control the ending API, and thus Twitter is having issues. I hope that they resolve them soon so that I don't have to redo these tutorials!
  38. 11/5/2009 1:59 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Is the Twitter API working yet? Unfortunately by the time I was done with this part, API stopped working and I couldn't see the app working :(
  39. 11/6/2009 3:54 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Anyone get it working yet.

    I keep getting the following error.

    InnerException = {System.Security.SecurityException: Security error.
    at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
    at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
    at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
  40. 11/6/2009 3:55 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Mark -- make sure you are running the WEB application as the startup (url in address bar http and not file)
  41. 11/7/2009 10:02 AM | # ActivityControl
    I'm having trouble with the ActivityControl. I have the dll and added a reference to it but when I try to create the xmlns reference it does not show that as a choice and if I type it manually it tells me it is trying to reference an assembly System.Windows.Control that is not included in the assembly.

    What am I missing?

    Thanks.
  42. 11/7/2009 11:24 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    RossT -- after you add the reference, let IntelliSense be your guide :-) -- ActivityControl always gets me too, look patiently through the intellisense list it should say System.Windows.Controls in ActivityControl. You can always manually type it in: xmlns:activity="clr-namespace:System.Windows.Controls;assembly=ActivityControl"
  43. 11/7/2009 2:18 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    That's the problem! I added the reference but IntelliSense doesn't see it. And I get the missing reference messge when I type it in manually.
  44. 11/7/2009 2:21 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    RossT - hmm...no errors in adding the reference? What if you do a build before you add any XMLNS declaration and see if that wakes up IntelliSense?
  45. 11/9/2009 7:30 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Tim,

    I added the ActivtyControl project, did a rebuild, and added reference. Now IntelliSense sees it but I still get the namespace error. I have Live Meeting. Can we take this private and have you connect and take a quick peek to see what's wrong? Thanks.
  46. 11/9/2009 7:38 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Tim,

    I am running the web application as the startup page.
    I told it to create a web project to host my SL app.

    So it automatically defaults the web application to run the SL app for me.
  47. 11/9/2009 7:42 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Mark -- I found out that Twitter did have another problem with their API again, but it has since been resolved (See: groups.google.com/.../4adf2a0297ce052d for the discussion). I created this sample using a freely available public API with low/no impact for setup. Unfortunately that comes with some risk. I apologize for that but wanted folks to learn Silverlight with minimal setup versus fiddling with account setups, database installations, etc.

    Try it again though Mark and it should be working.
  48. 11/9/2009 7:45 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Tim,

    Never mind LOL, I changed my configuration to use http://localhost/MyApp instead of http://localhost:2388

    I think you were trying to tell me that.

    Sorry for the confusion.

    Thanks,
    Mark
  49. 11/11/2009 3:32 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hello, Tim.

    Excellent tutorial!!

    I have a problem.

    When I initialize sourceResults from ObservableCollection<TwitterSearchResult>,
    then I can't reference to sourceResults.ItemsSource

    System.Collections.ObjectModel.ObservableCollection seems hasn't a itemsSource Metod. it derives from Collection, INotifyCollectionChanged, INotifyPropertyChanged

    any reference lost?

    Thanks.

    Juan Manuel
  50. 11/11/2009 3:42 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Sorry!!!

    I had confused!

    sourceResults is typeof ObservableCollection,
    and
    SourceResults is typeof Datagrid, and Datagrid has ItemsSource.

    Mistake resolved!

    Thanks.

    Juan Manuel.
  51. 11/12/2009 1:09 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    hi Tim,
    Thanks for this gr8 article you have put up.

    Is the Twitter API in working mode. i am still getting this error...

    The remote server returned an error: NotFound.

    at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
    at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
    at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
    at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)
  52. 11/12/2009 1:11 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    shanks -- make sure you are running from the WEB application.
  53. 11/12/2009 2:24 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    yes tim, i have TwitterSearchMonitor.Web as my Startup project. and it shows this in the browser url localhost:1358/.../Search
    still the same error. BTW thanks for the quick reply.
  54. 11/12/2009 3:28 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    shanks - use a tool like fiddler and look at the actual HTTP response message.
  55. 11/12/2009 8:48 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    My finished project only works on the first search. I have combed my Search.xaml.cs and I just cannot figure out what is wrong. Everything works as expected the first time I click the search button however no other button presses register. I am at a loss...
  56. 11/13/2009 2:37 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    James -- using the same search term? If so, the search will only get results since the last search. Using a term like 'twitpic' on Twitter usually yields constant new results. If not, if you download and run the completed project does it work as expected?
  57. 11/13/2009 6:26 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    hi Tim, i see these responses in the fiddler output

    1. GET http://search.twitter.com/clientaccesspolicy.xml 404 Not Found (text/html)
    2. search.twitter.com /crossdomain.xml response = 200
    3. GET search.twitter.com/search.atom 403 Forbidden (application/xml)

    any suggestions?

    thanks for helping.
  58. 11/13/2009 6:29 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    shanks -- looks like your query URL has an additional "=" character at the beginning of the query string. It should be ?q= instead of ?=q=
  59. 11/13/2009 6:49 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    wow. that solved it. gr8 catch. i am baffled. how did you catch it?

    thanks... i'll move on with the next part of the series. it was really frustating to stuck on the data retrieval part....
  60. 11/13/2009 7:18 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    shanks -- i just pasted your URL into the browser to see if there was any difference, then noticed it wasn't properly formatted.
  61. 11/13/2009 2:33 PM | # NULL result items
    weird, sometimes when I perform the search I can see a number of IEnumerable<results> in the debugger, say 40, but when looping to add them to the ObservableCollection some of them are NULL? like I needed to flush the stream or something. Has that happened to anyone else?
  62. 11/13/2009 2:40 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    I am getting these two errors
    I do have the
    Using System.Windows.Data;

    1.
    The type or namespace name 'TwitterSearchResult' could not be found (are you missing a using directive or an assembly reference?)

    2.
    The type or namespace name 'PagedCollectionView' could not be found (are you missing a using directive or an assembly reference?) C:\SilverlightStudy\TwitterSearchMonitor\TwitterSearchMonitor\Views\Searc
  63. 11/13/2009 3:22 PM | # re: NULL result items
    belay my last. I figured it out.
  64. 11/17/2009 11:33 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    figured out 1. misspelled TwitterSearchResult in the class def
    and 2 did not refrerance System.Windows.Data;
  65. 11/21/2009 10:07 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Cool tutorial but I have two questions

    Do you know any basic tutorial on .net Asynchronous programming ? I am pretty much beginner on this.

    Secondly, Will I able to deploy the same code on cloud service?
  66. 11/25/2009 2:43 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi great tutorial.
    I have one problem.

    Inside the System.ServiceModel class, there is no option to select Syndication. I have made sure I have updated everything, and I know the class exists because it is in the msdn help. Is there a way to download and add this class manually?

    Thanks in advance
  67. 11/25/2009 3:17 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    ignore that last post, problem solved :)
  68. 11/25/2009 12:32 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Lewis

    Could you please tell us how did you solve this problem.

    Thanks
  69. 12/1/2009 12:03 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi Tim, excellent posts.
    Do you have any suggestions here? After I build and set the aspx as the start up page, I see the Search page, I type TimHeuer in the search box and click Search. Then I get this error: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
    I have googled the error and users mention to create a XmlReaderSettings instance. Any suggestions?
  70. 12/2/2009 12:24 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    It's great that the completed project can be downloaded in VB. It would be helpful to include the VB code in the post as well. The intermediate steps would be easier.
  71. Gravatar
    12/5/2009 7:02 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Thanks for this tutorial.

    I think you should try to use more clear wording in a beginner's tutorial than this:

    >Understanding how to consume these various service types is probably the best time spent a developer can educate themselves on understanding what will be right for their scenario.

    Also, I don't understand why wouldn't a simplified ADO.NET-like class library be applicable to Silverlight? You just pull your data at the server load it into the grid and then send all that to the client where they can page or sort or do whatever they like.

    By the way do you realize that just this page with all supporting files and graphics is over 1MB, even though the useful content is no more than 100KB? Unfortunately, with my comments I've contributed to that clutter as well :-(
  72. 12/5/2009 7:14 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Lou -- sorry about the page size -- this is a longer post. I admit that. The screenshots and content add value to the text...without them I would receive more comments :-) I hardly consider it clutter if it is relevant to the topic/content though. It's weird you would say that.

    As to ADO.NET-like class library -- there exists no ADO.NET functionality in Silverlight -- this is a CLIENT technology. Having an ADO.NET library would mean you are wanting to expose your data source over the public internet so that the user's browser can get to it. All data access in Silverlight is done via services. If you have your own data source, you can use a strongly-typed class library that mirrors your service/model layer. This is one aim of what WCF RIA Services (http://silverlight.net/riaservices) is trying to accomplish. You should check out those tutorials to understand that as well.
  73. Gravatar
    12/5/2009 11:22 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Thanks Tim, I obviously don't understand the model of silverlight yet. I 'll keep on reading, thank you for clarifying this for me. I'll investigate the RIA Services as soon as my head gets used to all the new concepts in this tutorial.

    The content of the page is really balanced and helpful, I didn't mean to complain about that. What I meant by clutter was more of an HTML/CSS type of overhead in the page markup, that really you can't do much about, as it is a matter of life these days. Once again thank you for the help, and keep on the good work.
  74. 12/10/2009 4:03 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Is there something missing in the tutorial zaml code I copied it the way it is in the tutorial when I debug I'm picking up the tweets in the debuger but only the header of the grid displays none of the tweets I downloaded the source code but it is differnt that the tutorial so I have no Idea where I'm going wrong
    it would be nice to see the source in iterations the code I got is the finished product
  75. 12/10/2009 4:16 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Rickj1 - if you post some of your code where you are at (or email to me) I would be happy to help point out the issue.
  76. 12/10/2009 4:52 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    I sent you an email great stuff your putting out
  77. 12/11/2009 7:10 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi Tim,

    when I add "using System.ServiceModel.Syndication" I have this error on Syndication: Type or naemspace name "Syndication" does not exist in the namespace "System.ServiceModel".

    Probably Lewis had the same problem but I don't know how he has fixed it.
  78. 12/11/2009 7:34 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi Tim,

    I have solved the problem in this way: right Click on reference and "Add Reference"; I have then added "System.ServiceModel.Syndication" and the error has disappeared.

    Have I doone the right thing? Why happened that?

    Thanks,

    Simone
  79. 12/11/2009 12:03 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    I cannot seem to get the avatars to appear. No errors, just no avatars. searchResults contains a valid URI for Avatar. I noticed, when inspecting it, that it says pixelheight and pixelwidth are both 0. Have I missed something?
  80. 12/11/2009 12:06 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Never mind. It's in the next part.
  81. Gravatar
    12/16/2009 2:57 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    hi Tim,
    Thanks for this gr8 article you have put up.

    Is the Twitter API in working mode. i am still getting this error...

    The remote server returned an error: NotFound.

    at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
    at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
    at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
    at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)
  82. 12/16/2009 7:32 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hi Tim, just to aid keeping this up to date I'll mention that you don't need to build the ActivityControl yourself or link to RIA or anything now.

    They've (probably you've) added it into the November Toolkit and called it "BusyIndicator". Works the same though it would appear.

    Thanks
    Andy

    P.s. this is the wrong forum for asking (but the only one I have) but what blog editor do you use? It looks fantastic for dropping in code samples.
  83. 12/16/2009 8:49 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    hou -- take a look at the network trace using Fiddler and see if it provides anymore clues.

    Andrew -- yes, in the November toolkit the indicator is in there! I haven't changed this yet just because I already had the structure in place, but probably a good thing to note somewhere.

    Blog editor/stuff - timheuer.com/.../...oolbox-tools-for-blogging.aspx
  84. 12/18/2009 4:44 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    I have searchterm text box on my Search.xaml file ,
    and in its CS file when I try to access this , it vs2008 gives error that
    "The name 'SearchTerm' does not exists in current cotext"
    <TextBox Name="SearchTerm" FontSize="14.667" Margin="0,0,10,0" Width="275" TextWrapping="Wrap"/>

    CS file for Saerch.xaml.cs

    proxy.OpenReadAsync(new Uri(string.Format(SEARCH_URI, System.Windows.Browser.HttpUtility.UrlEncode(SearchTerm.Text), _lastId)));
  85. 12/18/2009 6:52 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Note to Andrew Murphy - it's not so great if, like me, you print stuff out to read on the train! The code doesn't get wrapped by the print style sheet so you lose the ends of lines.

    The site itself is great, though - please don't take that as a complaint, Tim. I love it - learning loads.
  86. 12/18/2009 6:56 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Whoops! Fumble-fingers: posted before I'd finished.

    I was having the same problem as James Grizzle, except that very occasionally a second search would work. I've added the middle line, below, in SearchForTweets:

    ActivityIndicator.IsActive = true;
    _lastId = "0"; // since we have no Helper, yet.
    WebClient proxy = new WebClient();

    and that seems to have taken care of it.
  87. 12/18/2009 9:42 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Mian - you need x:Name not Name.
  88. Gravatar
    12/30/2009 2:59 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    I am still having issues with the Security Error that others noted above. I confirmed that my asp.net web app is the starting project as well.

    Any ideas?
  89. Gravatar
    12/30/2009 3:05 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Ah, actually, my company blocks the Twitter website, so I'll assume that is the issue. I tried navigating to http://search.twitter.com/search.atom?q={0}&since_id={1} and got a message from my company saying the site is blocked.
  90. 1/2/2010 8:26 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Great tutorial. I too am new to Silverlight. 2 thoughts so far:

    1. It seems a little odd to me that the LayoutRoot grid needs to be contained within the BusyIndicator. Something just doesn't feel right about that.

    2. I am not sure I like the behavior in which a call to the twitter web service may be triggered by the timer while the user is in the middle of typing something into the search text box. Would be nice to prevent that.
  91. 1/5/2010 3:57 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hey Tim, Question! I cant open the Design in an Silverlight(Navigation) Application in Visual Studio 2008 (Currently I used Blend 3), I tried everything like right click open in Design-View, can you help me please?
    Sorry about my english, I am using the german version of VS2008
  92. 1/6/2010 12:42 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Has anyone run into the problem where SyndicationFeed does not resolve? I don't have the "Resolve" option in the context menu, nor does manually adding a reference to System.ServiceModel.Syndication work. Intellisense recognized System.ServiceModel but not Syndication. There seem to be no sub-namespaces beyond System.ServiceModel.

    Any help would be great! Thanks in advance.
  93. 1/13/2010 12:52 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Jeremy - i had the same issue and to resolve it, i added this line to my Search.xaml.cs:

    using System.ServiceModel.Syndication.SyndicationFeed;
  94. 1/13/2010 12:56 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Ooops...I take that back Jeremy sorry....that didn't work either. Drat! Will let you know if i resolve.

    Melissa
  95. 1/13/2010 1:45 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Jeremy-

    Here is what i did...and I think Simone mentioned this in her comment above as well. So first, in the Solution Explorer, I added the System.ServiceModel.Syndication as a reference under the C# part of my project. Then in my Search.xaml.cs file, when i listed "using System.ServiceModel.Syndication;" and then it compiled without error. So doing those 2 things resolved it for me.
  96. 1/13/2010 12:15 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Is there anything wrong with:

    <StackPanel HorizontalAlignment="Left" Margin="0,-32,0,0" VerticalAlignment="Top" Grid.Row="1" Orientation="Horizontal">

    20: <TextBox x:Name="SearchTerm" FontSize="14.667" Margin="0,0,10,0" Width="275" TextWrapping="Wrap"/>

    21: <Button x:Name="SearchButton" Width="75" Content="SEARCH" Click="SearchForTweets" />

    22: </StackPanel>

    It shows a message error when I insert these codes.
    Thanks.
  97. 1/13/2010 12:25 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    what is the message you see?
  98. 1/18/2010 2:38 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Hey whats up with the System.ServiceModel.Syndication.dll in Silverlight 4.0? I cant find it anywhere? It makes it very difficult to follow this guide!
  99. 1/20/2010 8:35 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    any inputs on the search feature if i want to populate the datagrid with an xml file..and want to execute search on it .. ?
  100. 1/23/2010 1:12 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Could you please exemplify how can I use the BusyIndicator in the Search.xaml page?
    I've tried to reference it but it's not working.

  101. 1/23/2010 1:29 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Just to complete my question:

    I referenced the Toolkit is ths xaml page like this:
    xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"

    And when I try call the tag <controlsToolkit:BusyIndicator>, the only options are:
    <controlsToolkit:DockPanel> and <controlsToolkit:TreeViewConnectingLines>

    I have the Silverlight Toolkit NOV09 installed, and the System.Windows.Controls.Toolkit.dll referenced in the project.

    Thanks in advance.
  102. 1/23/2010 2:29 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Silas -- I recently had some intellisense hiccups myself with this control. You are in the right place. Try building the project before you enter the busyindicator and see if that helps VS wake up :-)
  103. 1/27/2010 2:03 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Tim, thanks, great tutorial!
    @Silas - Is the BusyIndicator in your toolbox? It should be. If so, drag from there onto the xaml and VS will insert the xmlns reference. I simply have this entry in the xaml and set the IsBusy property as described in the article.
    <data:DataGrid x:Name="SearchResults" Margin="0,8,0,0" Grid.Row="1"/>
    <controlsToolkit:BusyIndicator x:Name="BusyBox" Grid.Row="1" />
    @All - to have the app (at this point) handle changes to the search text (I had to play with it), you can add a TextChanged event handler to the TextBox with this code in the handler:
    private void SearchTerm_TextChanged(object sender, TextChangedEventArgs e)
    {
    _lastId = "0";
    searchResults.Clear();
    }
    You need to reset lastId for the call to twitter to get fresh items for the new search term and you need to clear the searchResults otherwise the new data is added to the old results (which is probably not what you want).
    Enjoy.
  104. 1/28/2010 2:41 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Tim, when I run the app nothing returns I am stuck at the loading screen. In debug the completed event never triggers to return the data from twitter. Any Ideas?
  105. 1/28/2010 5:58 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    John -- any errors in debug running mode? Also, make sure you are running the WEB app and not running from the file system (i.e., the address bar should say http and not file)
  106. 1/29/2010 6:54 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    <<< stupid error on my part, another Homer Simpson moment for me
    Here was my old code
    proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(proxy_OpenReadCompleted);
    proxy.OpenWriteAsync(new Uri(string.Format(SEARCH_URI, HttpUtility.UrlEncode(SearchTerm.Text), _lastId)));

    It should of been OpenReadAsync. I assume the app was looking for the OpenWriteCompleted event and could not find it. Once I changed it to OpenReadAsync all was well with the world again :). Thanks for the response. I may post again if I run into trouble with your tutorial. So far been a great intro to Silver Light.

    Thanks,
    John
  107. 1/31/2010 6:26 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Yep, VB users, you'll find the HttpUtility in the System.Windows.Browser namespace.


  108. Gravatar
    1/31/2010 11:49 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    For those of you continuing to have a problem with the Syndication reference, you can find the .DLL at:

    C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\System.ServiceModel.Syndication.dll

  109. 2/3/2010 4:49 AM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    While creating this apps, you need to add the following references also in your project:
    using System.Windows.Media.Imaging;
    using System.ServiceModel.Syndication;
  110. 2/4/2010 5:44 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    1st, Awesome tutorial!
    2nd-- I'm super beginner, but have come this far by learning as I go. I learn pretty fast. I just have super spotty programming experience.

    3rd-- These may be basic questions, but...

    a) when we are adding member variables, where exactly are we adding these?
    b) I was using VS2010, but switched to 2008 recently because I thought my silverlight tools weren't showing up (problem solved) and now can't get a design view with .xaml or .cs tabs in VS2008. I get the Split view with aspx though. Is there a reason?

    Though I don't exactly know .net or c#, I'm picking it up quickly. I am comfortable with fundamental concepts, so this project is really helping me!
    Thanks again!
  111. 2/4/2010 6:36 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    Rhett -- glad you are getting started!

    a) you can add them anywhere within the Class you are putting them in...just not in any function/constructor -- take a look at some of the source for an example

    b) VS2008 doesn't have a XAML design view as of Silverlight 3, only code views for XAML/c#/VB.

    You can also take a look at the video walk through of this as well: silverlight.net/.../twitter-search-monitor/
  112. 2/8/2010 1:17 PM | # re: Getting started with Silverlight: Part 3 – Accessing Data
    The video is EXACTLY what I needed! Thanks!
  113. 2/9/2010 3:37 AM | # reference problems
    Ok, I started all over with the video. Now I have a real question!

    VS2008 doesn't seem to recognize HttpUtility.
    I seem to be missing the reference "System.Web" -- at least that's what I can tell from my research.
    I looked in the .net tab under references, and I'm pretty sure I've installed everything, but it isn't there. Is there a place I can find the missing reference? Maybe there is something I'm missing here.
  114. 2/9/2010 3:47 AM | # Utility not there, but...
    I right click>resolve> using system.windows.browser

    This did it. Sorry if this was mentioned in earlier posts!

 
Please add 1 and 7 and type the answer here:
First time here? You are looking at the most recent posts. You may also want to check out older archives. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS or email. Thank you for visiting! (hide this)