Using Silverlight Chart Controls With SharePoint 2010

In this blog post I am going to explain how we can use Silverlight Chart Control with SharePoint 2010. Overall SharePoint 2010 supports fully 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 them 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 article

Silverlight Task Control For SharePoint 2010 – Example of High Touch Integration

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 as 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 below image.

Fill Form

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

List Of All Marks

We are now done with the SharePoint Part. Now we will be consume 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, next screen will ask for creating a Silverlight Host application, Click on OK. 

Once you have done with 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 select  “Microsoft.SharePoint.Client.Silverlight.dll” and “Microsoft.SharePoint.Client.Silverlight.Runtime.dll” from the locationC:\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, corresponding marks chart will be displayed. Below is the sample XAML Code for the same.

        <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 be actually use the Share Point 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 below namespaces.

namespaces

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

    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 will manipulate the data from the list and will bind it to Silverlight Chart Control. Below is the complete Code Block for Code behind.

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 >= 0)
            {
                GetMarksSurce(0);
            }
        }

        /// <summary>
        /// Called when [site load failure].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Microsoft.SharePoint.Client.ClientRequestFailedEventArgs"/> instance containing the event data.</param>
        private void OnSiteLoadFailure(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
        }

        /// <summary>
        /// Handles the SelectionChanged event of the dataGrid1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>
        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetMarksSurce(dataGrid1.SelectedIndex);
        }

        /// <summary>
        /// Gets the marks surce.
        /// </summary>
        /// <param name="index">The index.</param>
        public void GetMarksSurce(int index)
        {
            mcChart.FlowDirection = System.Windows.FlowDirection.RightToLeft;
            ((PieSeries)mcChart.Series[0]).ItemsSource =
        new KeyValuePair<string, int>[]{
            new KeyValuePair<string, int>("Mathematics", students[index].Mathematics),
            new KeyValuePair<string, int>("Chemistry", students[index].Chemistry),
            new KeyValuePair<string, int>("Physics.", students[index].Physics),
            new KeyValuePair<string, int>("Computer", students[index].Computer),
};
       }
    }
}

 

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 you application from VS. To resolve this issues, you have to place the clientAccessPolicy.xml file to root of your SharePoint Sites. If you press F5 to run the application, below screen will appear.

SLHost

This is the Silverlight application which is hosted on a 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 will be look likes as a  windows application , refer 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 below picture.

ModuleSetup

Keep in mind, 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 used some other chartsl.

OverallPie

Regarding SharePoint project creation and Hosting it on SharePoint  site as web parts, I have highlighted only the few  importent steps here, For details step by step guide read below article.

Bing Maps Silverlight Control Integration with SharePoint 2010 – Integration of Silverlight 4 with SharePoint 2010

Summary : In this blog post I have explained about the using 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 placed 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

9 thoughts on “Using Silverlight Chart Controls With SharePoint 2010

  1. Nice blog and nice content. I found this site while I was searching a silverlight-sharepoint problem. I’m a silverlight developer and now there is a challange with connecting silverlight and sharepoint. When I try to use ClientContext, it’s always returns null. Is there any setting trick for connection? Because I did all what you said in your article above.
    Thanks

  2. Hi,

    I am trying to browse the silverlight application it says error at -1 at Microsoft.SharePoint.Client.ClientContext.OnGetResponse..

    How to resolve it..

    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s