Sunday, 3 July 2011

Tweeter Search Application with Silverlight (Beginners); Your First Silverlight Application



For developers new to Silverlight or in a learning phase, this demo/article can help them creating a small application. This isn't just a hello world application; this is something more interesting than that. So are ready to get your hands dirty with some XAML code and a little bit of the power of Silverlight?

To create a Silverlight project you need the Silverlight library component installed on your computer. If you have Visual Studio 2010 installed then you are good to go as the Silverlight 3.0 project template can be found there.
  1. Open a new project -> and select the Silverlight application from the Silverlight template.

    Silverlight1.gif
     
  2. Now when you click OK you'll see the next window prompting you few more details about what kind of project you want to run your Silverlight application within:

    Silverlight2.gif

Leave the default selections and click OK.

Now you'll see two projects in your solution explorer.

Silverlight3.gif

Let's go to our MainPage.xaml file to create a UI for our application. Add a Button and Listbox; that will create a UI and XAML like this. Set the Name and Content properties for your convenience.

Silverlight4.gif
<UserControl x:Class="TweeterSilverlightSearch.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<
Button Content="Get Tweets" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="btn_GetTweets" VerticalAlignment="Top" Width="75" Click="btn_GetTweets_Click" />
<
ListBox Height="247" HorizontalAlignment="Left" Margin="12,41,0,0" Name="TweetList" VerticalAlignment="Top" Width="376" />
</
Grid>
</
UserControl>
 This markup is your MainPage.xaml file. Now let's write something in the button click event of the GetTweets button.
private void btn_GetTweets_Click(object sender, RoutedEventArgs e)
        {
WebClient client = newWebClient();
//This event will let us know about the downloading competion
/*Experts prefer not to create seperate event handler for one time event handling they
             * prefer to have Anonymous handler using delegates and lambda expressions.
             * for e.g.
             * client.DownloadStringCompleted += (s, ea) => { System.Diagnostics.Debug.WriteLine(ea.Result); };
             *
             * no need to write a seperate lines for writing handler code and it'll reduce the lines of code and increase
             * the code beauty as you can see.
             * */
            client.DownloadStringCompleted += newDownloadStringCompletedEventHandler(client_DownloadStringCompleted);
//Let's do our main job            client.DownloadStringAsync(newUri("http://search.twitter.com/search.atom?q=silverlight"));
        }
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(e.Result);
        }
So that looks pretty good, uh!
Now we should have something that can hold the result and before that we need to parse the result too. Create a Tweet class that can hold the tweets.
namespace TweeterSilverlightSearch
{
public classTweet    {
public string Message { get; set; }public Uri Image { get; set; }
    }
}


Save the class and get back to write something to parse the result returned in the DownloadStringCompleted event. First create a global collection to hold the tweets in.
privateObservableCollection<Tweet> _tweet=newObservableCollection<Tweet>();

Why ObservableCollection ?

Good question! Ask someone experienced with WPF. Well no need to go anywhere. This collection will provide notification (as it's name implies) when an item from the list is removed or added.

You can find it in System.Collections.ObjectModel.

Now we want to parse the Result of the search so I would like to introduce the LINQ to XML, which are powerful classes of .Net. To use this you must add a reference of System.XML.Linq to your project (Silverlight project).

Silverlight5.gif

Now here's your complete event handler for the DownloadStringCompleted Event.
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
//System.Diagnostics.Debug.WriteLine(e.Result);XDocument doc = XDocument.Parse(e.Result);XNamespace ns = "http://www.w3.org/2005/Atom";var items = from item in doc.Descendants(ns + "entry")selectnewTweet()
                        {
                            Message = item.Element(ns + "title").Value,
                            Image = newUri((fromXElement xe in item.Descendants(ns + "link")
where xe.Attribute("type").Value == "image/jpg"select xe.Attribute("href").Value
                                              ).First<String>()),

                        };
foreach (Tweet t in items)
            {
                _tweet.Add(t);
            }
        }

Bind the ListBox:

TweetList.ItemsSource = _tweet;

This simple binding won't show you meaningful data.

Silverlight6.gif

So we need to make something meaningful and sensible. Open the MainPage.Xaml file again and let's add a DataTemplate to the ListBox control.
<ListBox Height="247" HorizontalAlignment="Left" Margin="12,41,0,0" Name="TweetList" VerticalAlignment="Top" Width="376">
<
ListBox.ItemTemplate>
<
DataTemplate>
<
Grid Margin="10">
<
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 Message}" FontSize="14" Margin="3" Grid.Column="1" TextWrapping="Wrap"/>
</
Grid>
</
DataTemplate>
</
ListBox.ItemTemplate>
</
ListBox>
Looks pretty fancy now.

Now run your application and see the output.
Silverlight7.gif

Oh my goodness… Here you go.

I think you'll enjoy after doing something like this. I've attached the sample application with this you can download it run it.

Happy Silverlighting...

Technology used:

Visual Studio 2010
.Net framework 4.0
Silverlight 3.0

Thanks.