Creating Silverlight Dashboards for SharePoint 2010 (Wrox)

Summary: Learn how to build Microsoft Silverlight dashboards in a Microsoft SharePoint Server 2010 environment.

Wrox logo

Wrox SharePoint Books

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

Author: Ryan Morgan

Editors: WROX Tech Editors for SharePoint 2010 Articles

Contents

  • Introduction to Creating Silverlight Dashboards

  • Overview of Data APIs Available to Silverlight in SharePoint 2010

  • All Silverlight Calls Are Made Within the Context of the Current User

  • Use LINQ Queries to Collect Data for the Dashboard

  • Deploying Silverlight in a SharePoint Site

  • Conclusion

  • About the Author

  • Additional Resources

Introduction to Creating Silverlight Dashboards

To help you understand how to build Microsoft Silverlight dashboards in a Microsoft SharePoint 2010 environment, this article uses a scenario. A marketing department in a fictitious company, Adventure Works, manages and provides assets through a SharePoint team site. The team decides to enhance the user experience by providing a rich user interface via Silverlight for browsing and for administrating approved graphical assets of their products. By using SharePoint workflows and a tasks list, marketing employees create requests for the assets from the graphic design team.

The tables that follow describe the lists and document libraries that are relevant to this article. The tables also define the fields and their types that correlate to the source code in this article.

Table 1 lists the Products Assets document library, which consists of a descriptive name for the assets, together with the legal and marketing approval dates for those assets. Table 2 lists the Product Lists and Table 3 details the Product Categories list. With these lists and data defined, the source code provided in this article works correctly against a SharePoint site.

When the graphic design team submits the asset, the contents are first reviewed by the marketing team, and then by the legal team before being made available to the broader company. A simple sequential workflow, built into Visual Studio, marks the asset as approved after the legal and marketing approval dates are set. The dashboard for the application has three charts: outstanding approvals by department, assets count by product, and the number of days that are required to approve an asset by department.

This article focuses on the fundamentals of using Silverlight in SharePoint 2010. Readers can build on the examples to develop scenarios that are specific to their business processes and reporting needs.

Table 1. Product Assets document library

Field

Use

Type

Title

Descriptive name for the asset

Single line of text

Product

Lookup field that associates a product from the Products list

Lookup (Products list)

LegalApprovalDate

Stores the date on which Legal approved the asset for use

Date and time

MarketingApprovalDate

Stores the date on which Marketing approved the asset for use

Date and time

Table 2. Products list

Field

Use

Type

Title

Descriptive name for the product

Single line of text

ProductNumber

Internal SKU for the product from Adventure Works Enterprise Resource Planning (ERP)

Single line of text

ProductCategory

Lookup field that associates a category from the Product Categories list

Lookup (Product Categories list)

ProductModel

The model description from Adventure Works ERP

Single line of text

Description

A short description of the product

Single line of text

Table 3. Product Categories list

Field

Use

Type

Title

Descriptive name for the category

Single line of text

Overview of Data APIs Available to Silverlight in SharePoint 2010

SharePoint 2010 has three APIs that Silverlight can use to access data: RESTful Services, client object model, and web services. Each of the three APIs has similar functionality with small variances. You should understand the differences between the APIs before you decide which API is appropriate for your project.

The RESTful Services API provides an ATOM XML or JSON (JavaScript Object Notation) view of list and library data. Although the REST API saves some of the manual coding that is required to build the classes for each list or library object, the API does not provide functionality to manage sites and webs. In addition, querying data can be much easier in this model because it is done using LINQ, but for large sets of data, the self-descriptive nature of the ATOM-format results adds too much overhead to maintain an acceptable level of performance.

The client object model provides an API that is similar to the server object model, and should feel familiar to developers who have traditional SharePoint development experience. The client object model API is powerful, but does require some SharePoint knowledge including an understanding of Collaborative Application Markup Language (CAML) to query data.

The web services API provides a backward-compatible SOAP API to manage SharePoint data and resources. The web services API is the only one that is backward-compatible with SharePoint 2007. However, to be proficient with this method, you must build more custom infrastructure to query with CAML and to connect to the services. Other articles in this series discuss the advantages and tradeoffs of each access method.

Table 4 summarizes some key distinguishing factors that you should consider when you determine the appropriate API for a project.

Table 4. Overview of SharePoint 2010 APIs for accessing data from Silverlight

API

Distinguishing Factors

RESTful ADO.NET Data Services

Strongly typed

Query with LINQ

List and library data only

Client object model

Weakly typed

Query with CAML

Update through objects

Similar programming model to server object model

Web Service

Weakly typed

CAML queries only

Backward compatible

Because creating a dashboard is a read-only view into list and library data, the RESTful API is the simplest way to query for the data that is required to display the dashboard metrics.

All Silverlight Calls Are Made Within the Context of the Current User

Users who view the Silverlight dashboard to see the current status of the approval process must have access to the lists in SharePoint because the Silverlight client queries those lists. (Even if the dashboard is on a page to which the user was granted access, Silverlight is client-based.) When those lists are queried through the remote API, the same security rules are enforced as those that apply when the user tries to browse those lists by using a browser. Unlike ASP.NET programming, the code that is written and compiled into the Silverlight application is not executed on the server. In code that uses the server object model or the remote APIs, all calls made to view or update data are made within the security context of the current user. Unlike server object model code, permissions cannot be elevated for an API call to view or update data within SharePoint. All three APIs respect the built-in security that is enforced throughout the SharePoint web and designer interfaces. It is important to understand that all calls are made under the auspices of the authenticated user when accessing data in SharePoint because the user must have permission for every site, list, or item that they intend to access through the API.

In addition to having access to the content that the caller is trying to access, the calling user must also be a member of a site group that has the Use Remote Interfaces permission (See Figure 1) because that permission controls the ability to access all three APIs. To view the setting, look in the Edit Permission Level interface for site groups in the site. By default, the permission is enabled for members of the Read site group and higher.

Figure 1. Use Remote Interfaces

Use Remote Interfaces

Use LINQ Queries to Collect Data for the Dashboard

This section shows how to start working with a Silverlight application to display SharePoint data by creating several simple queries that summarize data in a way that displays well in a dashboard chart.

The RESTful Services API is built on ADO.NET Data Services, which is a prerequisite installation for SharePoint 2010. Because the application under discussion has only one screen, the most basic Silverlight Application project is sufficient.

  1. Start Visual Studio.

  2. On the File menu, select New Project to open the New Project dialog box.

  3. Double-click Visual C#, and then select Silverlight.

  4. In the center pane, select Silverlight Application.

Now that you created the application, add a service reference to the application to create the proxy classes for the RESTful service API.

  1. Right-click the project.

  2. Select Add Service Reference.

  3. Type the URL for the RESTful service API.

    Note

    To access the service from a remote call, (for example, in a local development server or in the Add Reference dialog box), you must first enable remote calls for Silverlight. To enable remote calls, you must have a special formatted file called clientaccesspolicy.xml in the root of the site. For more information, see Client Access Policy Documentation.

    To find the location of the RESTful service, take the name of the site and add /_vti_bin/ListData.svc to the URL. For example, to reach a root site in a site collection with the URL sl2sp.local, use http://sl2sp.local/\_vti\_bin/ListData.svc. For this example, the SharePoint site that is used to build the application is ‘sl2sp.local’ and the name that was used to add the service reference was DashboardExampleDataService.

    Now that the service reference is part of the project, the DataContext class is available to write a query. Similar to a web service, adding a reference to the ListData.svc creates a local proxy (including generated .NET classes) as part of the project. Unlike web services, the proxy class includes .NET classes for all lists and document libraries, including all fields that are defined on the lists. To explore the classes created in the project, right-click the DashboardExampleDataService node of the ServiceReferences project icon, and then click View in Object Browser, as shown in Figure 2. All lists and document libraries in the site have the objects and properties automatically defined and can be queried by using the DashboardExampleDataContext object.

    Figure 2. View in Object Browser

    View in Object Browser

Now that the project is set up, writing queries to retrieve data is as simple as writing a LINQ query. In this example, a property is defined in the ViewModel called DashboardDataContext that is of type DashboardExampleDataContext, which was defined in the previous step. In the constructor for the ViewModel, the data context is initialized by using the following code.

DashboardDataContext = new DashboardExampleDataContext(new Uri("http://sl2sp.local/_vti_bin/listdata.svc/"));

The next code example has two methods. For brevity, error-handling and busy indicators are removed, and the URI to access the SharePoint services is hard coded. The first method, SelectApprovalStatusSummary, creates the query that is used to bind the chart. The first step is to clear the collection to which the chart is bound, and step two is to build the LINQ query that retrieves a set of ProductAssets. Finally, the query is initiated together with a callback method. Because all calls are made asynchronously in Silverlight, the second method serves to handle the callback from the asynchronous call. It is within the callback method that the code can begin to work with the queried data. In the callback method, the code uses LINQ to objects to group the results into a summary view of the data.

public void SelectApprovalStatusSummary()
{     
    // Clear the observable collection's contents.
    ProductApprovalCount.Clear();
 
    // Query the list of tasks where the status is not complete. 
    DataServiceQuery<ProductAssetsItem> qry = (from a in DashboardDataContext.ProductAssets select a) as DataServiceQuery<ProductAssetsItem>;
 
    // Set the method that will handle the asynchronous call to get data from 
    // the SharePoint API. 
    qry.BeginExecute(new AsyncCallback(SelectApprovalStatusSummaryComplete), qry);
}
 
public void SelectApprovalStatusSummaryComplete(IAsyncResult result)
{
    // Executes code on the UI thread to prevent cross-thread issues 
    // when changing properties that trigger Binding updates. 
    UIThreadDispatcher.BeginInvoke(() =>
        {
        // Receive the DataServiceQuery that was passed as a parameter to 
        // the asynchronous call. 
        DataServiceQuery<ProductAssetsItem> qry = (DataServiceQuery<ProductAssetsItem>)result.AsyncState;                    
                   
        // Finish executing the query to receive the results of the query. 
        var queryResults = qry.EndExecute(result);
 
        // Use LINQ to objects to group and summarize the results for 
        // consumption by the chart.
        ProductApprovalCount = new ObservableCollection<ProductMetricValuePair>(
         (from a in
        queryResults.Select((item) => new ProductAssetItemViewModel(item))
                    group a by a.ApprovalStatus into g
                    select new ProductMetricValuePair() { DisplayName = g.Key.ToString(), ValueCount = g.Count() }).ToList()
        );
        });
}

To roll up the status into a set of data that can be grouped, two objects are used. The ProductAssetItemViewModel object adds display functionality on the ProductAssetItem object. The specific property used, ApprovalStatus, is an Enum that allows for simple grouping based on whether the asset is waiting for approval from Legal, Marketing, whether it is complete, or whether it is not started. That Enum is used by the group by statement in the LINQ query. Finally, the grouped results are added to the Observable collection ProductApprovalCount to which the chart is bound in the XAML for the Silverlight control, as shown in the following example.

<chartingToolkit:Chart Title="Product Approval Status">
<chartingToolkit:Chart.Series>
<chartingToolkit:PieSeries ItemsSource="{Binding ProductApprovalCount}" 
                DependentValueBinding="{Binding ValueCount}"
                IndependentValueBinding="{Binding DisplayName}"/>
</chartingToolkit:Chart.Series>
</chartingToolkit:Chart>

Using the charts found in the Microsoft Silverlight Toolkit, the result is a professional chart that shows a pie chart of the breakdown of the approval status for the items in the Product Assets document library as in Figure 3.

Figure 3. Product Approval Status chart

Product Approval Status Chart

Deploying Silverlight in a SharePoint Site

After you debug the application in the local development environment, you are ready to add the Silverlight interface to a page on the SharePoint site. When a Silverlight application is compiled, the presentation and logic are compiled into a DLL or series of DLLs and packaged, along with the resources, into a special type of file called a XAP (pronounced "zap"). Because Visual Studio handles this packaging, the XAP file is built and ready to deploy when a developer runs the application to debug. Unlike traditional SharePoint programming that uses the server object model, packaging and deploying Silverlight applications does not require administrator access to SharePoint. Although the prescribed method to deploy an application is by packaging the content into a WSP file, you can build and deploy a Silverlight application as content. To deploy the XAP file, the compressed file must be uploaded into a document library and then added to a page. To package the XAP file for deployment on a SharePoint server, change the active solution configuration Debug to Release and then build the solution. Navigate to the folder where the Silverlight application is stored on the hard disk, and open the Bin folder. Inside of the Release folder is a XAP file that matches the name of the project, as shown in Figure 4. After you upload this file into the Site Assets document library, the application is ready to add to a SharePoint page.

Figure 4. Locate the XAP File in the Build Directory

Locate the XAP File in the Build Directory

SharePoint 2010 includes a new Silverlight Web Part. The default Web Part provides an easy way to include the XAP file built from a Silverlight project on a webpage by adding the Web Part and selecting the file to display. When you add a new Web Part, note that the Silverlight Web Part is in the Media and Content category. The Web Part, as shown in Figure 5, enables configuration of the area that contains the Silverlight application.

Figure 5. Configuring the Silverlight Web Part

Configuring the Silverlight Web Part

Conclusion

You can use Silverlight to build dashboard solutions for SharePoint 2010. Before you begin, you should have a basic understanding of the differences between the three APIs that provide data access to Silverlight applications, and know which API to use when, and why. The code example for this article includes two charts and queries, and shows how to use timeline graphs and how to use the Expand keyword to load related lists.

About the Author

Ryan Morgan is a managing partner and senior architect at Arrow Consulting & Design in West Palm Beach, Florida. At Arrow, Ryan focuses on large-scale business process automation and business intelligence in the areas of finance and master data management using SharePoint with Silverlight and ASP.NET. Ryan is an active member of the .NET and SharePoint community speaking at Code Camps, SharePoint Saturdays and at DevConnections in Las Vegas. Ryan co-wrote Professional DotNetNuke 5 for Wrox. Ryan’s company is on the web at www.ArrowDesigns.com and www.ArrowNuke.com.

The following were tech editors on Microsoft SharePoint 2010 articles from Wrox:

  • Matt Ranlett is a SQL Server MVP who has been a fixture of the Atlanta .NET developer community for many years. A founding member of the Atlanta Dot Net Regular Guys, Matt has formed and leads several area user groups. Despite spending dozens of hours after work on local and national community activities, such as the SharePoint 1, 2, 3! series, organizing three Atlanta Code Camps, working on the INETA board of directors as the vice president of technology, and appearing in several podcasts such as .Net Rocks and the ASP.NET Podcast, Matt recently found the time to get married to a wonderful woman named Kim, whom he helps to raise three monstrous dogs. Matt currently works as a senior consultant with Intellinet and is part of the team committed to helping people succeed by delivering innovative solutions that create business value.

  • Jake Dan Attis. When it comes to patterns, practices, and governance with respect to SharePoint development, look no further than Jake Dan Attis. A transplant to the Atlanta area from Moncton, Canada, Dan has a degree in Applied Mathematics, but is 100% hardcore SharePoint developer. You can usually find Dan attending, speaking at, and organizing community events in the Atlanta area, including code camps, SharePoint Saturday, and the Atlanta SharePoint User Group. When he's not working in Visual Studio, Dan enjoys spending time with his daughter Lily, watching hockey and football, and sampling beers of the world.

  • Kevin Dostalek has over 15 years of experience in the IT industry and over 10 years managing large IT projects and IT personnel. He has led projects for companies of all sizes and has participated in various roles including Developer, Architect, Business Analyst, Technical Lead, Development Manager, Project Manager, Program Manager, and Mentor/Coach. In addition to these roles, Kevin also managed a Solution Delivery department as a Vice President for a mid-sized MS Gold Partner from 2005 through 2008 and later also served as a Vice President of Innovation and Education. In early 2010 Kevin formed Kick Studios as a company providing consulting, development, and training services in the specialized areas of SharePoint and Social Computing. Since then he has also appeared as a speaker at numerous user group, summit, and conference type events across the country. You can find out more about Kevin on his blog, The Kickboard.

  • Larry Riemann has over 17 years of experience architecting and creating business applications for some of the world’s largest companies. Larry is an independent consultant who owns Indigo Integrations and does SharePoint consulting exclusively through SharePoint911. He is an author, writes articles for publication and occasionally speaks at conferences. For the last several years he has been focused on SharePoint, creating and extending functionality where SharePoint leaves off. In addition to working with SharePoint, Larry is an accomplished .Net Architect and has extensive expertise in systems integration, enterprise architecture and high availability solutions. You can find him on his blog.

  • Sundararajan Narasiman is a Technical Architect with Content Management & Portals Group of Cognizant Technology Solutions, Chennai, with more than 10 years of Industry Experience. Sundararajan is primarily into the Architecture & Technology Consulting on SharePoint 2010 Server stack and Mainstream .NET 3.5 developments. He has passion for programming and also has interest for Extreme Programming & TDD.

Additional Resources

For more information, see the following resources: