Silverlight Tips provides simple and useful tutorials and tips with real life examples, live demos and sample codes to download.
About authors:
Damon Serji
Damon Serji,
Silverlight developer working at Metia in London.
Gavin Wignall
Gavin Wignall,
Interactive Design Lead, working in design for over 10 years, the last 3 being in Silverlight.
Allan Muller
Allan Muller,
Developer, working on various types of Silverlight and WCF projects.
Recent comments
Get Microsoft Silverlight Latest posts from SilverlightTips.com

Displaying a RSS feed is a very straight forward task in Silverlight.

In summary: we need to access and download the RSS (XML file) and read it as a single string value, read the downloaded string as XML using XmlReader class, load the XML into a variable of type SyndicationFeed, and finally using a loop extract each node and save it in a desirable variable.

Some of the Silverlight built-in classes used in this example are:

Uri: Takes the URL of the RSS feed
XmlReader: Represents a reader that provides fast, non-cached, forward-only access to XML data” (msdn)
SyndicationFeed: Represents a top-level feed object, <feed> in Atom 1.0 and <rss> in RSS 2.0” (msdn)
WebClient: Receives data from a recource defuned by Uri (in our case a URL to RSS or XML file)

I am going to demonstrate how to read and display a RSS feed (XML file) in three simple steps:

Step 1: Create a custom RSS class
here I am just creating a new public class (RSSItem) for my RSS feed to contain any information I would like to keep for each item in the RSS. This will help to keep my project tidy and my code meaningful. In my RSSItem class I will add as many properties as I need:

public class RSSItem
{
    #region Properties
    public string RSSTitle {get; set;}
    public string RSSDescription { get; set; }
    public Uri RSSLink { get; set; }
    #endregion
}

Step 2: Reading the RSS feed in Silverlight
create three private variables for Uri, XmlReader and SyndicationFeed (for this you need to add a new reference in your project to System.ServiceModel.Syndication – do this by right clicking on ‘References’ folder in you Silverlight project and clicking on ‘Add Reference...’)

private Uri rssUri;
private XmlReader xmlReader;
private SyndicationFeed feed;

and don't forget to add the namespaces:

using System.Xml;
using System.ServiceModel.Syndication;

Now, in your constructor or ‘Loaded’ method add the following:

rssUri = new Uri("http://feeds.feedburner.com/Silverlighttips");
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(rssUri);

WebClient is another built-in class in Silverlight and is used to open the XML (RSS). Since the operation is done asynchronously the callback method (DownloadStringCompleted) is called after the operation is done.

Step 3: Populate RSS nodes
first, add an ItemsControl in the MainPage.xaml:


<ItemsControl x:Name="RSS" ItemsSource="{Binding}" >
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <HyperlinkButton x:Name="Title" NavigateUri="{Binding RSSLink}"
             Width="305" Margin="0,22,0,15" Foreground="#FF10589F"
             FontSize="12" FontWeight="Bold">
                <HyperlinkButton.Content>
                  <TextBlock Text="{Binding RSSTitle}" TextWrapping="Wrap" />
               </HyperlinkButton.Content>
            </HyperlinkButton>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

In the ItemsControl we can bind the required properties from our RSSItem class using {Binding nameOfProperty}.

Now, from our DownloadStringCompleted method in MainPage.xaml.cs we can retrieve the RSS in form of a string. Then, we can create our XmlReader and load it to a SyndicationFeed variable which treats the XML as a 'RSS' and allow us to use its properties:

private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        int itemsCount = 5;
        xmlReader = XmlReader.Create(new StringReader(e.Result));
        feed = SyndicationFeed.Load(xmlReader);
       
        List<RSSItem> itemsList = new List<RSSItem>();

        if (feed.Items.Count() < 5)
        {
            itemsCount = feed.Items.Count();
        }

        for (int i = 0; i <= itemsCount; i++)
        {
            RSSItem rssitem = new RSSItem();
            rssitem.RSSTitle = feed.Items.ToList()[i].Title.Text;
            rssitem.RSSLink = feed.Items.ToList()[i].Links[0].Uri;
            itemsList.Add(rssitem);
        }
        RSS.ItemsSource = itemsList;
    }
}

you will need to add the namespace for the StringReader:

using System.IO;

In the above method from top:

  • check if there are any errors in the result, if not continue
  • set the number of items to read
  • load the XML into a SyndicationFeed variable
  • create a new List of type RSSItem to hold each RSSItem
  • if the number of total RSS items to be found (itemsCount) is greater than the total number of RSS items available then go with the total number of available items
  • search in each node for ‘Title’ and ‘Summary’ (description)
  • add Title and Summary of each RSS item to the variable of type RSSItem class, and finally add the rssitem to the RSSItem list
  • at the end we bind our itemsList to 'RSS' which is an ItemsControl in our XAML page
Posted by Damon Serji on 29. November 2009 14:52 under: Intermediate
 with 6 Comments

Today Microsoft released Silverlight 4.0 Beta version along with the SDK and tools for Visual Studio 2010 Beta 2 for software developers.

there are great new features added to this version of Silverlight that enables Silverlight applications to provide 'rich interactive media experiences' to end users.

Since most of these new features, such as, printing, webcam, clipboard access, right mouse click and drag and drop functionalities, are completely brand new and did not exist in previous versions of Silverlight, we will be going through them by posting tutorials and exemplas, and hopefully you will be able to play around with the demos here at Silverlight Tips website. So, make sure you have all requirements for developing on Silverlight 4.0 Beta on your computer.

Resouces:

Microsoft Silverlight - getting started

Posted by Damon Serji on 18. November 2009 23:18 under: Silverlight News
 with 0 Comments

During the past two months or so I had been working on building Silverlight Tips website and managed to put up some useful Silverlight tutorials along with examples and demos. Just after a few weeks of the site's launch, it started receiving a great number of visits from around the world. The site received about 5000 visitors through this short period of time (2 months) and I must mention the comments I received from visitors were great and motivating. The site was picked up by major and minor search engines within the first two weeks and is now been featured on various great Silverlight and none-Silverlight websites including silverlightshow.netsilverlightcream.com and silverlightbuzz.com.

Today, I am glad to announce Gavin Wignall, an Interactive Design Lead and owner of Silverlight Buzz website, along with Allan Mullar, a Silverlight and WCF expert and owner of Silverlight Forums website, have joined the site to publish their tutorials and tips on Silverlight Tips website, and help to build a great source of information and tutorials about Microsoft Silverlight by using their experiences and expertise in this field.

I am looking forward to continue posting articles on Silverlight Tips and am most grateful to have Gavin and Allan on board.

Posted by Damon Serji on 9. November 2009 09:18 under: Silverlight News
 with 0 Comments
Get Microsoft Silverlight

The built-in validation in Silverlight 3.0 is a great new feature that can be used on essential Silverlight controls such as TextBox. Using this feature, it is possible to nicely display an error message and highlight the TextBox that has bad value.

In this post I will only cover validating data in TextBox controls, which are simply used in most forms to receive basic information such as Name, Surname and Email address. The completed and working version of this project can be downloaded from CodePlex from here. I will explain and provide solution on how to validate ComboBox, Radio Button controls or etc in another post soon, so please keep yourself updated on new posts here.

1. Create a basic form with a few TextBox controls in the xaml

2. Create a class, call it CustomValidation
Add the following code to your CustomValidation class:

private string message;
public CustomValidation(string message)
{
    this.message = message;
}
public bool ShowErrorMessage
{
    get;
    set;
}
public object ValidationError
{
    get
    {
        return null;
    }
    set
    {
        if (ShowErrorMessage)
        {
            throw new ValidationException(message);
        }
    }
}

3. Create an Extension class (Extensions)
To understand what is an Extension class and for more information about them visit my tutorial post “Extension methods in Silverlight and C#”.

In brief: Extensions will be your Extension class to extend any object of type FrameworkElement like TextBox controls within your application framework. It means you can use the public methods within this class as a “built-in” method for your TextBox.

Create a static public method and call it SetValidation. This method receives an instance of a FrameWorkElement and a string value, and returns nothing:

public static void SetValidation(this FrameworkElement frameworkElement, string message)
{
    CustomValidation customValidation = new CustomValidation(message);
    Binding binding = new Binding("ValidationError")
    {
        Mode = System.Windows.Data.BindingMode.TwoWay,
        NotifyOnValidationError = true,
        ValidatesOnExceptions = true,
        Source = customValidation
    };
    frameworkElement.SetBinding(Control.TagProperty, binding);
}

CustomValidation is the class we defined earlier.

"Binding" is a class in System.Windows.Data assembly which gets or sets a value that indicates whether to raise the error attached event on the bound object.

What are we doing? Here we have a CustomValidation class that has one property ("ShowErrorMessage") and one public methods ("ValidationError"). "ValidationError" is our source binding object and what we want to be able to do in the future is to bind our frameworkElement, which is a TextBox, to ValidationError. We are in simple words binding the CustomValidation class to our TextBox once we call this method on our TextBox.

For more information on Binding and BindingExpression visi msdn article here.

Create another two methods for displaying validation error and also for clearing validation error when the error was corrected:

public static void RaiseValidationError(this FrameworkElement frameworkElement)
{
    BindingExpression b =
    frameworkElement.GetBindingExpression(Control.TagProperty);
    if (b != null)
    {
        ((CustomValidation)b.DataItem).ShowErrorMessage = true;
        b.UpdateSource();
    }
}

public static void ClearValidationError(this FrameworkElement frameworkElement)
{
    BindingExpression b =
    frameworkElement.GetBindingExpression(Control.TagProperty);
    if (b != null)
    {
        ((CustomValidation)b.DataItem).ShowErrorMessage = false;
        b.UpdateSource();
    }
}

By creating a new BindingExpression you will be creating an instance of your binding so you can control the properties and public methods of your binding source/target. In above case, we are casting the BindingExpression.DataItem as CustomValidation. This enables us to access the properties of this class, "ShowErrorMessage" in this case.

4. RaiseValidationError() and ClearValidationError()
So now we have our TextBox, a method in our Extension class to bind the TextBox to our CustomValidation class and passes our error message, and a method in our Extension class that fires throw new ValidationException(message); from the CustomValidation class.

All we need to do now is to check if a specific TextBox is valid or not. If the TextBox was not valid we can simply use the RaiseValidationError() and ClearValidationError() methods, which should now be available from the intellisense in Visual Studio, to throw the validation exception and display a suitable error message and we do that by following code when the submit button was pressed:

Name.ClearValidationError();
bool isFormValid = true;
if (Name.Text == "")
{
    Name.SetValidation("Please enter your name");
    Name.RaiseValidationError();
    isFormValid = false;
}

use isFormValid variable to check if you have to submit the form or not. The Name.ClearValidationError() makes sure you clear the form everytime you press submit, so if the form was valid the error message had already been cleaned.

I have some extra validation extensions on this project and have organised the code in different class files. Download the project from here.

Posted by Damon Serji on 8. October 2009 19:24 under: Advance, Intermediate
 with 9 Comments

This post is very much a combination of my three previous posts (Silverlight QueryString using TryParse() method, Validate GUID in Silverlight – Parse GUID in C# and Extension methods in Silverlight and C#) to demonstrate all these great features in one place. I have also added an Extension method in this project to validate Date and Time using a simple Regular Expression, for better validation I suggest change the Regular Expression to match your specific needs.

I am not explaining the code for this project as each part is explained in details in the posts I mentioned above, but please do feel free to ask any questions in the comment section below and I will try to answer as soon as I can.

This project can be downloaded from CodePlex from here, and feel free to play with the working version of it below.

Get Microsoft Silverlight
Posted by Damon Serji on 7. October 2009 18:57 under: Intermediate
 with 1 Comments

I have been looking around to find any built-in method to parse GUIDs in Silverlight, or to tell me if a value of type string is a valid GUID or not. After a few research I decided to create an Extension method to validate my GUID using Regular Expressions.

You can read more about Extension methods in Silverlight in my previous post here, but here I have a method to receive a string value and return true/false depending on if the sting value is a valid GUID or not. Anyway, here is what we can do to validate Silverlight GUID!

public static bool IsGUIDValid(string expression)
{
    if (expression != null)
    {
        Regex guidRegEx = new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");

        return guidRegEx.IsMatch(expression);
    }
    return false;
}

Posted by Damon Serji on 7. October 2009 16:17 under: Intermediate
 with 0 Comments

Extension methods are great way to add and use custom functionality on your objects.

So what is an Extension method?

In a short and simple describing: instead of creating a method that takes an instance of your object, applies your changes and then returns you the instance of that control, you can create an Extension method for that specific object to do the same thing but in a way of built-in within your object.

Example: if we had a TextBox that needed to have a valid text input:


<TextBox x:Name=”InputEmail/>

And you have:

string inputEmail = InputEmail.Text;

You can do:

If (inputEmail != “” && ValidateEmail(inputEmail) == true)
{
   .
   .
}
.
.
private bool ValidateEmail(string getInputEmail)
{
   .
   .
}

or you can do it in a much cleaner and easier to understand way using “IsEmailValid” extension, which extends the string:

if (inputEmail.IsEmailValid())
{

}

You can immediately notice from the above example that how much time and line of codes you will save by simply using Extensions instead of re-writing your custom methods to apply the same operation on a common object or element within a project that uses that feature in many places.

How to add an Extension method to Silverilght objects?

First we need to add a new static class that contains a static method for our new Extension method (IsEmailValid).

public static class FrameworkElementExtensionExtensions
{
    public static bool IsEmailValid (this string getInputEmail)
    {
        bool isMatched = true;
        Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        
        if (getInputEmail != “” && regex.IsMatch(s))
        {
            isMatched = false;
        }
        return regex.IsMatch(s);
    }
}

Note in the IsEmailValid method we used the keyword “this” before string getInputEmail, this simply means the IsEmailValid Extension method belongs to objects of type “string”.

To use the above extension method anywhere within your project, all you have to do is to import the reference to any of your classes, where you like the extension to be available, by adding “using FrameworkElementExtensionExtensions;” to that class.

Now you should even get the IsEmailValid method in your Visual Studio Intellisense when you add a dot after any string variable. So now you could simply do:

if (inputEmail.IsEmailValid()){
    HtmlPage.Window.Alert("Email was successfully submitted!");
}

Above example was a very simple example, I will update the example solution regularly to include more advanced examples for you to use (copy & paste!) in the future, so please check this post later for updates. Also, this example, along with more examples in the future, is available to download from CodePlex from here.

Posted by Damon Serji on 6. October 2009 09:37 under: Intermediate
 with 0 Comments

In order to get the value of your QueryString parameters from the URL all you need is this line of code:

int id = HtmlPage.Document.QueryString["ID"];

And you need to add Windows.Browser namespace for HtmlPage class:

using System.Windows.Browser;

However, there are always two situations which could break your application:

  1. if there are no “ID” parameters in the url
  2. if there is an “ID” parameter in the url, but it has a string value instead of an integer number.

To avoid breaking the code and causing runtime error we need to add a few conditions and also parse the value to integer instead of assigning it right away. We can use Int32.TryParse() method to test the value which we are about to assign to an integer variable before we actually do so, this way we will only assign it if it really is an integer:

int id = -1;
if (HtmlPage.Document.QueryString.ContainsKey("ID"))
{
    string queryStringValue = HtmlPage.Document.QueryString["ID"];
    if (Int32.TryParse(queryStringValue, out id))
    {
        // the result was successful and
        // the correct ID will be inserted to id
    }
    else
    {
        // the result was not successful                   
    }
}

Using above method, you ensure the id gets assigned a value only if the ID parameter in the url has a valid integer value, or it will remain as -1 if the value was not an integer.

Posted by Damon Serji on 30. September 2009 22:30 under: Basic, Intermediate
 with 3 Comments

Gavin Wignall at Silverlight Buzz is doing a series of posts on his blog, aiming to cover the most useful information and techniques on Expression Blend for both beginners and pros. For more information, and to see the list of topics, which will be posted through the whole October, visit Learn Expression Blend in a Month! at SilverlightBuzz.com.

Posted by Damon Serji on 30. September 2009 21:26 under: Silverlight News
 with 1 Comments

In this example I will demonstrate how to use ImageBrush to fill area of shapes like rectangle or ellipse with an image.

In order to fill the area of a control like Rectangle control, we need to create an instance of type BitmapImage, and this is not possible if we do not have a Uri which points to a real image file.

So first, I create an Uri pointing to an image which I had put in the “images” folder in my Silverlight application project.

Hint: try to use Uri.TryCreate to create your Uri as by this way you stop your application from breaking if the path you gave your Uri was not valid or did not exist.

Second, create a new instance of BitmapImage and assign your Uri to its value.

Uri imageUri;
BitmapImage image = null;

if (Uri.TryCreate("images/SilverlightTips.jpg", UriKind.RelativeOrAbsolute, out imageUri))
{
    image = new BitmapImage(imageUri);
}

Now you can create a new instance of ImageBrush and assign your created BitmapImage to its ImageSource value:

ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = image;

Finally, using .Fill method on your Rectangle control fill the entire rectangle (or any other shapes your object is) with your ImageBrush. And here is how your final code should look like:

Uri imageUri;
BitmapImage image = null;

if (Uri.TryCreate("images/SilverlightTips.jpg", UriKind.RelativeOrAbsolute, out imageUri))
{
    image = new BitmapImage(imageUri);
}
if (image != null)
{
    ImageBrush imageBrush = new ImageBrush();
    imageBrush.ImageSource = image;
    Logo.Fill = imageBrush;
    LogoEllipse.Fill = imageBrush;
    LogoRectangle.Fill = imageBrush;
}

Download this project from CodePlex from here. Here it is working:

Posted by Damon Serji on 28. September 2009 13:42 under: Intermediate
 with 2 Comments