Export (0) Print
Expand All
3 out of 5 rated this helpful - Rate this topic

Chapter 14: Silverlight and SharePoint Integration (Professional SharePoint Branding and User Interface Design)

SharePoint 2010

Summary: This chapter discusses Microsoft Silverlight features and tools, how to create a Silverlight Web Part, how to access SharePoint 2010 data by using the Client Object Model, and how to extend Microsoft Visual Studio to create Silverlight solutions.

This article is an excerpt from Professional SharePoint Branding and User Interface Design by Randy Drisgill, John Ross, Jacob J. Sanford, and Paul Stubb, published by Wrox Press (ISBN 978-0-470-58463-7, copyright © 2010 by Wrox, all rights reserved). No part of these chapters may be reproduced, stored in a retrieval system, or transmitted in any form or by any means—electronic, electrostatic, mechanical, photocopying, recording, or otherwise—without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews.

Contents

Click to grab code  Download code

Introduction

Silverlight delivers rich user experiences and the tools developers and designers need to rapidly create these experiences. Silverlight has had amazing penetration in the consumer space, with more than 500 million downloads and over 500,000 developers and designers (and more every day). As Silverlight reaches critical mass, many developers and designers are turning their Silverlight skills toward other platforms, such as SharePoint. I generally see two types of SharePoint developers: those who are new to Silverlight, and those who are new to SharePoint. So, this chapter delves somewhat deeper into programming than many of the other chapters, but designers are frequently asked to work with technologies like Silverlight because of the richinteractive user interfaces that they make available. Silverlight projects often involve designers and developers to ensure the application looks as nice as it performs. This chapter covers Silverlight as it pertains to SharePoint. To learn more about Silverlight development, check out Wrox's Professional Silverlight 4.

SharePoint 2010 has a flexible security infrastructure that supports a number of different technologies (such as AD, claims-based authentication, forms-based authentication, Kerberos, and many more). The different types of security in SharePoint support different scenarios. For example, if you're trying to grant access for an individual or group to content on a site within your organization, then you would leverage AD, and assign permissions to specific site content to individuals or groups. If you were trying to federate that access to an external system (for example, integrating SAP data within a SharePoint site), then you might use the Secure Store Service (SSS) or claims-based authentication to provision access.

When you're developing for SharePoint, you develop and deploy applications at different security levels. For example, you can build either a farm-level solution or a sandboxed solution for SharePoint 2010. You also need to think about those users who have access to specific service-based applications, such as applications based on Business Connectivity Services (BCS). Exposing augmented permissions to all users could result in unwanted deletions, corruptions, or, worse, data mismanagement or public exposure.

The key take-away here is that you have many different ways in SharePoint to negotiate and configure security.

In this chapter, you'll start by becoming familiar with the authorization fundamentals using AD. You'll then see how you can develop farm-level and sandboxed solutions to get a sense for how they're different. You'll also see how you can use SSS to provision access to external systems for BCS applications. And, finally, you'll learn about federated authentication for SharePoint through forms-based and claims-based authentication.

Silverlight Features

Silverlight platform development is on a breathtaking pace, with a major new version delivered, on average, every 7 to 12 months. The Silverlight runtime works across multiple browsers and platforms. It also works both in the browser and out of the browser and on Windows Phone 7 devices and other mobile devices. You can loosely think about Silverlight as a competitor to Adobe Flash. Let's look briefly at some of the major feature areas and how those features fit with SharePoint.

  • Media — Silverlight was earliest renown as a great platform for media. It supports video, such as h.264 standard. It also supports smooth streaming and video camera and microphone input. In this chapter, you will see how to leverage these features to deliver media in SharePoint 2010.

  • Rich experiences — Silverlight has a number of rich experience features, including copy and paste, drag and drop, and a fluid interface.

  • Business applications — Although many Silverlight applications on the Internet are consumer-focused experiences, Silverlight has also been adding more features to make it a great platform for building business/SharePoint applications. These features include enhanced data binding, more forms controls, printing, the Managed Extensibility Framework, and internationalization support. Silverlight also supports dynamic theming, which enables Silverlight applications to look and feel like the SharePoint sites that host them.

  • Desktop applications — Most people think about Silverlight running in the browser or in SharePoint 2010 (the latter being the case in this chapter), but Silverlight can be run out of the browser, on the user's desktop. When the application is running on the desktop, it can still connect to SharePoint data and runs in the same domain as its origin SharePoint site. When the application is running out of the browser, it gains additional features such as access to the local file system, the ability to call COM applications such as Office applications, notifications, and the ability to render HTML inside of the Silverlight application.

This is a most basic list of Silverlight features — just enough to give you an idea about what this platform makes available. You will use some of these features in the examples in this chapter. At this point, however, let's examine the tools that enable you to create these rich experiences.

Silverlight Tools

Silverlight development tools are split into two tools that work seamlessly together.

  • Microsoft Expression Blend — Expression Blend is part of the Expression Suite. Expression Blend, shown in Figure 1, is a tool that designers will feel most comfortable with. It enables designers to create rich media and animated user experiences without writing code.

  • Visual Studio — Visual Studio is the tool that developers will feel most comfortable with. Visual Studio enables developers to create rich Silverlight applications that contain code.

Both tools have code editors and visual designers, but Expression Blend has, by far, the best visual designer, and Visual Studio has, by far, the best code-editing tools.

Many developers who also design their applications use both tools interchangeably during the application development process. If a clear separation of duties exists between designers and developers, however, the two tools really shine, facilitating easier collaboration between designers and developers without requiring much knowledge about what the other is doing. In other words, the designer and developer are loosely coupled and can work independently of each other and can even work in parallel.

Figure 1. Expression Blend user interface

Expression Blend user interface

Out-of-the-box

SharePoint has taken a big bet on Silverlight. This really speaks to the maturity of Silverlight. Microsoft is very conservative about the technologies they add to the Office and SharePoint platforms. But they saw the incredible value that Silverlight brings to the SharePoint developer. Not only do they support Silverlight in SharePoint, there are actually a number of places where SharePoint is built using Silverlight.

Let's look at a few examples of where Silverlight is used out-of-the-box in SharePoint. You'll most likely first encounter Silverlight in the Create dialog box, where you can create new content in SharePoint (pages, lists, libraries, and sites). To open the Create dialog box, click the Site Actions menu at the upper left of the site and then click More Options. Figure 2 shows a modal dialog box open with the Silverlight-based page for adding new content.

Figure 2. Silverlight content in the Create dialog box

Silverlight content in the Create dialog box

The Create dialog box has animation effects for the icons as you navigate around the control and filter templates using the categories listed on the left side. This is a vastly better experience than you have without Silverlight. If you do not have Silverlight installed or enabled, you will default back to the old-style Create page, which is not as user friendly. Figure 3 shows the non-Silverlight Create page for comparison.

Another great example of an out-of-the-box Silverlight experience is on your personal My Site. Your personal My Site is your own private site on which you can store your own documents. Your My Site also has a lot of profile information about you and your organization. Think of your personal My Site as a SharePoint version of your Facebook page. SharePoint ships with a Silverlight version of an Organization Browser. This very interesting control enables you to browse your organization both horizontally and vertically. Figure 4 shows an example of the Silverlight Organization Browser.

SharePoint has also made SharePoint a great platform for serving rich media. For example, they have a built-in Silverlight Media Web part that you can easily add to any page to show videos. Silverlight is also used to quick preview media elements in asset libraries. The Silverlight media control is also interesting because you can change the skin simply by copying and modifying the /Style Library/Media Player/AlternateMediaPlayer.xaml file. The media control even has a JavaScript API to do things such as play and stop the video. Figure 5 shows the media player and its associated context ribbon menu items.

Figure 3. No Silverlight content in the Create dialog box

No Silverlight content in the Create dialog box

 

Figure 4. Organization browser

Organization browser

 

Figure 5. Media Web part and associated ribbon

Media Web part and associated ribbon

You will see Silverlight used in a number of other places as well (some are where you might not even realize). Even some of the new Office web applications use Silverlight to enhance the rendering and display of the Office documents.

All this integration is great for both SharePoint and Silverlight developers. You can assume that the integration of Silverlight in SharePoint will only increase in the future. Now that you know a little about Silverlight and where it is used in SharePoint, let's spend the rest of this chapter showing how to build your own Silverlight solutions in SharePoint.

Silverlight web part

SharePoint 2010 ships with a Silverlight Web part, making it very easy for developers and power users to add Silverlight applications to SharePoint. You must solve two basic problems when you develop Silverlight applications for SharePoint: how to get the Silverlight application into SharePoint, and how to host the Silverlight application.

The first problem to solve is how to get the Silverlight application into SharePoint. You can do so in a number of ways, as discussed in more detail in the next section. The easiest way is just to copy the Silverlight application to a SharePoint library. A simple Silverlight application consists of a single Zip file with the extension .xap. You can build these Silverlight applications yourself or you can download from various sites on the Internet or buy them from third-party developers. In this example, I downloaded a Weather application from the MSDN code gallery. You can download the source files from Silverlight Web Services Samples. In fact, this was actually a Silverlight version 2 sample. I opened the solution in Expression Blend 4, and it upgraded the project to Silverlight version 4. The MSDN site also contains a prebuilt version of the .xap that you can use without any changes. Once you have the .xap file, follow these steps to upload the Silverlight application to the Shared Documents library on your site.

To upload the Silverlight application to the Shared Documents library

  1. On the ribbon for the Shared Documents library, display the Documents tab, and then click Upload Document from the New group.

  2. Browse to the Weather application's .xap file and click OK.

You now have the Silverlight application in SharePoint. The next problem to solve is how to host the Silverlight application. The most common way that developers add applications to SharePoint is using Web parts. Web parts in SharePoint allow developers to create "composite-able" units of functionality that power users can put together to make SharePoint sites and applications. SharePoint includes a Silverlight Web part out-of-the-box. The Silverlight Web part is as easy to use as setting the path to the Silverlight application. Let's go ahead and add the Silverlight Web part to the home page of your site.

To add the Silverlight web part to the home page

  1. Put the page in edit mode by clicking Edit Page from the Site Actions menu in the upper left of your site.

  2. Insert the Silverlight Web part. Once the page is in edit mode, you will see the Editing Tools context ribbon tab. Display the Insert tab of the Editing Tools tab, and then click the Web Part button in the Web Parts group.

  3. In the Categories section of the Insert Web Part gallery, select Media and Content. Then click Silverlight Web Part in the Web Parts list. Click Add to insert the Silverlight Web part.

  4. Type the URL to the Silverlight application. When you click the Add button, you are prompted to type the URL to the Silverlight application in a dialog box. This is the path to the .xap file that you uploaded to the Shared Documents library. It should be something like /Shared Documents/WeatherWidget.xap.

  5. Save the Page. Click the Save & Close button of the Edit group of the Page ribbon tab to save the page. You could also adjust other properties of the Web part as well, such as the height and width, title, and others.

After you have added the Weather Silverlight application to the page, it will call out to the weather web service to retrieve the current weather conditions. Figure 6 shows an accurate and real weather forecast for Redmond, Washington.

The SharePoint 2010 team has done a good job of making it very easy for non-developers to add Silverlight functionality to any SharePoint site. But how do professional developers and designers add Silverlight applications using Visual Studio and Expression Blend? How do you follow proper application lifecycle management (ALM), such as source control. How do you follow SharePoint best practices, such as packing all SharePoint applications into SharePoint packages? In the next section, you will learn how to follow all these coding practices using Visual Studio and Expression Blend.

Figure 6. Weather forecast displayed in the Silverlight web part

Weather forecast displayed in Silverlight web part

Visual Studio and Expression Blend

The biggest change for SharePoint 2010 is the availability of tools in Visual Studio 2010. SharePoint 2010 is a great platform now, with great tools to support it. In the past, you may have used a number of different tools and scripts to develop your SharePoint solutions, and most likely these were not Microsoft tools but community tools on sites such as CodePlex. All that has changed now. Now the SharePoint tools in Visual Studio are so good and extensible that you will rarely find occasion to develop outside of Visual Studio. That said, a few scenarios are not covered by the current release. The Visual Studio team knew that with the breadth of SharePoint they would not be able to cover everything right away. Taking this into account, they made it easy to extend the tools and add functionality. Later in this chapter, you will see some of the tools that my team has created to make Silverlight development even easier.

Creating a Silverlight Web Part

Earlier, you saw how easy it is to add a Silverlight application to the page using just the web browser, without writing any code. Now let's examine how to accomplish the same task using Visual Studio. Remember that you are trying to solve two problems. The first is how to get the Silverlight .xap file deployed to SharePoint 2010. The second is how to host the Silverlight application. Before delving into the details of how to do this, let's talk about the high-level process. For this solution, we need two projects.

  • The Silverlight project — This is just a standard Silverlight project and can be created with Visual Studio or Microsoft Expression Blend.

  • The SharePoint 2010 project — The SharePoint project will link to the Silverlight project and deploy both the Silverlight application and the Web part.

Adding a Silverlight project

For this example, you are going to use one of the sample applications that ships with Microsoft Expression Blend. Open Expression Blend and select the Contacts project from the Samples tab. Save a copy of the application under a new name by clicking Save Copy of Project under the File menu (in this case, ContactsInSilverlight). You should see something similar to Figure 7.

Figure 7. Saving the ContactsInSilverlight project

Saving the ContactsInSilverlight project

You can press F5 to compile and run the application. It is also a good practice to verify that everything is working before you move on to the next step. You may get a warning that the application does not have a startup scene. This is because the sample contains projects: the Silverlight application and the web project that hosts the test page. To fix this error, click Startup from the right-click context menu of the default.html file in the web project. (Because you will be using SharePoint to host and test your Silverlight application, you do not need this test web project. You will delete the web project in the next section.) Figure 8 shows the application running in the test web server that Expression Blend creates.

Figure 8. Running the ContactsInSilverlight project

Running the ContactsInSilverlight project

Next you add a SharePoint project to link to this Silverlight application.

Adding a SharePoint 2010 project

Up to this point, you have not really done anything with SharePoint. But you can imagine that this is the step where you have been handed a Silverlight project from a designer, and now you must deploy the application to SharePoint and host the application in a Web part. First, add a SharePoint project to the solution.

To add a SharePoint project to the solution

  1. Open the solution in Visual Studio. Right-click the Solutions node in the Project tab panel in Expression Blend, and from the solution context menu, click Edit in Visual Studio.

    Note that there are actually a couple of small bugs in the sample application that Visual Studio catches but Expression Blend does not. In the ContactsViewSampleDataModel.xaml file, there are actually two records with the Name="Adams, Terry". To fix this, delete the Contacts_ViewModels:ContactViewModel node that this duplicate record is in or change the Name property to something unique. Also there is a missing assembly reference. Add a reference to System.Windows.Controls.Data.Input.

    Figure 9. ContactsInSilverlight in Visual Studio Designer

    ContactsInSilverlight in Visual Studio Designer

  2. Delete the web project. You will be using SharePoint as the Silverlight host, so you do not need the web project that was included as part of the sample. Right-click the web project, click Remove, and then click OK to verify.

  3. Add a blank SharePoint project. Right-click the Solution node in the Solution Explorer. In the context menu, click Add, click New, and then click Project. Click the SharePoint node in the New Project dialog box. Visual Studio comes with a number of SharePoint project templates. You can see the complete list in Figure 10. Name the project ContactsSharePointProject. Click OK to create the project.

    Figure 10. Project templates in SharePoint 2010

    Project templates in SharePoint 2010
    TipTip:

    SharePoint projects require Visual Studio to run with elevated permissions. If you are prompted, click Restart under different credentials to restart Visual Studio with administrator rights.

  4. Specify the site and security level. When it creates SharePoint projects, Visual Studio uses a wizard to set the URL to the SharePoint site and asks you whether this is a farm solution (full trust) or a sandboxed solution. Sandboxed solutions are the default. Silverlight applications can run in sandboxed solutions, and doing so is the best practice for deploying to SharePoint. Enter the site (in this case, use http://intranet.contoso.com). You should also click the Validate button to verify that the path is correct and that everything is set up correctly on the SharePoint site. Click Finish to actually create the Empty SharePoint project.

Linking to the Silverlight project

You now have a Visual Studio solution with two projects: SharePoint and Silverlight. The next task is to deploy the Silverlight application to SharePoint. The way that you deploy files to SharePoint is by using modules. Let's go ahead and add a new module to deploy your Silverlight .xap file and a reference to the Silverlight project, so that when you build the SharePoint project, the Silverlight project will also build, and an updated copy of the Silverlight .xap file will be included in the SharePoint solution file, which is a .wsp file.

To link to the Silverlight project

  1. Add a new Module project item. Right-click the SharePoint project, choose Add and then New Item. Visual Studio comes with 14 SharePoint 2010 project templates, as shown in Figure 11. Select Module and name it SilverlightModule. Click Add to create the module.

    Figure 11. Adding a new module

    Adding a new module

  2. Delete the Sample.txt file. When you create a new module, Visual Studio creates a SharePoint project item that includes an Elements.xml file and a sample file called Sample.txt. You do not need this file, so you can delete it.

  3. Add a reference to the Silverlight project. Normally when you add a reference to another project in Visual Studio, it adds a reference to the output of that project, which is typically the .dll. For Silverlight projects, however, you want a reference to the .xap file. View the Properties window of the SilverlightModule node in your project. You can add a reference to the Silverlight project by adding it to the Project Output References collection. Click the ellipse in the Project Output References property to set the reference. In the Project Output References dialog box, click Add to a new reference, as shown in Figure 12. In the Project Name property, choose your Silverlight project from the drop-down list (in this case, Contacts). Set the Deployment Type property to Element File. Click OK to add the reference.

    Figure 12. Adding a new reference

    Adding a new reference

  4. Set the deployment location. Now that you have referenced the Silverlight application, you must specify where it will be deployed to within your SharePoint site. You specify this in the Elements.xml file. In Elements.xml, the File node has two properties: Path and Url. The Path property is the relative reference to the file within the SharePoint package file, so normally you should not change this. The Url property is the path where the file should be deployed to on the SharePoint site. Set the Url to _catalogs/masterpage/SilverlightModule/Contacts.xap. This will deploy the .xap file to the master page gallery library and create a folder called SilverlightModule.

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Module Name="SilverlightModule">
      <File Path="SilverlightModule\Contacts.xap"
        Url="_catalogs/masterpage/SilverlightModule/Contacts.xap" />
    </Module>
    </Elements>
    

Now you are ready to deploy your Silverlight application file to SharePoint. Set the SharePoint project as the startup project and press F5. SharePoint will build both projects, create the SharePoint package file, deploy it to the sandboxed solution gallery, activate the solution, open the SharePoint site, and attach the debugger. Once the site opens, browse to the master page gallery at http://intranet.contoso.com/_catalogs/masterpage. You should see a folder called SilverlightModule. Open the SilverlightModule and verify that the Contacts.xap file is there. This step has been the programmatic equivalent of manually adding the .xap file to the Shared Documents library that you did earlier in this chapter. You could now go to the home page and manually add the Silverlight Web part to display this application, but in the next section, you learn how to automate this process in your Visual Studio solution.

Adding a Silverlight Web part

You just completed the first step of deploying the Silverlight .xap file. Now you will complete the second step, which is to host the Silverlight application. There are several different approaches that you could take, depending on your specific needs. You could just create a new page to host the Silverlight application just as you would in any ASP.NET website. The more common approach is to create a Web part to host the application. This is what you are going to do in this sample. There are also a number of different ways to create the Web part. You could create your own Web part from scratch and add all the code to correctly render the Silverlight control within the Web part. Although this gives you the most flexibility, it also requires the most work. What I think is a better approach and covers the most common scenarios is to leverage the existing built-in Silverlight Web part provided by SharePoint. Let's add a Silverlight Web part to your SharePoint project.

To add a Silverlight Web part to your project

  1. Add a Web part. Although there are no specific project item templates out-of-the-box for a Silverlight Web part, you can use the normal Web part template as a starting point. Right-click the SharePoint project, click Add, and then choose New Item from the context menu. Select Web Part (not the Visual Web Part) from the list of SharePoint 2010 project item templates. Name the Web part SilverlightWebpart. Click Add to add the Web part to the project.

  2. Remove Custom Web part. When you create a new Web part, SharePoint adds a new SharePoint project item to your project that consists of three files. The first file is the Elements.xml file, used to define the location of the Web part and the group name that it should be placed in. You need this file, so do not delete it. The next two files are the actual Web parts. Remember that a Web part consists of two pieces: the actual code and an XML manifest file. Because you are going to use the built-in Silverlight Web part, you can delete the code file, SilverlightWebPart.cs.

  3. Add the Silverlight Web part. You are going to use the Silverlight Web part that ships with SharePoint so that the code side of the Web part is already deployed. Replace the contents of the file SilverlightWebpart.webpart with the following code.

    <webParts>
      <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
        <metaData>
          <type name="Microsoft.SharePoint.WebPartPages.SilverlightWebPart,
            Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral,
            PublicKeyToken=71e9bce111e9429c" />
          <importErrorMessage>
            Cannot import this Web Part.
          </importErrorMessage>
        </metaData>
      <data>
        <properties>
          <property name="HelpUrl" type="string" />
          <property name="AllowClose" type="bool">True</property>
          <property name="ExportMode" type="exportmode">All</property>
          <property name="Hidden" type="bool">False</property>
          <property name="AllowEdit" type="bool">True</property>
          <property name="Direction" type="direction">NotSet</property>
          <property name="TitleIconImageUrl" type="string" />
          <property name="AllowConnect" type="bool">True</property>
          <property name="HelpMode" type="helpmode">Modal</property>
          <property name="CustomProperties" type="string" null="true" />
          <property name="AllowHide" type="bool">True</property>
          <property name="Description" type="string">
            Contact Silverlight Web Part</property>
          <property name="CatalogIconImageUrl" type="string" />
          <property name="MinRuntimeVersion" type="string" null="true" />
          <property name="ApplicationXml" type="string" />
          <property name="AllowMinimize" type="bool">True</property>
          <property name="AllowZoneChange" type="bool">True</property>
          <property name="CustomInitParameters" type="string" null="true" />
          <property name="Height" type="unit">436px</property>
          <property name="ChromeType" type="chrometype">None</property>
          <property name="Width" type="unit">619px</property>
          <property name="Title" type="string">Contact Silverlight Demo</property>
          <property name="ChromeState" type="chromestate">Normal</property>
          <property name="TitleUrl" type="string" />
          <property name="Url" type="string">
            ~site/_catalogs/masterpage/SilverlightModule/Contacts.xap
          </property>
          <property name="WindowlessMode" type="bool">True</property>
        </properties>
        </data>
      </webPart>
    </webParts>
    

The .webpart has two sections. The first section defines the code for the Web part. In this case, it references the built in Silverlight Web part in the Microsoft.SharePoint.dll. The second section defines all the properties supported by the Web part. You need to change only a few. The most important is the URL that references the Silverlight .xap file. Set this to ~site/_catalogs/masterpage/SilverlightModule/Contacts.xap. Note that this uses a special SharePoint variable called ~site to refer to the current site that the Web part is hosted in. The other properties that you should set are Title, Description, Height, and Width.

You now are done with your solution. It should look something like Figure 13. All that is left to do is deploy and test the solution.

Figure 13. Completed solution before deployment

Completed solution before deployment

Deploying Silverlight to SharePoint

The solution that you created is ready to deploy. Press F5 to deploy the SharePoint solution to the sandboxed solution gallery. Doing so will deploy the Silverlight .xap file and the Silverlight Web part. This solution does not contain a page to test the Web part.

To add a page manually

  1. When the site opens, create a new site page called Contacts.

  2. With the page in Edit Mode, click Insert, and then choose Web Part from the Editing Tools tab on the ribbon.

  3. In the Insert Web Parts panel, select Custom in the Categories column, click Contact Silverlight Demo, and then click Add.

    You can see that your custom Silverlight Web part shows up just like any other Web part in the Web Part gallery. Unlike when you added the Silverlight Web part earlier in this chapter, you are not prompted to type a URL to the Silverlight application because you already defined it when you created the .webpart file.

  4. Save the page to exit edit mode. Figure 14 shows your Silverlight application running in SharePoint.

    Figure 14. Silverlight application running in SharePoint 2010

    Silverlight application running in SharePoint 2010

Now that you have everything working, let's take a quick look at how to debug these types of applications.

Debugging Silverlight applications

Debugging Silverlight applications in SharePoint is actually very easy and straightforward. First, set your breakpoints in the Silverlight application just as you would do with any Visual Studio application. Then, enable Silverlight debugging in the SharePoint project. Right-click the SharePoint project and click Properties from the context menu. Display the SharePoint tab in the project Properties window. Now scroll down to Enable Silverlight debugging (instead of Script debugging), as shown in Figure 15

Figure 15. Enabling Silverlight debugging

Enabling Silverlight debugging

The Client Object Model

Up to this point, you have learned how to create a SharePoint 2010 project to deploy your Silverlight applications. But SharePoint is just hosting the Silverlight application. The application is not really leveraging the SharePoint platform for things such as data. This is the real value of hosting Silverlight inside of SharePoint: leveraging all the data and services that make up the SharePoint platform. You learned in Chapter 13 how to call the Client Object Model by using JavaScript; now you will learn how to leverage the Client Object Model from Silverlight.

In this section, you learn how to hook up your Contacts application to real SharePoint data by using the Client Object Model. The Client Object Model is a new API for SharePoint that enables client applications to efficiently and easily program against the SharePoint server. There are three versions of the Client Object Model: EcmaScript, .NET CLR, and Silverlight. They all are very consistent; after learning one, you should be able to program them all. Although it is beyond the scope of this chapter to teach you everything about the Client Object Model, I will show you how to get started and pull data from SharePoint.

Referencing the Client Object Model

The Silverlight Client Object Model is contained in the Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll assemblies.

Add a reference to these assemblies in your Silverlight project by using the standard Visual Studio Add Reference dialog box. They are located in the C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin folder. These will be added to your Silverlight .xap file. This is not the best practice because it increases the size of your applications and increases the download times. These files are relatively small, 407 KB total. It is not a huge hit, but every little bit helps. Later, you will see how to decouple these from your solution and dynamically load them at runtime.

Reading lists with the Client Object Model

The Contacts application uses the Sample Data features of Expression Blend and Visual Studio to render data into the designer while you are creating the application. It also switches when running to pull data from a different location. In this case, the data is hard-coded into the application. You can see this switch in the ContactsViewModel constructor. This code checks to see whether the app is running in a design tool. If it is not, you want to load the real data, not the sample data (which is defined in the XAML for the page).

if(!DesignerProperties.IsInDesignTool)
{
  this.PopulateContacts();
}

For this application, you can replace the PopulateContacts method with your own implementation. In this case, we will actually get the data from SharePoint using the Client Object Model.

To load data from the SharePoint 2010 by using the Client Object Model

  1. Add a using statement for the Client Object Model. Edit the ContactsViewModel.cs file and add the following code to the top of the page.

    using Microsoft.SharePoint.Client;

  2. Add class variables. The Silverlight Client Object Model is an asynchronous API. You will need to define a couple of variables to track references across method calls. Add the following variables to the ContactsViewModel class.

    public class ContactsViewModel : INotifyPropertyChanged
    {
      ClientContext ctx;
      ListItemCollection contactsListItems;
    ...
    
  3. Get the list data from SharePoint. In the PopulateContacts method of the class, you need to get a reference to the current client context. Then you need to specify which list you want returned and which items in the list you want returned. And finally, you need to load the query on the client context and execute it on the SharePoint server. The ExecuteQueryAsync method executes all the queries that have been loaded onto the client context asynchronously. Once the SharePoint server is finished, it calls back on one of the two callback methods passed depending on whether the request succeeded or failed. Add the follow code to the ContactsViewModel.cs file to get the list data from SharePoint.

    private void PopulateContacts()
    {
      //Get Data from SharePoint using the Client Object Model
    
      //Get a reference to the current client context
      ctx = ClientContext.Current;
    
      //Specify the List and Listitems to return
      List contactsList = ctx.Web.Lists.GetByTitle("Contacts");
      contactsListItems =
        contactsList.GetItems(CamlQuery.CreateAllItemsQuery());
    
      //Add query to context and execute it on the server
      ctx.Load(contactsListItems);
      ctx.ExecuteQueryAsync(ContactsLoaded, ContactsLoadedFail);
    }
    

    Figure 16 shows what the Contacts list looks like in SharePoint. This is just a normal SharePoint list that I created by using sample data from the AdventureWorks database.

    Figure 16. Contacts list in SharePoint 2010

    Contacts list in SharePoint 2010

  4. Handle the failed callback. In the ExecuteQueryAsync method, one of the parameters is the failed callback method. In this example, you will implement a handler that doesn't actually do anything. I normally use this during development as a place to set a breakpoint, but in a production application you would want to take the appropriate action, such as writing to the event log. The callback contains a ClientRequestFailedEventArgs parameter. This contains details about the error (for example, error code, error details, the error message, and even stack trace information). Add the following code to the ContactsViewModel.cs to handle the failed callback.

    void ContactsLoadedFail(object sender,
    ClientRequestFailedEventArgs args)
    {
      string error = args.Message;
    }
    
  5. Load the Contacts collection. In the succeeded callback method, you can iterate through the contactsListItems collection, which was populated when you executed the query on the server. For this example, you are creating new ContactViewModel objects and adding them to the Contacts collection. Most of the code in this is just mapping and formatting the values returned from SharePoint into values expected by the application's object model. I also formatted some of the data to match the format of the sample data (for example, padding the Id field with leading zeros). Also because my sample Contacts list in SharePoint didn't have all the fields used in the sample application, I concatenated different fields together using string.Format and even had to use a regular expression to strip out special characters from the company names. The last important thing to talk about with this code is about threading. Silverlight executes the calls to SharePoint on a background thread. Therefore, if you want to do something to the UI, such as update the contacts, you must do this on the UI thread. To get back on the UI thread, you need to wrap your code in a Dispatcher.BeginInvoke method. Everything inside of the BeginInvoke will run on the UI thread.

    void ContactsLoaded(object sender, ClientRequestSucceededEventArgs args)
    {
      foreach (ListItem ci in contactsListItems)
      {
        ContactViewModel cvm = new ContactViewModel();
        cvm.Id = ci.Id.ToString("D3"); //pad with leading zeros
        cvm.Name = string.Format("{0}, {1}",
          ci.FieldValues["Lastname"].ToString(),
          ci.FieldValues["Title"].ToString());
        cvm.Email = ci.FieldValues["Email"].ToString();
        cvm.Phone.Number = string.Format("{0}-{1}-{2}",
          ci.FieldValues["PhoneNumberAreaCode"].ToString(),
          ci.FieldValues["PhoneNumberPart1"].ToString(),
          ci.FieldValues["PhoneNumberPart2"].ToString());
        //need to strip out non alphanumeric chars for validation
        Regex regEx = new Regex("\\W|[0-9]");
    
        cvm.Blog.Address = string.Format("http://blogs.{0}.com/{1}{2}",
          regEx.Replace(ci.FieldValues["Company"].ToString(),""),
          ci.FieldValues["Title"].ToString(),
          ci.FieldValues["Lastname"].ToString());
        cvm.Website.Address = string.Format("http://www.{0}.com",
          regEx.Replace(ci.FieldValues["Company"].ToString(),""));
        //call back on the UI thread
        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
          Contacts.Add(cvm);
        });
    }
    

That is all the code required to connect your application to live SharePoint list data. Press F5 to run the application. When the site opens, browse to the Contacts page that you created earlier. There is no need to change anything on the page. SharePoint will load the page using the new version of the Silverlight application that you just built. This is very convenient while developing because you need to set up the page in SharePoint only once and can then focus on the Silverlight code. You should now see the list data in your application as shown in Figure 17.

Figure 17. List data displayed for Contacts

List data displayed for Contacts

This example also has a details page, which you can see when you click the ellipse for any given record (see Figure 18).

Figure 18. Details page for a specific Contact

Details page for a specific Contact

Dynamically referencing the Client Object Model

The SharePoint Client Object Model for Silverlight requires references the Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll assemblies.

Earlier in the chapter, you added a reference to these assemblies using the standard Visual Studio Add Reference dialog box. When you add references in Visual Studio, the referenced assemblies are, by default, copied and packaged into Silverlight .xap files. This is not a best practice for the Silverlight Client Object Model because the added assemblies increase the size of all your Silverlight applications by 407KB. There are also maintenance issues. What happens if or when Microsoft updates these files? How do you plan to update the embedded files? Another benefit is that the browser will cache this .xap file just as it would any other file based on the cache policies that are set. Therefore, the .xap file will be stored in the browser's cache location and subject to the user's actions, meaning if the user clears the browser cache, the .xap will be downloaded again on the next request. The best practice is to dynamically load the assemblies at runtime. Doing so solves all the problems associated with embedding them in your .xap files.

In addition to the Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll files, SharePoint ships with a prebuilt .xap called Microsoft.SharePoint.Client.xap. This .xap file is located in the same folder as the other Silverlight Client Object Model files:

C:\Program Files\Common Files\Microsoft Shared\WebServer Extensions\14\TEMPLATE\LAYOUTS\ClientBin

The Microsoft.SharePoint.Client.xap contains copies of the Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll files. You need to add only a small amount of code to your Silverlight applications to dynamically load this application at runtime.

To convert your Silverlight Contacts application from using the statically referenced Client Object Model to the dynamic one

  1. Stop Visual Studio from embedding the Client Object Model assemblies. In the Solution Explorer, expand the References node and click the Microsoft.SharePoint.Client.Silverlight node. In the Properties window, change the Copy Local property to False. Do this also for the Microsoft.SharePoint.Client.Silverlight.Runtime node. This will stop Visual Studio from adding these files to your .xap package file. You still need to have a reference to these files for design-time support, such as IntelliSense, and compile support.

  2. Call a method to load assemblies at runtime. You could actually optimize this step based on your application needs, but at some point before you use them, you must load the assemblies from the SharePoint server. In this example, you replace the direct call to PopulateContacts with the call to load the Silverlight Client Object Model, first passing in the callback to the PopulateContacts method. Change the code in the ContactsViewModel constructor to look like the following code.

    if (!DesignerProperties.IsInDesignTool)
    {
      //PopulateContacts();
      LoadClientOM loadClientOM =
      new LoadClientOM(delegate() { PopulateContacts(); });
    }
    
  3. Create a class to dynamically load the Silverlight Client Object Model. You need to create a class called LoadClientOM. Right-click the Silverlight project, choose Add, choose Class, and then name the class LoadClientOM.cs. This class will be responsible for dynamically loading the Client Object Model. This code is generic and can be used in any of your Silverlight applications unchanged. You might consider refactoring this into a separate reusable assembly. To keep the example as simple as possible, just add a class file to your project. Add the following code to the LoadClientOM.cs file that you just created.

    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using System.IO;
    using System.Reflection;
    using System.Windows.Resources;
    
    namespace Contacts
    {
      public class LoadClientOM
      {
        private Action action;
    
        public LoadClientOM(Action action)
        {
          this.action = action;
          WebClient client = new WebClient();
          client.OpenReadCompleted +=
          new OpenReadCompletedEventHandler(ReadCompleted);
          client.OpenReadAsync
          (new Uri("/_layouts/clientbin/Microsoft.SharePoint.Client.xap",
    UriKind.Relative));
        }
    
        void ReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
          Stream assemblyStream;
          AssemblyPart assemblyPart;
    
          assemblyStream = Application.GetResourceStream(new
    StreamResourceInfo(e.Result, "application/binary"),
    new Uri("Microsoft.SharePoint.Client.Silverlight.Runtime.dll",
    UriKind.Relative)).Stream;
          assemblyPart = new AssemblyPart();
          Assembly b = assemblyPart.Load(assemblyStream);
    
          assemblyStream = Application.GetResourceStream(new
    StreamResourceInfo(e.Result, "application/binary"),
    new Uri("Microsoft.SharePoint.Client.Silverlight.dll", UriKind.Relative)).Stream;
          assemblyPart = new AssemblyPart();
          Assembly a = assemblyPart.Load(assemblyStream);
    
          //Call back on the passed delegate
          if (action != null)
          {
            action();
          }
        }
      }
    }
    

The LoadClientOM constructor takes one parameter, the callback method to call after the assemblies have been loaded. Next, the constructor uses the WebClient class to download the Microsoft.SharePoint.Client.xap asynchronously from the clientbin folder of the current site where the Silverlight application is running. Once the download is complete, the ReadCompleted method is called. The ReadCompleted method extracts and loads the assemblies from the Silverlight .xap package file. After the assemblies have been loaded, the callback action delete is called if specified. In this example, the callback method is the PopulateContacts method.

That is all you need to convert the application to dynamically load the Silverlight Client Object Model. You can run the project and see that the application does not look any different.

SharePoint 2010 Extensibility Projects

You have seen how to integrate and build a Silverlight Web part for SharePoint from beginning to end. Although doing so involves a number of steps, once you do it a couple of times and get your head around it, it's not too bad. But it would be better if there were an actual Silverlight project template to build a Silverlight Web part. Fortunately, Visual Studio is highly extensible, making it easy to build in functionality that may be missing. That is exactly what my team has done; we built a few new extensibility features into Visual Studio, including a Silverlight Web part. You can download the SharePoint 2010 Extensibility Project from MSDN Code Gallery. The project contains three templates: Silverlight and Sharepoint project template, Sharepoint ribbon project template, and OBA Deployment project template. You should look at the other templates, as well, but for now the one you should download is the Silverlight and SharePoint project template.

Installing the Visual Studio extension

Install the Silverlight Web part Visual Studio project template by running the Silverlight Web part .vsix file you downloaded from the MSDN Code Gallery. After installing the Silverlight extension, you can verify its installation by clicking Tools, and then Extension Manager from the main menu in Visual Studio. You can also disable or remove the extension from the Extension Manager dialog box, as shown in Figure 19.

Figure 19. Disabling or removing a Web part

Disabling or removing a Web part

Creating a Silverlight Web Part by Using a Visual Studio Extension Project

Once you have the Silverlight Web Part extension installed, creating a new Silverlight Web Part is as easy as creating any other Visual Studio project.

To create a Silverlight Web Part by using a Visual Studio extension project

  1. Open Visual Studio and open the New Project dialog box. Select the SharePoint-2010 node on the left. Scroll down and select the Silverlight Web Part template. This is a new project template that was added when you installed the extensibility project. Click OK to start the New Project Wizard.

  2. The first page of the New Project Wizard looks just like any SharePoint New Project Wizard. You must type the path for the SharePoint server. In this case, type http://intranet.contoso.com, and then click Next.

  3. Specify information about the project. On this page, you type the name to give to the Silverlight project and the title and description of the Web Part. You also specify where to deploy the Silverlight .xap file. In this example, I chose the Site Assets library as the deployment location, as shown in Figure 20. Type the values and click Finish to generate the project files.

    Figure 20. Specify configuration information in the wizard

    Specify configuration information in the wizard

When the wizard completes, it creates a solution with two projects, just as you did manually earlier in the chapter. Although it is beyond the scope of this chapter to go into detail about the implementation, there are a few things to point out. First, note that this Silverlight Web Part generates the Silverlight control from scratch and does not use the built-in Silverlight Web Part. So, examining the generated code is a good learning tool for creating more advanced Silverlight Web Parts. Second, the Silverlight project that the wizard generates contains code that uses the Silverlight Client Object Model to create a list of all the SharePoint lists. To enable this sample code, open the MainPage.xaml.cs file, press Ctrl+A to select all the code, and click the Uncomment button on the toolbar (or press Ctrl+K, U). The project is ready to run. Press F5 to run the project. Once the site opens, put the page in edit mode and insert a new Web Part. By default, the Web Part will be under the Custom category on the Web Part gallery dialog. Save the page and you will see a Silverlight application listing all the SharePoint lists with an item count, as shown in Figure 21.

Figure 21. Web part lists all SharePoint 2010 lists

Web part lists all SharePoint 2010 lists

The Silverlight VSIX extensibility project is a great learning tool for beginners to get up to speed quickly with building Silverlight applications for SharePoint. It also is a great tool for experts to rapidly develop Silverlight applications.

Summary

This chapter described how to build a simple Silverlight Web part for SharePoint and how to access SharePoint data using the Client Object Model. It's important to remember that with Silverlight development on SharePoint, you are solving two fundamental problems: how to get the Silverlight application into SharePoint, and how to host and display the Silverlight application. You saw that there are a number of ways to solve the first problem, from simply copying the .xap file to a document library to having it completely automated as part of your solution. You also learned that thereare a few ways to host Silverlight applications in SharePoint, from using the built-in Silverlight Web part to completely building your own Silverlight Web part. You also saw an example of how Visual Studio can be extended to make completing complex tasks easier, such as creating Silverlightsolutions.

A third problem to solve is how to interact with SharePoint and SharePoint data. You learned how to use the SharePoint Client Object Model to access SharePoint data. You also saw how you could optimize your Silverlight applications by dynamically loading the SharePoint Client Object Model.

There is so much to learn about SharePoint and Silverlight development, and this chapter covered only the most basic aspects to get you started and pointed in the right direction. With the incredibly fast pace of Silverlight innovations and the rapid adoption of Silverlight across the world, coupled with the power and depth of the SharePoint platform, Silverlight is the perfect technology for building rich collaborative business applications for the enterprise and the Internet.

About the Authors

  • Randy Drisgill is a consultant with SharePoint911. He is a Microsoft MVP for SharePoint Server and the coauthor of Professional SharePoint 2007 Design.

  • John Ross is a consultant with SharePoint911 and a Microsoft MVP. He is an active member of the SharePoint community and a frequent guest speaker.

  • Jacob J. Sanford is a senior consultant for Cornerstone Software Services.

  • Paul Stubbs works at Microsoft and is a frequent speaker at Tech Ed and Dev Connections events about branding and SharePoint.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.