Integrating Custom Silverlight Applications with SharePoint Server 2010

Summary:  Learn how to use the SharePoint Foundation 2010 managed client object model to work with managed Microsoft Visual C# code within the context of custom Silverlight 4 applications to consume and work with SharePoint list data.

Applies to: Business Connectivity Services | Office 2010 | Open XML | SharePoint | SharePoint Designer 2010 | SharePoint Foundation 2010 | SharePoint Online | SharePoint Server 2010 | Visual Studio

Provided by:  Casey Margell, FooBarbarians

Contents

  • Overview

  • Advantages to Developing with the SharePoint Foundation 2010 Managed Client Object Model

  • Common Integration Scenarios for Custom Silverlight Applications and SharePoint Server 2010

  • Scenario Overview: Combining Silverlight and SharePoint to Create a Dashboard

  • Creating the Incident Dashboard

    • Creating the Silverlight 4 Application by Using Visual Studio 2010

    • Adding References to the SharePoint Foundation 2010 Managed Client Object Model Assemblies

    • Adding a Using Statement to the Managed Client Object Model

    • Getting SharePoint List Data

    • Addressing Security and Cross-Domain Calls

    • Adding and Updating SharePoint List Data

  • Adding Support for Specific Silverlight 4 Features

    • Enabling Printing with Silverlight 4

    • Implementing Right-Click Support in Silverlight 4

    • Enabling Clipboard Operations in Silverlight 4

    • Creating Silverlight Web Parts in SharePoint Foundation 2010

  • Conclusion

  • Additional Resources

  • About the Author

Click to grab code  Download the sample code from MSDN Code Gallery

Overview

One of the advances made in Microsoft SharePoint Foundation 2010 is the introduction of the SharePoint Foundation 2010 Managed Client Object Model. The managed client object model provides a framework for accessing multiple SharePoint data sources from .NET Framework-based managed code and JavaScript/ECMAScript (JavaScript, JScript). Previously you had to use the Server API and test code directly on the server hosting the SharePoint Server installation. The managed client object model enables you to create applications that access and work with SharePoint data and perform configuration tasks without writing or installing code directly onto the server computer.

This article is part of a series of articles that describe how to integrate client applications together with business processes and workflows:

Advantages to Developing with the SharePoint Foundation 2010 Managed Client Object Model

The SharePoint Foundation 2010 managed client object model provides a client-side framework to work with the common objects in SharePoint Server sites. For more information, see Using the SharePoint Foundation 2010 Managed Client Object Model. Applications taking advantage of the managed client object model can perform operations similar to those supported by the server-side object model.

As SharePoint usage and functionality becomes more common and more needed within organizations, IT teams are often called to support SharePoint API functionality from outside SharePoint product and technologies deployments. Previously, this was accomplished by using SharePoint Server Web Services or, when those services did not provide the required functionality, a custom web service running alongside the SharePoint deployment that used the server-side object model. These services were non-trivial to create and maintaining the different endpoints and keeping definitions in sync often led to problems. Additionally deployment of server-side code can incur organizational resistance or be out of the question altogether. SharePoint Foundation 2010 provides a managed client object model with similar functionality to improve the flexibility of environments in which you can use SharePoint Server data and functionality and to simplify application development.

The managed client object model relieves the strain by providing a common framework for the .NET Framework-based applications. These applications do not rely on server-side code. Therefore, they are easier to set up, deploy, maintain, and to develop. Integrating the managed client object model into Silverlight applications is simple and predictable.

Common Integration Scenarios for Custom Silverlight Applications and SharePoint Server 2010

Some example scenarios include the following:

  1. Presenting content from internal SharePoint sites by using Silverlight on a public-facing site

  2. Building a Silverlight application that targets enterprises and uses SharePoint products and technologies for storage, authentication, and reporting

  3. Presenting list data within SharePoint sites dynamically by using Silverlight

These scenarios show some of the primary needs and capabilities that need to be addressed:

  • Access to SharePoint data and functionality

  • Authorization

  • Authentication

This article describes how to access and consume SharePoint data by working with SharePoint list data from a Silverlight 4 application.

Scenario Overview: Combining Silverlight and SharePoint to Create a Dashboard

In this scenario, Contoso Inc, an insurance company, uses Microsoft SharePoint Server 2010 to manage data and workflows. This scenario encapsulates the entire lifespan of a claim; from how the incident is reported to how the work is approved and completed. The workflow on the claim is managed within SharePoint Server 2010 and can easily be referred to when you have to check the status of a particular claim.

Contoso implemented an infrastructure using Microsoft SharePoint Server 2010 and Microsoft Office 2010 to facilitate and streamline the processing of incidents. This process involves multiple applications that are used internally and externally. They also use different technology from mobile clients to desktop computers. But they all have one thing in common: SharePoint Server 2010 and the SharePoint Foundation 2010 managed client object model.

In the scenario, we create a Silverlight dashboard for silverlightnv2customer service agents at Contoso to show how to feature SharePoint data by using Silverlight capabilities to provide a rich and responsive user experience.

Personas in the Silverlight Scenario

  • Don Funk, Driver (Car Accident Victim) a customer of Contoso, Inc.

  • April Regan, Customer Service Agent at Contoso, Inc.

  • Rob Young, Insurance Agent at Contoso, Inc.

  • Jeff Ford, Body Shop Manager and a partner with Contoso, Inc.

Flow of Events

Figure 1. Flow of events

Flow of events

A large thunderstorm moved through Don Funk’s neighborhood. The high winds knocked down a tree and it landed on Don’s car. Don takes pictures of the damage with his camera phone and sends his insurance company the pictures along with a report of the incident by using his mobile phone to submit his claim.

At the insurance company the submission is received and added to a task list. A customer service agent, April, receives notification, reviews the data to ensure all the required information is present, and passes the incident along to the customer’s agent, Rob Young.

A task is created for Rob Young to investigate the claim and either approve it or reject it. Rob Young reviews the incident report and then meets with Don to perform an inspection and get more information about the incident. He then concludes there is no fraud involved, approves the claim and submits a request for estimates on the repair. The task assigned to Rob is updated and the workflow assigns a new task to a repair shop manager Jeff Ford to submit a bid for the repair work.

When Jeff is notified that Contoso, Inc. has a new request for bid he accesses the Contoso, Inc. extranet and fills out a bid form. Jeff wins the bid for work and schedules a time with Don to perform the work on Don’s car.

Upon completing the repairs, Jeff bills Contoso.

Scenario Workflow Details

Our scenario workflow is kicked off by the submission of the incident by Don Funk through his mobile phone. Figure 2 shows the portion of the workflow that applies to this document.

Figure 2. Workflow Diagram

Workflow Diagram

When our scenario kicks off our customer, Don Funk, uses the mobile application to submit a claim and provide incident details. The mobile application communicates the incident details by using a Windows Communication Foundation (WCF) service that is running alongside the SharePoint Server 2010 installation. The service creates a list item in the Incidents list as shown in the following figure.

Figure 3. Incidents List

Incidents List

When an item is created in the Incidents list, SharePoint starts a custom workflow automatically. The workflow assigns a task to our customer service representative, April Regan. At this point an email message is sent to our customer service representative alerting her to the new task assigned to her and to our customer indicating that the incident was received and is being processed.

Figure 4. Incident Tasks List

Incident Tasks List

Upon receiving an email message notifying her of a new task associated with the claim, the customer service agent, April, uses the Incident Dashboard to review the claim and move it along the workflow.

Creating the Incident Dashboard

The Incident Dashboard (Figure 5) used by our scenario is a Silverlight 4 application created with Microsoft Visual Studio 2010 that uses the managed client object model. This dashboard shows the open claims and where each claim is within the workflow life cycle. This section describes how to create a Silverlight 4 application in Visual Studio 2010, add references to the managed client object model assemblies, and use the managed client object model to work with SharePoint data.

Figure 5. Incident Dashboard

Incident Dashboard

Creating the Silverlight 4 Application by Using Visual Studio 2010

To create Silverlight 4 applications in Visual Studio 2010, you must first install the Silverlight 4 Tools for Visual Studio 2010. To download these tools, see Microsoft Silverlight 4 Tools for Visual Studio 2010. After installing the Silverlight tools, create a project in Visual Studio 2010 using the Silverlight application template.

To create a Silverlight project in Visual Studio 2010 by using the Silverlight application template

  1. Start Microsoft Visual Studio 2010.

  2. On the File menu point to New, and then click Project.

  3. In the New Project dialog, expand the Visual C# node under Installed Templates, and then select Silverlight.

  4. In the center pane that lists project types, select Silverlight Application as shown in the following figure.

    Figure 6. Silverlight Application Template in Visual Studio 2010

    Silverlight Application Template

  5. In the Name text box, type a project name, such as Contoso.IncidentDashboard.

  6. In the Location text box, type the path of the location where you can store the solution files.

  7. Press OK.

After you provide a project name and location, Visual Studio prompts you to add a website project to the solution and the target Silverlight version as shown in the following figure. In the scenario, we add a website project targeted to Silverlight 4 as shown in the following figure.

Figure 7. Creating the web site project and targeting the Silverlight version in Visual Studio 2010

Creating the web site project

Adding References to the SharePoint Foundation 2010 Managed Client Object Model Assemblies

Next, you must add references in the project to the managed client object model to use the functionality. The two assemblies, Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll are located in the following directory on the computer that is running SharePoint Foundation 2010:

%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\ISAPI

To add references to the managed client object model assemblies in Visual Studio 2010

  1. Right-click the Contoso.IncidentDashboard project.

  2. Select Add Reference.

  3. Click Browse.

  4. Browse to the location of the Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime assemblies.

  5. Select the two assemblies

  6. Press OK.

After adding the required reference, the project looks like the following figure.

Figure 8. Silverlight application with references to the client object model assemblies in Visual Studio 2010

Silverlight application with references

Adding a Using Statement to the Managed Client Object Model

The next step is to add a Using statement at the top of the .cs file. Working with the managed client object model resembles working with the server-side object model. For those with experience working with the server-side object model, the objects and methods of working with those objects are logical and easy to work with.

To add a Using statement to the managed client object model

  1. Open MainPage.xaml.cs

  2. Add the following Using statement after the existing ones.

    using Microsoft.SharePoint.Client;
    

Setting up the references and the using statements provides access to the objects that are defined in the Microsoft.SharePoint.Client assembly.

Getting SharePoint List Data

[Microsoft.SharePoint.Client.ClientContext] object and [Microsoft.SharePoint.Client.Web] object comprise the core of the managed client object model. Without these objects, none of the other operations can function. You should use object-level variables to persist the objects across asynchronous calls throughout the application execution.

Important

You should avoid the use of multiple ClientContext objects as some client-side objects, such as ListItemCollection objects, are specific to a particular ClientContext object. Attempting to use an object with a different ClientContext object other than the one responsible for creation of that object can lead to problems.

To retrieve list data by using variables

  1. Add the following properties to the object after the class definition:

            private ClientContext _context = null;
            private Web _site = null;
            private ListItemCollection _incidentListItems = null;
    

    The three member variables in the previous example are a ClientContext object that refers to the SharePoint site to operate against, a Web object that represents a SharePoint site, and a ListItemCollection object to use to retrieve items in a SharePoint list by using the managed client object model. An event handler for the Loaded event on the MainPage object is used to initialize the member variables after the MainPage object and its children initialize:

  2. Inside of the MainPage constructor, add the following code after the method.

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
    
  3. After the MainPage constructor, add the following method.

            void MainPage_Loaded(object sender, RoutedEventArgs e)
            {
                _context = new ClientContext("http://intranet.contoso.com");
                _site = _context.Web;
    
                List list = _site.Lists.GetByTitle("Incidents");
                CamlQuery query = new CamlQuery();
                query.ViewXml =
                    @"<View>
                        <Query>
                            <Where>
                                <Neq>
                                    <FieldRef Name='Status' />
                                    <Value Type='Choice'>Closed</Value>
                                </Neq>
                            <Where>
                        <Query>
                    </View>";
    
                _incidentListItems = list.GetItems(query);
                _context.Load(_incidents);
                _context.ExecuteQueryAsync(
                    onGetIncidentsSucceeded, 
                    onGetIncidentsFailed
                    );
            }
    

    This code initializes the ClientContext object, passing it the URL of the site to reference. Next, the Web object is retrieved from the ClientContext object. Both are stored in member variables to maintain the reference to them.

This procedure shows the pattern to follow when you are working with the managed client object model from Silverlight.

  • Set a reference to the logical object to work with.

  • Set up the action to perform.

  • Execute the action, providing callback methods for both success and failure.

Following this pattern, the previous example performs the following steps:

  • Sets a reference to the Incidents list

  • Creates a [Microsoft.SharePoint.Client.CamlQuery] object and set its query. In this scenario, that means getting incident list items that do not have a status of Closed.

  • Calls the [Microsoft.SharePoint.Client.List.GetItems] method and stores the result in the ListItemCollection member variable. The [Microsoft.SharePoint.Client.CamlQuery] object is provided to the [Microsoft.SharePoint.Client.List.GetItems] method. This defines the results expected by our Get operation.

Asynchronous operations were mentioned briefly previously. Now review what they are and why they are important. When working in Silverlight, you must not lock the user interface while waiting for the query to return results. When waiting for an asynchronous operation to complete, it is important to give visual feedback to the user that something is occurring and that the user interface does not lock up. If nothing changes in the user interface, then the user has no indication that anything is occurring in the back-end. Calling the [Microsoft.SharePoint.Client.ClientRunTimeContext.ExecuteQueryAsync] method provides event handlers to indicate operation success and failure.

As shown in Creating the Silverlight 4 Application by Using Visual Studio 2010, when getting the list of incident items, the dashboard must indicate how many claims fall into each claim category. It must also indicate incident items that fall into particular categories in the list. Now is a good time to call out one of the implications of performing an asynchronous operation. Callbacks for asynchronous operations do not run on the same thread as that of the user interface. Therefore, an attempt to modify the user interface from inside that callback results in an exception. To ease this, you can use a custom delegate and an additional method as shown in the following example. Add the following code after the MainPage_Loaded method.

        private void onGetIncidentsSucceeded(
            object sender, 
            ClientRequestSucceededEventArgs args
            )
        {
            UpdateIncidentsSummary();
        }

        private delegate void UpdateIncidentsSummaryDelegate();
        private void UpdateIncidentsSummary()
        {
            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.BeginInvoke(
                    new UpdateIncidentsSummaryDelegate(UpdateIncidentsSummary)
                    );
                return;
            }

            int newIncidents = 0;
            //... Additional counter variables

            foreach (ListItem listItem in _incidentListItems)
            {
                string status = (string)listItem["Status"];

                switch (status)
                {
                    case "New":
                        newIncidents++;
                        break;
                    //... Additional cases for the different statuses
                }
            }

            this.txtNewIncidentCount.Text = newIncidents.ToString();
            //... Set Additional Count display controls
        }

Walking through this example, the onGetIncidentsSucceeded method calls the UpdateIncidentsSummary method. The UpdateIncidentSummary method checks whether it has user interface access by using the Dispatcher.CheckAccess method. If it does not, then it creates a delegate back to the UpdateIncidentSummary method that executes on the user interface thread.

This check occurs for each status update. After the process is complete, the user interface updates to reflect the current counts.

Now let's review the failure handler.

Add the following block of code after the UpdateIncidentSummary method.

     private void onGetIncidentsFailed(
            object sender, 
            ClientRequestFailedEventArgs args
            )
        {
            Alert("An Error Occurred Retreiving Incidents. Please refresh the page and try again:\n\n" + args.Exception);
        }

        private delegate void AlertDelegate(string message);
        private void Alert(string message)
        {
            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.BeginInvoke(new AlertDelegate(Alert), message);
                return;
            }
            MessageBox.Show(message);
        }

Walking through this example briefly, the general pattern is the same. The handler makes a call to a method that checks for user interface access. If it does not have access, it invokes a custom delegate on the user interface thread. One thing to call out is that the ClientRequestFailedEventArgs object has an Exception property. This contains an exception that was encountered and is very useful for tracking down the reason that the exception occurred.

If you are following along in your own project, press F5 to start debugging and you will see an error as shown in the following figure.

Figure 9. Security exception encountered when updating the incident summary

Figure 9

This exception occurred because the debug location on a different domain than the SharePoint site. Visual Studio 2010 automatically assigns a port to the instance of the server development computer that is running ASP.NET it spawns to support debugging. The next section describes how to mitigate this.

Addressing Security and Cross-Domain Calls

Accessing a resource in one domain from a separate domain and the security implications of doing so is known as cross-domain calls. In our case we want to make a cross-domain call to our target SharePoint instance from our debug environment. The way to address this issue is by using a cross-domain access policy file.

Cross-domain access policies address security issues associated with allowing access across domains. Cross domain access policies are configured by using an XML file called clientaccesspolicy.xml. This file is stored in the root of the virtual directory hosting the site. For example, in this scenario, I stored the file in the following location:

C:\InetPub\wwwroot\wss\VirtualDirectories\80\

The following code example is a very simple client access policy file.

<?xml version="1.0" encoding="utf-8" ?> 
<access-policy> 
    <cross-domain-access> 
        <policy> 
            <allow-from> 
                <domain uri="*"/> 
            </allow-from> 
            <grant-to> 
                <resource include-subpaths="true" path="/"/> 
            </grant-to> 
        </policy> 
    </cross-domain-access> 
</access-policy>

Stepping through this xml file, there is a policy set up that allows requests from all domains and grants permission to all resources on the site. While this wide-open access policy is not recommended for a production environment, it can be useful for development. Note that Administrator access to the server computer that is running SharePoint Foundation 2010 is required to follow these steps.

To create a client access policy file for the development environment

  1. Create a text file that is named clientaccesspolicy.xml.

  2. Add the previous xml code to the file.

  3. Save your changes and close the file.

  4. Copy this file to the root of the web application.

    Figure 10. ClientAccessPolicy.xml

    ClientAccessPolicy.xml

    After saving this file in the appropriate location, restart Microsoft Internet Information Services (IIS).

  5. Press Start.

  6. On the start menu, expand All Programs, and expand the Accessories folder.

  7. Right-click Command Prompt and then click Run As Administrator.

  8. Type iisreset and then press Enter as shown in the following figure.

    Figure 11. Restarting the site

    Restarting the site

After creating the client access policy file and restarting IIS, you should be able to debug through the application without error.

Adding and Updating SharePoint List Data

Now let's touch briefly on adding and updating list items. Note that the example does not show the success callback and failure callback because examples are provided earlier in the article. Adding an item is not complex as shown in the following example.

        List incidents = _site.Lists.GetByTitle("Incidents");

        ListItemCreationInformation listingListItemCreation = 
            new ListItemCreationInformation();
        ListItem item = incidents.AddItem(listingListItemCreation);
        item["Title"] = (string) . . .
        . . .
        item.Update();
        
        _context.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);

The example adheres to the pattern discussed earlier (get the object that you want to work on, set up the action, execute). This example performs the following actions:

  • Get the list to which to adding an item.

  • Set up a ListItemCreationInformation object and use it to create a ListItem object in the list. After creating the ListItem object, set the field values.

  • Execute the query.

Updating item creation follows the same pattern introduced previously. For the sake of simplicity, assume that the previous code retrieved items from the Incidents list (storing the results in _incidentListItems). The following code example updates the status of items in the list to show status Closed.

        foreach (ListItem incident in _incidents)
        {
            incident["Status"] = "Closed";
            incident.Update();
        }

        _context.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);

As these examples demonstrate, the managed client object model simplifies the development process and helps by providing additional support for developing rich user experiences that use the Silverlight framework.

Adding Support for Specific Silverlight 4 Features

Now that we provided general data access to the customer service dashboard in our scenario, the next step is to add support for specific Silverlight 4 features. The next sections add support for printing, right-click, and the clipboard. There are other features as well. For more information about Silverlight capabilities, see Silverlight.NET website.

Enabling Printing with Silverlight 4

Silverlight 4 introduces a printing API that you can use to enable printing within your applications. Previous versions of Silverlight lacked that support and so required considerable work to ease that lack of flexibility. The Silverlight 4 print support is easy to use and very flexible.

To enable printing, you want to use the PrintDocument object. The following example shows how to use the PrintDocument object to print.

To implement the Silverlight 4 PrintDocument object

  1. Add a button control to your MainPage.xaml as follows.

                <Button x:Name="bttnPrint" Content="Print" Click="bttnPrint_Click" />
    
  2. Add the following event handler to MainPage.xaml.cs after the Alert method.

            private void bttnPrint_Click(object sender, RoutedEventArgs e)
            {
                PrintDocument printDoc = new PrintDocument();
                printDoc.PrintPage += (s, args) =>
                {
                    args.PageVisual = LayoutRoot;
                };
    
                printDoc.Print();
            }
    

The key parts of this example to call out here are as follows:

  • Creates the PrintDocument object.

  • Adds an event handler (in this case an anonymous method) that sets up the PrintPageEventArgs object according to what and how we want to print.

  • Calls the Print method of the PrintDocument object.

Alternately, you can create a custom print layout that does not match the default visual layout of the Silverlight application. In the case of our scenario, suppose that the items from the Incident list are stored in a list of a custom type.

            private List<Incident> _incidents = new List<Incident>();

In the PrintPage event handler, you can use the list as the ItemSource object for a Silverlight DataGrid object. You can provide the DataGrid object as the PageVisual object to the PrintPageEventArgs object in the PrintPage event handler as shown in the following code example.

            printDoc.PrintPage += (s, args) =>
            {
                DataGrid dataGrid = new DataGrid();
                dataGrid.ItemsSource = _incidents;
                dataGrid.AutoGenerateColumns = true;
                
                args.PageVisual = dataGrid;
            };

The following figure shows the results if you test the code by printing to Microsoft OneNote 2010.

Figure 12. Testing the print results of the data grid view in OneNote

Testing print results

Implementing Right-Click Support in Silverlight 4

Silverlight 4 offers the ability to override right-click button events. In previous versions, right-clicking resulted in a built in menu appearing as shown in the following figure.

Figure 13. Default Silverlight right-click menu

Default right-click menu

The ability to override this menu and provide custom events provides additional opportunities for customizing user interfaces and adding functionality.

At a high level to implement right-click events you must:

  • Define a canvas that contains a popup control that contain the content to display for right mouse button events.

  • Define the response to the appropriate mouse events to control visibility and placement of the popup.

The following procedure walks through this process.

To add custom right-click events to a Silverlight application

  1. First, add a canvas that contains a popup control to the MainPage.xaml.cs file after the LayoutRoot control as shown in the following example.

            <Canvas x:Name="pnlPop" 
                    Background="Transparent" 
                    Visibility="Collapsed">
                <Popup x:Name="popMenu" IsOpen="False">
                    <Border Background="LightGray" 
                            CornerRadius="5">
                        <StackPanel Margin="5">
                            <Button Content="Escalate to Supervisor" />
                            <Button Content="Email Customer" />
                        </StackPanel>
                    </Border>
                </Popup>
            </Canvas>
    

    This XML markup defines controls that visually consist of a border with rounded corners that contains two buttons.

  2. Next, add event handlers for the MouseRightButtonDown event, MouseRightButtonUp event, and MouseLeftButtonDown event to the parent control as shown in the following example.

        <Grid x:Name="LayoutRoot" 
              Background="White" 
              MouseRightButtonDown="LayoutRoot_MouseRightButtonDown" 
              MouseRightButtonUp="LayoutRoot_MouseRightButtonUp" 
              MouseLeftButtonDown="LayoutRoot_MouseLeftButtonDown">
    
  3. Add the handler for the MouseRightButtonDown event to MainPage.xaml.cs:

            private void LayoutRoot_MouseRightButtonDown(
                object sender, MouseButtonEventArgs e)
            {
                e.Handled = true;
            }
    

    Important

    The event handler in the previous code example is required despite the fact that it appears to not be doing very much. If your control does not handle the MouseRightButtonDown event, the Silverlight core does not raise the MouseRightButtonUp event for your application.

  4. Add the following MouseLeftButtonDown event handler to MainPage.xaml.cs.

            private void LayoutRoot_MouseLeftButtonDown(
                object sender, MouseButtonEventArgs e)
            {
                this.pnlPop.Visibility = System.Windows.Visibility.Collapsed;
                this.popMenu.IsOpen = false;
            }
    

This code example sets the canvas visibility to collapsed and then set the IsOpen property of our popup to false so that both are hidden. Now, when the user clicks elsewhere within the application, the popup is hidden.

Figure 14. Popup visibility on right click.

Popup visibility on right-click

Enabling Clipboard Operations in Silverlight 4

Clipboard access is new in Silverlight 4. Accessing the clipboard in Silverlight 4 uses the static methods of the Clipboard object. Clipboard support is text only. Use the GetText method and SetText method to get or set the text. This is particularly useful to enable the user to copy fixed text. In the scenario, you add Clipboard support for an Incident listing using the following code.

            Clipboard.SetText(incident.Customer + " - " +
                incident.Agent + " - " + 
                incident.Status);

Note that when your Silverlight 4 application attempts to access the clipboard by using the Clipboard object, the user receives a prompt to allow access to the clipboard. This is a security prompt to prevent malicious use of the clipboard.

Creating Silverlight Web Parts in SharePoint Foundation 2010

Now we have a fully-featured Silverlight 4 application that pulls data from a SharePoint list by using the managed client object model. The final step is to deploy it to the SharePoint site. To do this, you use the default Silverlight Web Part. Previously, deploying Silverlight applications to SharePoint sites required writing and maintaining custom Web Parts that consumed the Silverlight applications. The Silverlight Web Part included in SharePoint Foundation 2010 greatly reduces the amount of custom code associated with deploying Silverlight applications to SharePoint sites.

You must host the Silverlight .xap file in a location that is accessible to the server computer that is running SharePoint 2010. In this scenario, the file is stored in a document library. The following procedure walks through the process.

To deploy the Silverlight application to a SharePoint 2010 site

  1. Navigate to the SharePoint site where you want to host the Silverlight application.

  2. Click Site Actions. In the list, click More Options.

  3. In the Create window, under Page, click New Web Part Page.

  4. After you create the page, on the page, where you want to add the Silverlight Web Part, click Add a Web Part as shown in the following figure.

    Figure 15. Adding a Web Part to the SharePoint Web Parts page

    Adding a Web Part

  5. Under Categories, click the Media and Content category, and then click the Silverlight Web Part.

  6. In the Add Web Part to list, choose the location on the page and then click Add as shown in the following figure.

    Figure 16. Adding a Web Part

    Adding a Web Part

  7. In the dialog, type the path to the Silverlight .xap file and then click OK.

    Figure 17. Typing the path to the Silverlight .xap file

    Typing the path

    After you add the Silverlight Web Part, edit the properties to suit your needs.

  8. Click the down arrow in the heading of the Silverlight Web Part and select Edit Web Part to open the Properties pane as shown in the following figure.

    Figure 18. Editing the Silverlight Web Part on the SharePoint Web Parts Page

    Editing the Silverlight Web Part

  9. Modify the properties as needed and then press OK.

    Figure 19. Configuring the Silverlight Web Part properties

    Configuring the Silverlight Web Part properties

The Silverlight application should appear on the SharePoint Web Parts page as shown in the following figure.

Figure 20. Silverlight application in a Web Part on the SharePoint Web Parts page

Silverlight application in a Web Part

Conclusion

This article demonstrates the value of the SharePoint Foundation 2010 managed client object model towards adding significant flexibility and functionality. The managed client object model simplifies consuming SharePoint data and working with SharePoint functionality. Combined with the power of Silverlight 4 and its ability to present rich interfaces and dynamic user experiences, there are tremendous possibilities for maximizing the features of SharePoint and Silverlight together. To summarize, this article provides a model for using the managed client object model by providing examples of how to create, add, and edit SharePoint list items. After that it described how to use features that were introduced in Silverlight 4: printing, right-click support, and clipboard access. Finally, it walked through how to deploy the Silverlight applications by using the new Silverlight Web Part in SharePoint Foundation 2010. These additions represent significant new potential opportunities for using SharePoint Foundation 2010 in new and more flexible ways without the overhead previously involved in developing client applications for SharePoint products and technologies.

Additional Resources

About the Author

Casey Margell has been developing custom software for almost a decade spanning a variety of technologies. Most recently he is focusing on Silverlight and SharePoint and integrating various technologies and systems. Casey holds a Bachelor's degree in Computing and Software Systems from the University of Washington, Bothell Campus.