Implement Twitter Search in Silverlight


In this article, I will cover and explain the following three topics.

  1. How to use twitter search and get search result on page using RIA concept.  
  2. Use of TextBox watermark
  3. How to change out of browser settings.

Let's get started. 

Getting Started: Creating Silverlight Project. 

  1. Open Visual Studio 2010.
  2. Go to File => New => Project
  3. Select Silverlight in installed templates
  4. Select Silverlight Application
  5. Enter the Name and choose the location.
  6. Click OK

First of all add a new class using Add New Item option on the right click on the project name in Solution Explorer and rename that class as following.

public class SearchedTweets

    {

        public string Title { get; set; }
        public Uri Image { get; set; }
     
          public Uri Link { get; set; }

    }

Now change your MainPage.xaml as following by adding a ListBox and other controls. I also have two Button controls - Get Tweets and Export to Excel. The Get Tweets buttons gets the tweets for the give twitter handle in the TextBox. 

xmlns:local="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls.WatermarkedTextBox"
<
Grid x:Name="LayoutRoot" Background="White">
       
<ListBox Margin="8,41,8,8"
                 HorizontalContentAlignment
="Stretch"
                 ScrollViewer.HorizontalScrollBarVisibility
="Disabled"
                 x:Name
="lstTweets">

           
<ListBox.ItemTemplate>
               
<DataTemplate>
                   
<Grid>
                       
<Grid.ColumnDefinitions>
                           
<ColumnDefinition Width="Auto" />
                           
<ColumnDefinition Width="*" />
                       
</Grid.ColumnDefinitions>

                       
<Image Source="{Binding Image}"
                               Grid.Column
="0"
                               Margin
="3"
                               Width
="50"
                               Height
="50"
                               Stretch
="UniformToFill" />

                       
<TextBlock Text="{Binding Title}"
                                   FontSize
="14"
                                   Margin
="3"
                                   Grid.Column
="1"
                                   TextWrapping
="Wrap" />

                   
</Grid>
               
</DataTemplate>
           
</ListBox.ItemTemplate>

        </ListBox>      
<Button x:Name="btnGetTweets" Width="80" Content="Get Tweets" VerticalAlignment="Top" Margin="147,9,169,0" Click="btnGetTweets_Click"/>     <Button x:Name="btnExport" Content="Export Tweets in Excel" HorizontalAlignment="Right" VerticalAlignment="Top" Width="155" Margin="0,8,10,0" Click="btnExport_Click" d:LayoutOverrides="HorizontalAlignment"/>      

        <local:WatermarkedTextBox Name="txtSearchText" Watermark="Enter search name..." Height="22" Margin="10,9,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="134"/>

    </Grid>


Now let's update the code behind. The MainPage.xaml.cs file looks like following. As you can see from this code, the Get Tweets method makes a call to the Twitter search, get results using LINQ and adds search results to the ListBox control including images and tweet text. The Export to Excel button simply creates an Excel sheet and export data from the ListBox to an Excel file.

Note: You must add reference to the Excel Interop library to use the Excel objects.

using System.Collections.ObjectModel;

using System.Xml.Linq;
using
System.Runtime.InteropServices.Automation;

ObservableCollection<SearchedTweets> objSearchedTweets = new ObservableCollection<SearchedTweets>();
        public MainPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }    


        void MainPage_Loaded(object sender, RoutedEventArgs e)

        {

            lstTweets.ItemsSource = objSearchedTweets;

          
// btnExport.IsEnabled = AutomationFactory.IsAvailable;

        }
 

        private void btnGetTweets_Click(object sender, System.Windows.RoutedEventArgs e)
        {
             
// TODO: Add event handler implementation here.
            if (!string.IsNullOrEmpty(txtSearchText.Text))
            {
                objSearchedTweets.Clear();
             
//  lstTweets.ItemsSource = null;
                WebClient objWebClient = new WebClient();
                objWebClient.DownloadStringCompleted += (s, ra) =>
                {
                    XDocument doc = XDocument.Parse(ra.Result);
                    XNamespace ns = "http://www.w3.org/2005/Atom";
                    var items = from item in doc.Descendants(ns + "entry")
                                select new SearchedTweets()
                                {
                                    Title = item.Element(ns + "title").Value,
                                    Image = new Uri((from XElement xe in item.Descendants(ns + "link")
                                                     where xe.Attribute("type").Value ==
"image/png"
                                                     select xe.Attribute("href").Value).First<string>()),
                                    Link = new Uri((from XElement xe in item.Descendants(ns + "link")
                                                    where xe.Attribute("type").Value ==
"text/html"
                                                    select xe.Attribute("href").Value).First<string>())
                                };
                    foreach (SearchedTweets t in items)
                    {
                        objSearchedTweets.Add(t);
                    }                 
                };
                objWebClient.DownloadStringAsync(new Uri("http://search.twitter.com/search.atom?q=" + txtSearchText.Text));
            }
           
else
            {
                MessageBox.Show("Type search text");
           }
        }

        private void btnExport_Click(object sender, System.Windows.RoutedEventArgs e)

        {
             
// TODO: Add event handler implementation here.

            if (objSearchedTweets.Count == 0)
            {
                MessageBox.Show("No tweets to export. Please get latest tweets first.");
                return;
            }
           
try
            {
                dynamic excel = AutomationFactory.CreateObject("Excel.Application");
                excel.workbooks.Add();
                dynamic sheet = excel.ActiveSheet;
                int row = 1;
               
// headers
                dynamic linkHeaderCell = sheet.Cells[row, 1];
                dynamic textHeaderCell = sheet.Cells[row, 2];
                linkHeaderCell.Value = "Url";
                textHeaderCell.Value = "Message Text";

                // rows

                foreach (SearchedTweets t in objSearchedTweets)
                {

                    row++;
                    dynamic linkCell = sheet.Cells[row, 1];
                   
dynamic textCell = sheet.Cells[row, 2];

                    linkCell.Value = t.Link.ToString();
                    textCell.Value = t.Title;

                }
                excel.Visible = true;

            }
            catch (Exception ex)

            {
                MessageBox.Show("Error automating Excel: " + ex.Message);

            }

        }


When you run the application, UI looks like the following Image 1 where you can see there is a Get Tweets button, As you can see from the above code, I make a call to the Twitter search service using the following line of code:

"http://search.twitter.com/search.atom?q=" + txtSearchText.Text

Click on the Get Tweets buttons gets the tweets and displays in the ListBox including the account image and URL.

img1.jpg

Image 1. 

img2.jpg

Image 2.

Now when you click on Export button you will get this error message.

img3.jpg

Image 3.

To remove this error message you need to right click on Properties and click Open and check this check box.

img4.jpg

Image 4.

After that click on Out-of-Browser Settings button and check these check boxes.

img5.jpg

Image 5.

Save the changes and click on Export button now. The output Excel document looks like Figure 6. 

img6.jpg

Image 6.


Summary

In this article, we saw how to create a Silverlight application that uses Twitter search to get tweets and display in a formatted way. We also saw how to export tweets in an Excel document.



Similar Articles