Posted by admin
December - 1 - 2009

Have you ever tried to read a RSS feed and been denied access? Or have you tried to read an XML file and for your code to throw up all manner of exceptions? Well with Silverlight 2 Microsoft decided to address the situation. The solution is a simple XML file called ClientAccessPolicy.xml. The Client Access Policy file allows you to grant access to Silverlight applications to access content on your server like RSS feeds, web services and WCF services.

Before jumping into the code make sure you read the following to ensure that you don’t have any conflicts.

When accessing a server (in this case for a RSS feed) Silverlight will automatically look for the Client Access Policy file. If the file exists then it will go by the configuration defined inside that. If the Client Access Policy file does not exist Silverlight by default looks for another file called Cross Domain (crossdomain.xml) which is the file format implemented by Adobe Flash. If the Cross Domain file exists then it will use its configuration settings and if both the Client Access Policy and the Cross Domain files do not exist then Silverlight will throw an exception.

For more information on the Cross Domain file please visit crossdomainxml.org.

When creating a Cross Access Policy file my advice would be to start with a file that allows full access to everything, test you code works and this fixes the problem. If you wish to lock it down then you can start tweaking it and testing your code to check there is no knock on effects. Below is the code to grant ‘full’ access.

<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="http://*"/>
        <domain uri="https://*" />
      </allow-from>
      <grant-to>
        <resource include-subpaths="true" path="/"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

To lock down the file you have several options but the main two are:

  1. <allow-from/> Defines the sites that are allowed to access resources in a certain policy.
  2. <grant-to/> Defines all the server’s resources that are affected by this policy.

To only allow certain sites to access your content list the sites domains in the <allow-from /> tags like below:

&lt;access-policy&gt;
  &lt;cross-domain-access&gt;
    &lt;policy&gt;
      &lt;allow-from http-request-headers=&amp;quot;SOAPAction&amp;quot;&gt;
        &lt;domain uri=&amp;quot;http://silverlightforums.com&amp;quot;/&gt;
        &lt;domain uri=&amp;quot;http://silverlighttutorials.com&amp;quot;/&gt;
      &lt;/allow-from&gt;
      &lt;grant-to&gt;
        &lt;resource include-subpaths=&amp;quot;true&amp;quot; path=&amp;quot;/&amp;quot;/&gt;
      &lt;/grant-to&gt;
    &lt;/policy&gt;
  &lt;/cross-domain-access&gt;
&lt;/access-policy&gt;

The above Client Access Policy will only allow access requests made from Silverlightforums.com or Silverlighttutorials.com and all other requests will be blocked. Requests from those two sites will be granted access to all content (including sub-directories).

The following Client Access Policy with allow access to all requests made from Silverlightforums.com but the only grant access to files inside the ‘feeds’ directory:

&lt;access-policy&gt;
  &lt;cross-domain-access&gt;
    &lt;policy&gt;
      &lt;allow-from http-request-headers=&amp;quot;SOAPAction&amp;quot;&gt;
        &lt;domain uri=&amp;quot;http://silverlightforums.com&amp;quot;/&gt;
        &lt;domain uri=&amp;quot;http://silverlighttutorials.com&amp;quot;/&gt;
      &lt;/allow-from&gt;
      &lt;grant-to&gt;
        &lt;resource include-subpaths=&amp;quot;false&amp;quot; path=&amp;quot;/feeds&amp;quot;/&gt;
      &lt;/grant-to&gt;
    &lt;/policy&gt;
  &lt;/cross-domain-access&gt;
&lt;/access-policy&gt;

If you are comfortable with XML then setting up a Client Access Policy should be a breeze, but if you have any questions or need any help feel free to ask at Silverlight Forums.

Further information on the Client Access Policy can be found here at MSDN.

Posted by admin
September - 16 - 2009

RSS is an essential part of the internet and is almost used on every website from youtube to Silverlight Forums. It’s no surprise that one of the most common questions I am asked is how do you read RSS in Silverlight? Well the answer is pretty straight forward and I am going to show you how to do it.

For this tutorial I am going to consume an RSS feed from Silverlight Forums.

First create you project and once it’s setup then right click on ‘References‘ in the Silverlight application as shown

Silverlight Add Reference

Silverlight Add Reference

Select ‘Add Reference‘ and choose ‘System.ServiceModel.Syndication

Silverlight Add Reference - Synidication

Silverlight Add Reference - Syndication

Now that the project is setup you can now get on with the coding :) On the Xaml I have added a ScrollViewer and a StackPanel. On the ScrollViewer I have set ‘ScrollViewer.VerticalScrollBarVisibility=”Auto”‘ to auto so that a vertical scrollbar will be visible.

&lt;UserControl x:Class=&amp;quot;SilverlightForums_ReadRSS.MainPage&amp;quot;
    xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
    xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot;
    xmlns:d=&amp;quot;http://schemas.microsoft.com/expression/blend/2008&amp;quot; xmlns:mc=&amp;quot;http://schemas.openxmlformats.org/markup-compatibility/2006&amp;quot;
    mc:Ignorable=&amp;quot;d&amp;quot; d:DesignWidth=&amp;quot;640&amp;quot; d:DesignHeight=&amp;quot;480&amp;quot;&gt;
  &lt;StackPanel x:Name=&amp;quot;LayoutRoot&amp;quot; Background=&amp;quot;AliceBlue&amp;quot;&gt;
      &lt;HyperlinkButton Content=&amp;quot;Silverlight Forums&amp;quot; NavigateUri=&amp;quot;http://www.silverlightforums.com&amp;quot; TargetName=&amp;quot;_blank&amp;quot; FontSize=&amp;quot;16&amp;quot; FontWeight=&amp;quot;Bold&amp;quot; Foreground=&amp;quot;Black&amp;quot; HorizontalAlignment=&amp;quot;Right&amp;quot; Margin=&amp;quot;50, 50, 50, 0&amp;quot; /&gt;
      &lt;ScrollViewer Height=&amp;quot;100&amp;quot; Margin=&amp;quot;50, 0, 50, 50&amp;quot; Background=&amp;quot;White&amp;quot; ScrollViewer.VerticalScrollBarVisibility=&amp;quot;Auto&amp;quot;&gt;
            &lt;StackPanel x:Name=&amp;quot;LinkList&amp;quot; Height=&amp;quot;Auto&amp;quot; Width=&amp;quot;Auto&amp;quot; /&gt;
      &lt;/ScrollViewer&gt;
        &lt;StackPanel Orientation=&amp;quot;Horizontal&amp;quot; HorizontalAlignment=&amp;quot;Center&amp;quot;&gt;
            &lt;TextBlock Text=&amp;quot;Created by&amp;quot; /&gt;
            &lt;HyperlinkButton Content=&amp;quot;Silverlight Tutorials&amp;quot; NavigateUri=&amp;quot;http://www.silverlighttutorials.com&amp;quot; TargetName=&amp;quot;_blank&amp;quot; Foreground=&amp;quot;Black&amp;quot; /&gt;
            &lt;TextBlock Text=&amp;quot;and&amp;quot; /&gt;
            &lt;HyperlinkButton Content=&amp;quot;Silverlight Forums&amp;quot; NavigateUri=&amp;quot;http://www.silverlightforums.com&amp;quot; TargetName=&amp;quot;_blank&amp;quot; Foreground=&amp;quot;Black&amp;quot; /&gt;
            &lt;TextBlock Text=&amp;quot;.&amp;quot; /&gt;
      &lt;/StackPanel&gt;
    &lt;/StackPanel&gt;
&lt;/UserControl&gt;

On the mainpage.xaml.cs I have setup the following private members

        #region Private Members
        private Uri RSSUrl;
        private XmlReader reader;
        private SyndicationFeed feed;
        #endregion

Then I set the RSS Url to my Uri and then called a method called GetRSSFeed()

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            RSSUrl = new Uri(&amp;quot;http://www.silverlightforums.com/external.php?type=RSS2&amp;quot;);
            GetRSSFeed();
        }

The GetRSSFeed() method creates and instance of WebClient which is used to retrieve data and is best used for a one-time retrieval of data (which is exactly what we are doing!). Once our WebClient is created we can then register the ‘DownloadStringCompleted’ event so once our WebClient has completed retriving the data it will trigger that event. To Kick the retrieval of the RSS feed off I call the WebClient.DownloadStringAsync(Uri) helper method.

        private void GetRSSFeed()
        {
            WebClient client = new WebClient();
            client.DownloadStringAsync(RSSUrl);
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        }

Once the download is complete the following is triggered.

        private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            reader = XmlReader.Create(new StringReader(e.Result));
            feed = SyndicationFeed.Load(reader);

            foreach (SyndicationItem item in feed.Items)
            {
                HyperlinkButton link = new HyperlinkButton();
                link.Content = item.Title.Text;
                link.NavigateUri = item.Links.First().Uri;
                link.TargetName = &amp;quot;_blank&amp;quot;;
                LinkList.Children.Add(link);
            }
        }
e.Result fill with RSS data

e.Result full with RSS data

Now this code processes the RSS feed. An XmlReader is setup and is passed the data from the WebClient (e.Result is the RSS feed :) ). The reader reads all the data in the StringReader and then the SyndicationFeed (feed) is setup which in turn loads the data from the XmlReader (reader).

SyndicationItem populated with RSS node

SyndicationItem populated with RSS node

Once that is done you can then loop through your RSS nodes and I have done this with a foreach loop. For each SyndicationItem inside the feed.Items collection it will then create a HyperLinkButton with the feed items title and link Uri set to the HyperLinkButton. Finally the HyperLinkButton control is added to my StackPanel which is called LinkList.

Build the project and run the application and you should see this

Silverlight 3 Reading RSS

Silverlight 3 Reading RSS

Here you can see the RSS feed displayed as HyperLinkButtons in a ScrollViewer. To update the feed simply refresh the page in the browser.

Download the example and take a look. If you have any issues or questions feel free to discuss them at Silverlight Forums.

Posted by admin
September - 13 - 2009

You have your design almost in the bag, you have a font that you want to use but how can you use that font in Silverlight. Without distributing a font (which would be illegal unless you had a license to do this) requires you to obfuscate the font. Obfuscating the font means taking the font and converting it into an un-usable format outside your application.

So to convert you font follow this simple steps:

  1. Open up Word 2007
  2. Type every character, digit and symbol that you might need.
  3. Then select all the copy in the word document and change the font to the desired font.
  4. Save the document as an XPS file.
  5. Now close word and find the XPS file you have just created.
  6. Rename the file from .xps to .zip
  7. Now open that zip file and look inside the ‘Resources’ directory and you should see a file with the extension .odttf
  8. Copy the .odttf file into your Silverlight Application and set it’s build action to ‘Resource‘ (see our tutorial on Silverlight Build Actions)
  9. Now on a TextBlock in your page set the FontFamily location to your .odttf file

This is how you set the FontFamily on your TextBlock

<TextBlock x:Name=&quot;Msg&quot; FontFamily=&quot;./Fonts/20FD640A-6B8C-569B-6B08-6F60BA7CC534.odttf#Segoe UI&quot; FontSize=&quot;17.333&quot; FontWeight=&quot;Bold&quot; Foreground=&quot;White&quot; Text=&quot;This is your font!&quot; TextWrapping=&quot;Wrap&quot; />

The font name (the bold bit!) ‘Segoe UI‘ you see in the FontFamily path after the # needs to be exactly the same as what appears in your Word document dropdown list. This selects the font with the .odttf as you could have multiple fonts within the same .odttf file.

If you have any questions or need any help simply create a post at Silverlight Forums in the Fonts section.

Posted by admin
September - 13 - 2009

Resources, embedded resources, content and all the other options! It’s just confusing! So I hope to outline the build actions so you can choose the best one to suit your needs :)

Silverlight Build Actions

Silverlight Build Actions

Silverlight build actions defined:

  • None – Does exactly what it says on the tin (well textbox). The resource file will not be a part of the .xap.
  • Compile – This build action is reserved for .cs and .vb files and should not be used for other items.
  • Content – Item will be included in the application package (.xap) without it being embedded it in the project assembly.
  • Embedded Resource – This build action is aimed at non-Silverlight action. Should be changed to a build action of Resource
  • ApplicationDefinition – This build action is reserved for the app.xaml file which defines the start point for your Silverlight application.
  • Page – This build action is given to certain types of Xaml based files like user controls and pages. Mainly used with Silverlight navigation applications.
  • CodeAnalysisDictionary – Unknown.
  • Resource – The file is embedded into the application assembly. The resource is accessible using a relative Uri, relative to the Xaml file from where they are being referenced.
  • SplashScreen – Is for WPF applications only and is explained perfectly here.
  • EntityDeploy – is used by the ADO.NET Entity Framework.

Resource files and their related BuildAction alternatives are explained here.

If you have any comments or thoughts why not start a thread at Silverlight Forums?

Source: Bob’s Blog

Posted by admin
September - 13 - 2009

When building RIAs you often rely on data being downloaded when up front via the preloader which is find for getting the look and feel and some static content but when you need to display specific data which the user has input into often you need to pass data to and from web services or databases. This obviously requires an active internet connection but what happens if the users connection drops? Well in Silverlight 3 the NetworkInformation namespace was introduced which allows you to hook up an event to your application and capture when the connection is alive or dropped.

In this tutorial I am going to show you how to hook up this event and also inform the user of the issue on screen.

I hook up the event on the App.xaml.cs but before we hook up the event we need to create a control which we display on screen. Once you have your project created add a new file ‘Silverlight User Control’

Create a Silverlight User Control

Create a Silverlight User Control

Once the user control is created you need to add a textblock to the new control so you can inform the user what is happening. Here is the Xaml from my control

<UserControl x:Class=&quot;SilverlightForums_NetworkInformation.InternetConnectionStatus&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    Width=&quot;400&quot; Height=&quot;300&quot;>
    <StackPanel x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;>
        <TextBlock x:Name=&quot;Status&quot; Text=&quot;Internet Connection Lost&quot; />
    </StackPanel>
</UserControl>

Now that the Xaml is taken care of you can move on to the code. Obviously you should design the Xaml to fit in with your project but for this example it shall do :) Now in the app.xaml.cs create a private member of your new control.

#region Private Members
private InternetConnectionStatus _ics;
private MainPage mainPage;
#endregion

Also define a private member of MainPage as you can see I have done this above and it is called mainPage.

Now find the ‘Application_Startup’ method and comment out the line

//this.RootVisual = new MainPage();

mainPage = new MainPage();
this.RootVisual = mainPage;
_ics = new InternetConnectionStatus();

The next thing you need to do is hook up the NetworkAddressChanged event in the ‘Application_Startup’ like this

System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += new System.Net.NetworkInformation.NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);

Once the event has been hooked up and created you now need to wire up the action for when the connection drops. So inside the event I have hooked up a simple if statement which checks to see if the connection has dropped and if GetIsNetworkAvailable() is false adds the instance of _ics (The user control you created earlier) to the mainpage. The oppersite happens if the GetIsNetworkAvailable() is true – it removes it.

private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
            {
                if (mainPage.Root.Children.Contains(_ics) == false)
                {
                    mainPage.Root.Children.Add(_ics);
                }
            }
            else if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
            {
                if (mainPage.Root.Children.Contains(_ics) == true)
                {
                    mainPage.Root.Children.Remove(_ics);
                }
            }
        }

Now the final stage is exposing the Root item on the MainPage.xaml.cs which is done by adding this public property

public Panel Root
{
get { return LayoutRoot; }
}

You should be able to build the Silverlight application and run the project (with your connection active). If you disable your connection (pulling out the Cat5 cable or switching off your wireless connection you should see a message be displayed on your screen like this

Silverlight Internet Connection Alert

Silverlight Internet Connection Alert

Now that you know how to display a message on screen you might want to integrate this with a ChildWindow (see my previous post – Silverlight: Custom ChildWindow popup) as this will take the focus away to a popup in which the user must interactive with.

To do that add a Silverlight Child Window to your solution (I have called mine InternetConnectionStatusPopUp.xaml) and set up a private member for your popup

#region Private Members
//private InternetConnectionStatus _ics;
private InternetConnectionStatusPopUp _ics;
private MainPage mainPage;
#endregion

Now in the Application_StartUp create the instance of the ChildWindow

//_ics = new InternetConnectionStatus();
_ics = new InternetConnectionStatusPopUp();

Now if you rebuild the solution and run it you shall see the following once you drop your internet connection

Silverlight: Detect Network Changes with ChildWindow

Silverlight: Detect Network Changes with ChildWindow

Download the example from this post and take a look. If you have any issues or questions feel free to discuss them at Silverlight Forums.

Posted by admin
September - 6 - 2009

Often when building Silverlight RIA you need to prompt the user to confirm an action; Say you are deleting an item you want to make sure they approve the deletion. Just like you do in Windows/Mac OS. In Silverlight 3 the ChildWindow control was added which basically popups a dialog window where you can focus the users attention until you get a confirmation or cancelation on the matter at hand.

In my example I have placed a button inside a StackPanel which once click Shows my ChildWindow. What I do is create the ChildWindow on MainPage Loaded event as a private member and then I can just show or hide it. The reason I do not just keep creating new instances of the ChildWindow is because the garbage collection in Silverlight isn’t the greatest and I would prefer to keep my apps to a minimum.

Silverlight ChildWindow Example

Silverlight ChildWindow Example

Silverlight ChildWindow in action

Silverlight ChildWindow in action

This is how I setup my ChildWindow as a private member on MainPage.xaml.cs:

private PopupWindow _popupWindow;

This is how I setup my ChildWindow instance (line 6) on the MainPage Loaded Event:

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            SilverlightForums.Click += new RoutedEventHandler(SilverlightForums_Click);
            SilverlightTutorials.Click += new RoutedEventHandler(SilverlightTutorials_Click);
            // Create instance of PopupWindow
            _popupWindow = new PopupWindow();
            // Hookup Click Event
            ShowPopup.Click += new RoutedEventHandler(ShowPopup_Click);
        }

When I click my button on MainPage it calls this Click() method:

        private void ShowPopup_Click(object sender, RoutedEventArgs e)
        {
            // Populate PopupWindow
            _popupWindow.ErrorTitle = &amp;quot;If you have any questions visit SilverlightForums.com and ask :-) &amp;quot;;
            // Display PopupWindow
            _popupWindow.DisplayPopup();
        }

On my ChildWindow (called PopupWindow) I have created a property that I can pass through a string message:

        #region Properties
        /// &lt;summary&gt;
        /// Gets or sets the title
        /// &lt;/summary&gt;
        public string ErrorTitle
        {
            get { return _errorTitle; }
            set { _errorTitle = value; }
        }
        #endregion

To Show and Hide the ChildWindow I have two public methods. One to Show it and one to hide it.

        #region Public methods
        public void DisplayPopup()
        {
            this.Show();
        }

        public void HidePopup()
        {
            this.Close();
        }
        #endregion

Here is the Xaml From the ChildWindow to show you what it looks like:

&lt;controls:ChildWindow x:Class=&quot;SilverlightForums_ChildWindow.PopupWindow&quot;
           xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
           xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
           xmlns:controls=&quot;clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls&quot;
           Width=&quot;250&quot; Height=&quot;200&quot;
           Title=&quot;PopupWindow&quot;&gt;
    &lt;StackPanel x:Name=&quot;LayoutRoot&quot; Orientation=&quot;Vertical&quot;&gt;
        &lt;TextBlock x:Name=&quot;Title&quot; HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Center&quot; TextWrapping=&quot;Wrap&quot; /&gt;
        &lt;StackPanel Orientation=&quot;Horizontal&quot; Margin=&quot;30,50,0,0&quot;&gt;
            &lt;Button x:Name=&quot;OK&quot; Content=&quot;OK&quot; Width=&quot;75&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Right&quot; /&gt;
            &lt;Button x:Name=&quot;Cancel&quot; Content=&quot;Cancel&quot; Width=&quot;75&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Left&quot; /&gt;
        &lt;/StackPanel&gt;
    &lt;/StackPanel&gt;
&lt;/controls:ChildWindow&gt;

If you download the example you will see that the source code is quite easy to follow (probably easier to follow than this posts actually :) ). If you have any issues or questions feel free to discuss them here

Thank you to Silverlightfreak at Silverlight Forums who requested this Silverlight tutorial. We hope you find it useful :)

Posted by admin
August - 27 - 2009

Often you want to change the colour when you perform an action to indicate to the user that something has happened. In Silverlight this can be done in may ways including using states, styles and directly changing the controls foreground or background colours.

In this example I am going to have a button inside a StackPanel. When the button is clicked I want the StackPanel’s background to change colour.

private void BtnBgcolor_Click(object sender, RoutedEventArgs e)
{
LayoutRoot.Background = new SolidColorBrush(Colors.HotPink);
}

My StackPanel is called ‘LayoutRoot‘ and I am addressing its background property by passing it a SolidColorBrush. The SolidColorBrush() allows me to pass in a color from the Windows.Media.Colors class.

Download the example from this post and take a look. If you have any issues or questions feel free to discuss them here

About Silverlight Forums

Silverlight Forums Stats

Silverlight Forums is an established Silverlight community for people interested in design and development using Silverlight.

11066 news articles
29 tutorials and 2 video tutorials
2061 forum posts in 1299 threads

Silverlight User Groups (SLUGs)

Why not join your local SLUG?

London, Atlanta, Phoenix, Toronto, Portland, Wellington, Los Angeles, Seattle, South Florida, Tampa Bay, Jacksonville, Belgium

Silverlight Usergroups (SLUGs)