Click here to Skip to main content
15,881,139 members
Articles / Desktop Programming / XAML

Using Silverlight Chart Controls With SharePoint 2010

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
25 Nov 2010CPOL5 min read 31.4K   5   3
How to use Silverlight Chart Control with SharePoint 2010

In this blog post, I am going to explain how we can use Silverlight Chart Control with SharePoint 2010. OverallSharePoint 2010 supports full integration with Silverlight application either of Silverlight In Browser or as a Silverlight OOB (Out Of Browser) applications. In this blog post, I will be using one Share Point List to read the data using SharePoint Client Object Model (OM) and display it using Silverlight Chart Control inside SharePoint as a SharePoint Out of the box Silverlight Web Parts. This is also an example High Touch Integration of Silverlight and Share Point 2010.

If you want to know more about the different types of Integration between SharePoint 2010 and Silverlight, please read one of my previous articles:

In this post, I am not going to describe the step by step process of integration, this is just an example of High Touch Integration similar to the Silverlight Task Control. The only difference is that we will be using Silverlight Chart Control for Data Visualization.

To start with, first create a Share Point Custom List called “StudentInfo” with four different marks columns (Mathematics, Physics, Chemistry, Computer) and student name.

SPLists

Once you are done with the custom list creation, insert some dummy data into the “studentinfo” list as shown in the below image:

Fill Form

Below is shown a few sample data which are inserted using the above form.

List Of All Marks

We are now done with the SharePoint Part. Now we will be consuming the above list of data using SharePoint 2010 Client Object Model (OM) to display them as a Silverlight Chart and then will them as a SharePoint web parts.

To start with a New Silverlight Application, open Visual Studio IDE, create a New Silverlight Project named “SilverLightChartForSP”. Once you click on OK, the next screen will ask for creating a Silverlight Host application, click on OK.

Once you are done with the creation of your Silverlight application, the next task is to add the Reference of Client Object Model API. Right click on your Silverlight solution, select “Add Reference”.

addREf

and then, we need to select “Microsoft.SharePoint.Client.Silverlight.dll” and “Microsoft.SharePoint.Client.Silverlight.Runtime.dll” from the location “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin”.

adddlls

Let’s design a simple Silverlight UI. This UI will only have a Silverlight Data Grid and a Silverlight Column Chart Control. By default, Data Grid will show you the list of all student information and on click on Student records from data grid, the corresponding mark chart will be displayed. Below is the sample XAML code for the same:

XML
???<StackPanel>
    <Grid x:Name="LayoutRoot" 
    Background="White" Height="353" Width="529">
        <sdk:DataGrid  Height="186" 
        HorizontalAlignment="Left" 
		Margin="12,12,0,0" 
		Name="dataGrid1" VerticalAlignment="Top" 
		Width="453" 
		SelectionChanged="dataGrid1_SelectionChanged" />
        <chart:Chart Canvas.Top="1" 
        Canvas.Left="10" x:Name="mcChart" 
	Width="400" Height="250" 
	Background="LightSteelBlue" Margin="473,12,-344,91">
            <chart:Chart.Series>
                <chart:PieSeries Title="Marks" 
                AnimationSequence="Simultaneous" 
		IndependentValueBinding="{Binding Path=Key}" 
		DependentValueBinding="{Binding Path=Value}"></chart:PieSeries>
            </chart:Chart.Series>
        </chart:Chart>
    </Grid>
</StackPanel>

In code behind, we will actually use the SharePoint Client Object Model (OM) to read the data from the “StudenInfo” list. As we have already added the client object model references, now first we need to add the below namespaces.

namespaces

I have created one class called “Student” as shown below:

C#
public class Student
{
     public string Name { get; set; }
     public int Mathematics { get; set; }
     public int Physics { get; set; }
     public int Chemistry { get; set; }
     public int Computer { get; set; }
}

We will be using SharePoint Client Object Model to load the data into our Custom Student Object by a CAML query, then manipulate the data from the list and bind it to Silverlight Chart Control. Below is the complete code block for code behind.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
using System.Windows.Controls.DataVisualization.Charting;

namespace SilverLightChartForSP
{
    public partial class MainPage : UserControl
    {
        /// <summary>
        /// ShrePoint Site URL
        /// </summary>
        public string webFullURL = @"http://abhijjitjana:8888";

        /// <summary>
        /// Student List
        /// </summary>
        ///
        List stud = null;

        /// <summary>
        /// List Collections
        /// </summary>
        ListItemCollection lists = null;

        /// <summary>
        /// List of Students
        /// </summary>
        List<Student> students = new List<Student>();

        /// <summary>
        /// Update UI Method With Data
        /// </summary>
        private delegate void UpdateUIMethod(List<Student> studentList);

        /// <summary>
        /// Initializes a new instance of the <see cref="MainPage"/> class.
        /// </summary>
        public MainPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        /// <summary>
        /// Handles the Loaded event of the MainPage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        /// The <see cref="System.Windows.RoutedEventArgs"/> 
        /// instance containing the event data.</param>
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            ClientContext spContext = ClientContext.Current;
            if (spContext == null)
            {
                spContext = new ClientContext(webFullURL);
                spContext.Load(spContext.Web);
                stud = spContext.Web.Lists.GetByTitle("StudentInfo");
                spContext.Load(stud);
                CamlQuery query = new CamlQuery();
                string strQuery = @"<View>
                <ViewFields><FieldRef Name='AssignedTo'/>
		<FieldRef Name='Name'/><FieldRef Name='Mathematics'/> 
		<FieldRef Name='Physics'/><FieldRef Name='Chemistry'/>
		<FieldRef Name='Computer'/></ViewFields></View>";
                query.ViewXml = strQuery;
                lists = stud.GetItems(query);
                spContext.Load(lists);
                spContext.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
            }
        }

        /// <summary>
        /// Called when [site load success].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref=
		"Microsoft.SharePoint.Client.ClientRequestSucceededEventArgs"/> 
		instance containing the event data.</param>
        private void OnSiteLoadSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            foreach (ListItem item in lists)
            {
                Student student = new Student();
                student.Name = item["Name"].ToString();
                student.Mathematics = Int32.Parse(item["Mathematics"].ToString());
                student.Physics = Int32.Parse(item["Physics"].ToString());
                student.Chemistry = Int32.Parse(item["Chemistry"].ToString());
                student.Computer = Int32.Parse(item["Computer"].ToString());
                students.Add(student);
            }

            UpdateUIMethod up = new UpdateUIMethod(updateUI);
            this.Dispatcher.BeginInvoke(up, students);
        }

        /// <summary>
        /// Updates the UI.
        /// </summary>
        /// <param name="tasks">The tasks.</param>
        private void updateUI(List<Student> tasks)
        {
            dataGrid1.ItemsSource = tasks;
            dataGrid1.SelectionMode = DataGridSelectionMode.Single;
            if (tasks.Count >

We are now done with the implementation. But if you are trying to run the application now, you may get the exception for cross domain access as your SharePoint site hosted on IIS and you are running your application from VS. To resolve these issues, you have to place the clientAccessPolicy.xml file to root of your SharePoint Sites. If you press F5 to run the application, the below screen will appear.

SLHost

This is the Silverlight application which is hosted on an ASP.NET Web Application. Similarly, you can make it as Out of Browser (OOB) application by selection “Out – of - browsers Settings…” setting from the properties windows of your Silverlight application.

OOB

Once you done with the OOB Settings, if you run the application, it will look like a Windows application, refer to the below picture for the same:

OOBApps

Well, your Silverlight XAP files is already ready to use. Now, let’s put it as a SharePoint Web Parts.

First, create a SharePoint project and add a New SharePoint Module.

SPProj

A module contains files that are included in a SharePoint application when it is deployed. To add a module, right click on SharePoint Project and Click on Add New Item.

Module

Give the module name and click on “Add”. After that Right Click on the module and click on “Properties”. In the properties windows, “Select Project Output Reference” and do the setting as shown in the below picture.

ModuleSetup

Keep in mind that you need to select the Deployment Type as “ElementFile” and Project name should be the name of your “Silverlight Project”. Click on the OK. Now go to “Element.XML” File under the SharePoint Module. Verify the path for the Silverlight “.xap” File. You need to provide the same URL while you will add the Silverlight Web part inside SharePoint Site.

Now, set the Site Property URL in SharePoint Project and deploy the solution. Once you will get the VS statusbar “Deployed Successful”, you can go to your SharePoint Site and add the Silverlight Web Part in a page. Below is the Silverlight web parts integrated with SharePoint 2010.

Overall

Similarly, you can also use some other charts.

OverallPie

Regarding SharePoint project creation and hosting it on SharePoint site as web parts, I have highlighted only the few important steps here. For a detailed step by step guide, read the following article:

Summary

In this blog post, I have explained about using the Silverlight Chart Control with SharePoint 2010. I have used an SharePoint Custom list to read the list content using Client Object Model (OM) and displayed them as a Silverlight Chart. Finally, I have shown how we can place them inside SharePoint site with the help of SharePoint Out of the Box Silverlight Web Parts.

Hope this will help you.

Thanks !
Shout it

AJ

Filed under: Sharepoint 2010, Silverlight 4 Image 17 Image 18 Image 19 Image 20 Image 21 Image 22 Image 23 Image 24

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
.NET Consultant | Former Microsoft MVP - ASP.NET | CodeProject MVP, Mentor, Insiders| Technology Evangelist | Author | Speaker | Geek | Blogger | Husband

Blog : http://abhijitjana.net
Web Site : http://dailydotnettips.com
Twitter : @AbhijitJana
My Kinect Book : Kinect for Windows SDK Programming Guide

Comments and Discussions

 
GeneralXAML Pin
MJDamron22-Feb-11 8:02
MJDamron22-Feb-11 8:02 
GeneralMy vote of 5 Pin
Brij26-Nov-10 6:01
mentorBrij26-Nov-10 6:01 
GeneralMy vote of 5 Pin
Kunal Chowdhury «IN»26-Nov-10 1:12
professionalKunal Chowdhury «IN»26-Nov-10 1:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.