DevLost

A developer lost in the mountains

Silverlight and Sharepoint 2010 a step forward: how to build a small Silverlight 4 utility to upload files in a List or Library of Sharepoint

This article may be considered as the continuation of my previous article “Silverlight and Sharepoint 2010: Getting Started” where I described how to integrate Silverlight applications in a SharePoint solution. This time we will take a step forward investigating on the Silverlight Client Object Model available in Sharepoint 2010. To better understand what we can do we will create, as an exercise, a small but powerful Silverlight utility to upload files, images and documents inside a Library or List.

What we want to do

The objective is to create a Silverlight application capable to list the Libraries and Lists of a Sharepoint site in a DataGrid. We want to be able to insert one or more files into a Library or List through a simple drag & drop of files from the file system over an item of the DataGrid. I decided to do this because the standard procedure to upload files on Sharepoint is a little boring as you will see in the next paragraph.
In this video you can see briefly the creation of the application and here you can download the code.

HomePage

The standard procedure to upload images and files in Sharepoint

Depending on the site template you have chosen, SharePoint 2010 provides a series of lists and libraries where it is suggested to load the images, style sheets, documents, files, etc. In particular, the “Team Site” template includes four Document Libraries which, as you can see in the image below, should be used according to the rules described on the right.

documentLibraries

Now let’s suppose we want to add a series of images to the Site Assets Library and a css file to the Style Library. Starting from the home page, we have to click on “Libraries”, then on “Site Assets”, then on “add document”, then on “Upload multiple files…”, then drag&drop the image files and eventually click OK. To insert the css file we have to follow more or less the same procedure. The following image shows all the steps required.

SP_procedure

It is a little boring, isn’t it? Would not it be better to see all the Libraries and Lists inside a flat grid and perform the drag and drop on a row of the grid? Let’s find out in the next paragraphs.

Building the Silverlight application responsible for uploading files

First of all make sure you have installed the Silverlight Toolkit, since we will use some controls included in this package. Let’s create a new project of type “Silverlight application” in Visual Studio; you can skip the option to “Host the Silverlight application in a new Web site” since we will use a Sharepoint site instead. Add the references to “System.Windows.Controls.Toolkit” and “System.Windows.Controls.Data.Toolkit” and insert the xaml code below in MainPage.xaml:

 xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"             
 xmlns:toolkitData="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Toolkit"  
 >
  
  <toolkit:BusyIndicator x:Name="busyIndicatorElement" IsBusy="false" BusyContent="Contacting Sharepoint..." >
      <toolkitData:DataGridDragDropTarget x:Name="MainGridDragDropElement" HorizontalAlignment="Stretch">
          <sdk:DataGrid Name="MainGridElement" AutoGenerateColumns="True" AllowDrop="True"  HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Visible"  HorizontalAlignment="Stretch" />
      </toolkitData:DataGridDragDropTarget>
  </toolkit:BusyIndicator>

As you can see the interface is very basic: a BusyIndicator Control surrounds a DataGrid with its drag-n-drop-target Content Control. I used the BusyIndicator Control to get an immediate feedback each time the application is waiting for a response from Sharepoint.

Getting data from Sharepoint using the Silverlight Client Object Model

Using the SL Client Object model to retrieve data from Sharepoint is easier than it seems. However, before going any further you should have three things clear in mind:

  1. since Silverlight follows an asynchronous model, you can only make asynchronous queries to the Sharepoint Server from the UI thread. You can perform synchronous queries only in a thread that does not interact with the UI thread for instance using a ThreadPool.QueueUserWorkItem()
  2. you have to perform two separate tasks: firstly inform the Client Object Model about operations that you need (i.e. accessing properties of Sharepoint objects, data retrieval etc) using a “Load()” method and then send these “loaded operations” to Sharepoint launching an asynchronous call.
  3. any asynchronous query you make, be it successful or failed, will fire a callback running into another thread other than the main UI thread.

To play with the Client Object model you need to add the following reference assemblies: Microsoft.SharePoint.Client.Silverlight and Microsoft.SharePoint.Client.Silverlight.Runtime. They are usually located in “\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin”.

The namespace to use is, as you may guess, Microsoft.SharePoint.Client;

In our specific application that we want to build we need to know the title of the Libraries and Lists included in our Sharepoint site. How can that be obtained? First by defining a ClientContext object in the MainPage code behind , then by creating a method to load your requests to the Client Model and recall it from the MainPage() constructor after InitializeComponent():

 public partial class MainPage : UserControl
  
    private ClientContext myClContext;
  
    public MainPage()
    {
        InitializeComponent();
  
        // Drop Event Handler
        MainGridElement.Drop += new DragEventHandler(SPListsGrid_Drop);
  
        ConnectToSP();
    }
     
    private void ConnectToSP()
    {
        myClContext = new ClientContext("http://My_Server_name");
  
        myClContext.Load(myClContext.Web);
        myClContext.Load(myClContext.Web.Lists);
   
        myClContext.ExecuteQueryAsync(OnConnectSucceeded, OnConnectFailed);
        busyIndicatorElement.IsBusy = true;
    }

As you can see, I instantiated a ClientContext giving the Url of the server then I asked for the access to the Web and Lists objects of Sharepoint calling the load() method. Eventually, I called ExecuteQueryAsync() passing the callbacks to activate in case of success and failure.

Since the callbacks run in a separate thread we can only schedule the execution of the necessary update of the UI using a Dispatcher:

 // callbacks
 private void OnConnectSucceeded(Object sender, ClientRequestSucceededEventArgs args)
 {
     Dispatcher.BeginInvoke(FillGrid);
 }
  
  
 private void OnConnectFailed(object sender, ClientRequestFailedEventArgs args)
 {
     Dispatcher.BeginInvoke(NotifyFailure);
 }

The OnConnectSucceeded(..) callback invokes the execution of the method FillGrid() in the UI thread; FillGrid() performs the databinding to the DataGrid as follows:

 private void FillGrid()
 {
     busyIndicatorElement.IsBusy = false;
     var isource = from List ls in myClContext.Web.Lists.AsEnumerable()
                   select new InfoList() { Title = ls.Title, Description = ls.Description };
  
     MainGridElement.ItemsSource = isource;
 }
   
 public class InfoList
 {
     public string Title { get; set; }
     public string Description { get; set; }
 }

where I used a dummy object (InfoList) since the databinding with anonymous types is still an issue in Silverlight.

Capturing the Drop event and uploading the files dragged

Now it’s time to add the logic for handling the drag&drop of files in the DataGrid. Just an event handler for the Drop event is needed:

 void SPListsGrid_Drop(object sender, DragEventArgs e)
 {
     if (e.Data == null)
         return;
  
     // we have to identify the item in the Grid where the file is dropped 
     Point loc = e.GetPosition(Application.Current.RootVisual);
  
     var list = VisualTreeHelper.FindElementsInHostCoordinates(loc, MainGridElement);
     DataGridRow row = list.FirstOrDefault(i => i is DataGridRow) as DataGridRow;
   
     if (row != null)
     {
         IDataObject dataObject = e.Data as IDataObject;
         FileInfo[] files = dataObject.GetData(DataFormats.FileDrop) as FileInfo[];
   
         InfoList listDetails = row.DataContext as InfoList;
         foreach (FileInfo file in files)
         {
             UploadFile(file, listDetails.Title);
         }
     }
 }

The code above locates the row where the files were dropped and for each of them calls the Upload() method where, again, the Client Object Model is implicated. Here the code for the Upload() method:

 private void UploadFile(FileInfo fileToUpload, string libraryTitle)
 {
     var web = myClContext.Web;
     List destinationList = web.Lists.GetByTitle(libraryTitle);
  
     var fciFileToUpload = new FileCreationInformation();
  
     Stream streamToUpload = fileToUpload.OpenRead();
     int length = (int)streamToUpload.Length;  // get file length
   
     fciFileToUpload.Content = new byte[length];
  
     int count = 0;                        // actual number of bytes read
     int sum = 0;                          // total number of bytes read
  
     while ((count = streamToUpload.Read(fciFileToUpload.Content, sum, length - sum)) > 0)
         sum += count;  // sum is a buffer offset for next reading
     streamToUpload.Close();
   
     fciFileToUpload.Url = fileToUpload.Name;
   
     Microsoft.SharePoint.Client.File clFileToUpload = destinationList.RootFolder.Files.Add(fciFileToUpload);
  
     myClContext.Load(clFileToUpload);
     myClContext.ExecuteQueryAsync(OnLoadingSucceeded, OnLoadingFailed);
     busyIndicatorElement.IsBusy = true;
 }

What is interesting to highlight in the UploadFile() above is that we make use of the Web object of the ClientContext included as a request in the previous query to get the List (or Library) where we want to put the file. Once we have the list (destinationList), we read the file and create a Sharepoint.Client.File object, then load it in the ClientContext created at the beginning. Once again, an asynchronous request is submitted to perform the action. In the OnLoadingSucceeded() callback you can notify the user about the positive result of the operation in various ways. In the source code of my example I just added a “OK, file uploaded!” message box.

Deploy the Silverlight application using a Visual WebPart

In my previous article “Silverlight and Sharepoint 2010: Getting Started” I described three different methods to insert a Silverlight application in a Sharepoint Site. Now we are going to see the fourth (yes, another one). Somehow it is a combination between the second method, “Using a web part”, and the third method “Using a Sharepoint module”. In fact, as in the second method, the Silverlight application is attached to the Visual Web Part by adding a portion of HTML code, which includes the Silverlight host control to the rendering of the web part. Furthermore, for the deployment this fourth method makes use of a mechanism similar to the module method where a module ferries the Silverlight application inside Sharepoint but this time the 'ferry' is the Visual WebPart.

The reason why I used this new method will be clear in a moment, for now I anticipate that in this way we will be able to pass values and parameters between the web part and the Silverlight application. Let’s go ahead by adding a new project to the solution of the Siverlight app that we have just created. Choose the “Sharepoint 2010 Visual Web Part” template from “New Project in Visual Studio:

lib

Choose the option “Deploy as a farm solution”, in the Solution Explorer, locate the “VisualWebPart1” automatically generated and delete it. Now right click on the Project name and choose “Add new item”; from the dialog box choose the “Visual Web Part” template of Sharepoint 2010 and call it “FileUploaderVWP” as in the image below:

FileUploaderVWP

Don’t worry about this strange procedure, it’s just a pragmatic way to give an identifiable name to the Visual Web Part without having to change it by hand here and there in various files. Open the source code of the Visual Web Part (it should be the file “FileUploaderVWP.cs”) and override the Prerender() method as follows:

 protected override void OnPreRender(EventArgs e)
 {
     string webUrl = SPContext.Current.Web.Url;
      
     string renderHost = @"<div id='silverlightControlHost'>
     <object data='data:application/x-silverlight-2,'
     type='application/x-silverlight-2' width='100%' height='100%'>
     <param name='source' value='/_catalogs/wp/SLFileUpload.xap'/>
     <param name='background' value='white' />
     <param name='minRuntimeVersion' value='4.0.50303.0' />
     <param name='autoUpgrade' value='true' />
     <param name='windowless' value='false'/>
     <param name='initParams' value='host_url=" + webUrl +  @"' />
     <a href='http://go.microsoft.com/fwlink/?LinkID=149156
     &v=4.0.50303.0' style='text-decoration:none'>
     <img src='http://go.microsoft.com/fwlink/?LinkId=161376'
     alt='Get Microsoft Silverlight' style='border-style:none'/>
     </a>
     </object><iframe id='_sl_historyFrame' style='visibility:hidden;
     height:0px;width:0px;border:0px'></iframe></div>";
    
     LiteralControl host = new LiteralControl(renderHost);
     Controls.Add(host);
     base.OnPreRender(e);
 }

As you may see a Silverlight host control is injected into the HTML before the rendering of the web part. Now give a look at the value of “source” parameter: “/_catalogs/wp/”; it is the default path where Sharepoint puts all the web parts. We will put also our Silverlight app in this folder in a while. The other interesting thing here is that at the beginning we make a call to the server object model of Sharepoint to retrieve the Url of our Sharepoint site (this code runs on the server so we don’t need to invoke the client model here). The url is then passed to the Silverlight app as an initParams attribute called “host_url”. Why are we doing this? Because when in the Silverlight app we query the Client object model for the first time , we can’t obtain this information in any way.

If you have noticed in the code snippet added in the paragraph Getting data from Sharepoint using the Silverlight Client Object Model, I had included the name of the server statically:

 myClContext = new ClientContext(http://my_server_name/);

This makes the application unusable in other domains without recompile. Passing this information as parameter solves the problem. Now you can substitute the line of code above with the following:

 string webUrl = App.Current.Host.InitParams["host_url"];
 myClContext = new ClientContext(webUrl);

and the application will work also in other domains.

Using the Visual Web Part as a ‘ferry’

The next step is to raise your thumb and hitchhike to find someone who has a seat available for your Silverlight application, destination: 'Sharepoint'. In my previous article it was a module, this time it is the visual Web Part itself. Let’s go back to Visual Studio and, in the Solution Explorer, right click on your Web Part (FileUploaderVWP) and click on “Properties” in the context menu. In the Properties panel Select the “Project Output References” property and click on the small button on the right to open the “Project Output References” Dialog Box; here click on the “Add” button to add an item to the list on the left; configure the properties on the right as shown in the following image:

ProjectOutputReferences

Unfortunately this step is not enough to fully instruct the deployment process. We need to manually modify the file Elements.xml under the Visual Web Part tree including the line highlighted:

 <?xml version="1.0" encoding="utf-8"?>
 <Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
   <Module Name="SPFileUploadVWP" List="113" Url="_catalogs/wp">
     <File Path="SPFileUploadVWP\SPFileUploadVWP.webpart" Url="SPFileUploadVWP.webpart" Type="GhostableInLibrary" >
       <Property Name="Group" Value="Custom" />
     </File>
     <File Path="SPFileUploadVWP\SLFileUpload.xap" Url="SLFileUpload.xap" />
   </Module>
 </Elements>

Here, contrary to what we saw in the 'module method' Visual Studio does not help us to update the file automatically.
You can now select the Sharepoint project just included in the Solution as the “Startup project”, add the Silverlight Project to its “Project Dependencies” and deploy your solution. Your “.xap” file will be added to Sharepoint in the same folder of the other web parts.

Don’t forget to enable debugging: open the dialog box of the properties of your Sharepoint Visual Web Part project; click on the “SharePoint” tab option and set the “Enable Silverlight debugging (instead of Script debugging) checkbox”.

EnableDebugging

Summary

In this article we have put togheter the potential of Silverlight and of the SL Client Object Model added in Sharepoint 2010 to create a small but useful utility to quickly load files in a List or Library of Sharepoint. We have learned how to get the title and description of all the Libraries and Lists in our Sharepoint site and how to insert files in a List. We have also learned how to pass data from the host Web Part to the Silverlight application. Possible improvements are: finding a way to allow upload ing of large files (this is regulated by a setting of the site accessible from the administration) , an extended DataGrid showing the files included in each List or Library, interaction with the publishing framework and a better look and feel in general.