Silverlight Image Viewer for SharePoint 2010

This week I had a lot of time to experiment with new ideas – snow in Texas has a way of shutting down business. As part of my tasks for this week, I wanted to provide a flashy way to show off images stored in an image library. The idea came from an “employee club” site at a client. The group is made up of people from across the organization who participate in activities outside of the job – Special Olympics, Ranger’s Games and other social or community events.

The idea was to create a case-study for the client on how Silverlight can extend the capabilities of SharePoint and provide rich interaction with the data contained on the site. The web part will show a list of images in a left hand panel and allow the site visitor to click on the image to get more details about the photograph.

Since I’m still learning Silverlight, I started with a basic layout and some sample images from the web.

And here is the XAML source:

    xmlns:i="" xmlns:ei="" x:Class="Tribridge.Silverlight.ImageViewer.MainPage"
    d:DesignHeight="600" d:DesignWidth="800">
        <Style x:Key="HorizontalListBox" TargetType="ListBox">
            <Setter Property="ItemsPanel">
                        <StackPanel Orientation="Horizontal"
        <local:ImageDataCollection x:Key="Images" />
        <Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource Images}}">
        		<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
        			<GradientStop Color="#FF323232" Offset="1"/>
        			<GradientStop Color="Gray"/>
        			<GradientStop Color="#FF8C8C8C" Offset="0.296"/>
            <ColumnDefinition Width="160"/>
            <ColumnDefinition Width="*"/>
        <Border Grid.Column="1" Margin="8" BorderBrush="#59000000" BorderThickness="2">
        		<Grid DataContext="{Binding SelectedItem, ElementName=ImageList}">
        				<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
        					<GradientStop Color="#7F646464" Offset="1"/>
        					<GradientStop Color="#7FB4B4B4" Offset="0.008"/>
                    <RowDefinition Height="128"/>
                    <Image x:Name="CurrentImage" Margin="10,10,10,10"
        				Grid.Row="0" Grid.Column="1" Grid.RowSpan="1"
        				Stretch="Uniform" VerticalAlignment="Stretch"
        				HorizontalAlignment="Stretch" Source="{Binding ImageURL}">
        					<ei:FluidMoveBehavior InitialTag="DataContext" FloatAbove="False" Duration="0:0:0.65">
        							<CircleEase EasingMode="EaseOut"/>
        							<CircleEase EasingMode="EaseOut"/>
                <TextBlock Text="{Binding Path=Caption}" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="1" FontSize="22" FontWeight="Bold" FontFamily="Arial" />
        <ListBox x:Name="ImageList" Grid.Row="0"
                 Margin="8" SelectionChanged="ImageList_SelectionChanged" SelectedIndex="-1" ItemsSource="{Binding}" Background="#3FFFFFFF">
                    <Border BorderThickness="2" CornerRadius="0" BorderBrush="#FF000000">
                    <StackPanel Orientation="Vertical" Width="100" Height="100" VerticalAlignment="Top" HorizontalAlignment="Center">
                    		<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    			<GradientStop Color="#FFFFFFFF" Offset="0"/>
                    			<GradientStop Color="#FFFAFAFA" Offset="1"/>
                            <Border Width="95" Height="70" BorderThickness="1" Margin="0,5,0,3" BorderBrush="#FF000000" Background="Black">
                            <Image Width="95" Height="70" Source="{Binding ImageURL}" Stretch="UniformToFill" Margin="0">
                            		<ei:FluidMoveSetTagBehavior Tag="DataContext"/>
                            <TextBlock Text="{Binding Caption}" TextAlignment="Center" FontWeight="Bold" Foreground="Black"/>

In the layout, I basically have a list box on the left hand side with a custom data template for the list items. On the right, there is another grid with an image and a textbox. I am not going to cover data binding in this example, but you will see there is a reference to my view model and binding set for each element in the view.

After creating the layout, I turned my attention to the model and view model. The model at this time is very simple, it has three properties that are used to display in the View.

    public class ImageData
        public ImageData() { }

        public string ImageURL { get; set; }
        public string Caption { get; set; }
        public string Description { get; set; }

I decided to inherit from an ObservableCollection for my collection that would be bound to the grid. This ended up with a few caveats that I’ll cover when I get to the data access layer of the project.

    public class ImageDataCollection : ObservableCollection<ImageData>
        public static bool IsInDesignMode
                return DesignerProperties.IsInDesignTool;

        public ImageDataCollection() {
			// Logic to load my sample data -- these are just random images from the web
            if (ImageDataCollection.IsInDesignMode)
                this.Add(new ImageData { Caption = "A Bug's Life", ImageURL = "" });
                this.Add(new ImageData { Caption = "Stress", ImageURL = "" });
                this.Add(new ImageData { Caption = "Foggy Morning", ImageURL = "" });
                this.Add(new ImageData { Caption = "Cadet Life", ImageURL = "" });
                this.Add(new ImageData { Caption = "Life on Mars", ImageURL = "" });
                this.Add(new ImageData { Caption = "Tranquility", ImageURL = "" });
                this.Add(new ImageData { Caption = "Night Memory", ImageURL = "" });
                this.Add(new ImageData { Caption = "Mountains", ImageURL = "" });
                this.Add(new ImageData { Caption = "Raindrops", ImageURL = "" });
                this.Add(new ImageData { Caption = "Apartment Life", ImageURL = "" });
                this.Add(new ImageData { Caption = "Concepts", ImageURL = "" });
                this.Add(new ImageData { Caption = "Going Green", ImageURL = "" });
                this.Add(new ImageData { Caption = "Bell V22", ImageURL = "" });
                this.Add(new ImageData { Caption = "Bell 429", ImageURL = "" });
                this.Add(new ImageData { Caption = "Bell Helicopter", ImageURL = "" });
                this.Add(new ImageData { Caption = "Freedom", ImageURL = "" });
                this.Add(new ImageData { Caption = "Lamborghini", ImageURL = "" });
                this.Add(new ImageData { Caption = "Audi", ImageURL = "" });
                this.Add(new ImageData { Caption = "Concept Corvette", ImageURL = "" });
                this.Add(new ImageData { Caption = "Transformer", ImageURL = "" });

		// This is my method to load data dynamically from SharePoint. I decided to use an interface so it could be easily replaced if necessary.
        public void LoadData(IImageCollectionDataLoader loader)
            if (!ImageDataCollection.IsInDesignMode)

        private ImageData _Current;
        public ImageData SelectedItem
                return _Current;
                if (_Current != value)
                    _Current = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("SelectedItem"));

So far, the project has been pretty painless. As I mention in the comments of the source code above, I decided to make use of an interface for my data access layer. It is a very simple implementation on purpose — I just want to get things working!

public interface IImageCollectionDataLoader
	void LoadData(ImageDataCollection dataContainer);

Now I’m ready to build a data access layer. This will make use of the new SharePoint 2010 Client Access Object Model to obtain the data and notify the UI that the data is ready to display. The class will inherit from the interface that was defined above.

    public class SharePointImageLoader : IImageCollectionDataLoader
        public SharePointImageLoader(string LibraryName, int ItemsToLoad)
            _libraryName = LibraryName;
            _totalItems = ItemsToLoad;

        public void LoadData(ImageDataCollection dataContainer)
			Throw New NotImplementedException();

There are some variables that must first be defined so I can have a global access to them. This is because the methods I’ll be using deal are executed asynchronously.

		// The client object model context
        private ClientContext _context = null;
		// A reference to the current website
        private Web _web = null;
		// A reference to the targeted list
        private List _targetList = null;
		// A collection of items queried from the targeted list
        private ListItemCollection _items = null;
		// A reference to the image data collection used for binding on the UI thread -- my view model
        private ImageDataCollection _imagedata = null;
		// The name of the library that will be configured on the web part
        private string _libraryName = string.Empty;
		// The total items to query -- we don't want them all!
        private int _totalItems = 0;

The LoadData method needs an implementation. This will make use of the client object model (humor me, I’m forcing myself to learn how to use it so I can hopefully cheer when using WCF).

        public void LoadData(ImageDataCollection dataContainer)
			// Set the view model -- it will be used later for adding new elements from the query
            _imagedata = dataContainer;
			// Get the current client context for client side queries of SharePoint data
            _context = ClientContext.Current;
			// Get the current web
            _web = _context.Web;
			// Get the list as specified by the name of the library -- this is set in the constructor
            _targetList = _web.Lists.GetByTitle(_libraryName);

			// Set the properties to load, and load the website
            _context.Load(_web, website => website.Title);
			// Load the list

			// Create a basic query to limit the total items returned
            CamlQuery query = new CamlQuery();
            query.ViewXml =
                <RowLimit>" + _totalItems + @"</RowLimit>

			// Instruct the context to execute a query to the targeted list and get back the resulting items.
            _items = _targetList.GetItems(query);
			// Tell the context what fields to load
            _context.Load(_items, items => items.Include(item => item.Id, item => item.DisplayName, item => item["Title"], item => item["NameOrTitle"], item => item["EncodedAbsUrl"], item => item["_Comments"], item => item["EncodedAbsThumbnailUrl"]));

			// Now, get busy and load that data!
            _context.ExecuteQueryAsync(AddItemsToCollection, AddItemsFailed);

Loading the data happens asynchrounously, so delegates must be provided for when the method returns successfully or in a failure. This is where I found my first difficulty with the ObservableCollection I used as the base for my View Model. For some reason, the call to add an item to the collection results in a cross-thread security exception — no problem, let’s make sure the call is dispatched to the UI thread properly

        private void AddItemsToCollection(object sender, ClientRequestSucceededEventArgs e)
			// Time to iterate through all the items we've found
            foreach (ListItem listItem in _items)
				// Create a new model
                ImageData newItem = new ImageData();

				// Start setting the properties of the new model -- use the Title if it is available, otherwise
				// the name of the file will work.
                if (listItem["Title"].ToString().Trim().Length > 0)
                    newItem.Caption = listItem["Title"].ToString();
                    newItem.Caption = listItem["NameOrTitle"].ToString();

				// Get the absolute URL
                newItem.ImageURL = listItem["EncodedAbsUrl"].ToString();

				// Load up any comments -- otherwise set it to an empty value.
                if (listItem["_Comments"] != null)
                    newItem.Description = listItem["_Comments"].ToString();
                    newItem.Description = string.Empty;

				// Aha! Here's where we have to make sure we dispatch the add method to the proper thread
				// so let's just do that now
                Deployment.Current.Dispatcher.BeginInvoke(() =>

		// I'm optimistic -- we won't have any errors! That's how confident I am that
		// my code will work -> or maybe, I'm just not interested in making my example overly
		// complex
        private void AddItemsFailed(object sender, ClientRequestFailedEventArgs e)

The data layer can now retrieve data from SharePoint using the client object model and add new models to my view model. Now, there is a little code that I need to add to my code-behind (MVVM Purists, just skip this section and pretend I didn’t say anything about putting something in the code behind). A few extra lines of code are needed to begin loading the data once the Silverlight application is loaded.

        public MainPage(string LibraryName, int ItemsToLoad)
            SharePointImageLoader loader = new SharePointImageLoader(LibraryName, ItemsToLoad);

And a modification to the App.xaml.cs file and the Silverlight project is finished:

        private void Application_Startup(object sender, StartupEventArgs e)
            string parameterName = e.InitParams["Name"];
            int totalItems = Convert.ToInt32(e.InitParams["TotalItems"]);
            this.RootVisual = new MainPage(parameterName, totalItems);
            ApplicationContext.Init(e.InitParams, System.Threading.SynchronizationContext.Current);

To make this solution as easy to deploy as possible, I created a SharePoint project and followed the instructions of many blogs on how to reference my XAP file. In order to keep the project as portable as possible, I decided it should be a sandbox solution. The solution is completed after I add a new web part to the SharePoint solution:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace SilverlightViewer.SilverlightViewerWebPart
    public class SilverlightViewerWebPart : WebPart
        private string _ListName = string.Empty;
        [WebBrowsable(true), WebDescription("The name of the list to load images from"), WebDisplayName("Asset List"), Category("Configuration"), Personalizable( PersonalizationScope.Shared)]
        public string ListName
                return _ListName;
                _ListName = value;

        private int _TotalImages = 20;
        [WebBrowsable(true), WebDescription("The total number of images to retrieve from the library"), WebDisplayName("Total Images"), Category("Configuration"), Personalizable(PersonalizationScope.Shared)]
        public int TotalImages
                return _TotalImages;
                _TotalImages = value;

        protected override void OnPreRender(EventArgs e)
            if (ListName.Trim() != string.Empty)
                System.Text.StringBuilder builder = new System.Text.StringBuilder();
                builder.Append("<div id=\"silverlightControlHost\">");
                builder.Append("<object data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" width=\"99%\" height=\"99%\">");
                builder.Append("<param name=\"source\" value=\"/_catalogs/wp/Tribridge.Silverlight.ImageViewer.xap\"/>");
                builder.Append("<param name=\"background\" value=\"white\"/>");
                builder.Append("<param name=\"minRuntimeVersion\" value=\"4.0.50826.0\"/>");
                builder.Append("<param name=\"autoUpgrade\" value=\"true\"/>");
                builder.Append("<param name=\"initParams\" value=\"Name=" + ListName + ",TotalItems=" + TotalImages.ToString() + ",MS.SP.url=" + SPContext.Current.Site.Url + "\" />");
                builder.Append("<a href=\"\" style=\"text-decoration:none\">");
                builder.Append("<img src=\"\" alt=\"Get Microsoft Silverlight\" style=\"border-style:none\"/>");
                builder.Append("</object><iframe id=\"_sl_historyFrame\" style=\"visibility:hidden;height:0px;width:0px;border:0px\"></iframe></div>");

                Controls.Add(new LiteralControl(builder.ToString()));
                Controls.Add(new LiteralControl("<p>Unable to load the viewer because the list name has not been configured.</p>"));

Here you can see the final project inside of SharePoint (however, it takes a long time to load because I decided to upload unprocessed images into my image library — each one is at least 5MB and it takes forever to download all that data!):


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s