Create Silverlight Graphs to use SharePoint 2010 Data
Prepare SharePoint to use Silverlight:
Need to put the following two files in the root of your SharePoint Web Application:
ClientAccessPolicy.xml
<?xml version="1.0" encoding="utf-8"?> <access-policy> <cross-domain-access> <policy> <allow-from http-request-headers="*"> <domain uri="*"/> </allow-from> <grant-to> <resource path="/" include-subpaths="true"/> </grant-to> </policy> </cross-domain-access> </access-policy>
CrossDomain.xml
<?xml version="1.0"?> <cross-domain-policy> <allow-http-request-headers-from domain="*" headers="*"/> </cross-domain-policy>
Create Silverlight in Visual Studio 2010:
- Open Visual Studio 2010 Select New Project…
- At top select .NET Framework 3.5 and Silverlight
- In Visual C# section Select Silverlight-> Silverlight Application
- Type in name of project. We will create a Pie chart first, so we will use Silverlight.PieCharts and press
- In New Silverlight Application Window, make sure Host the Silverlight application in new Web site is checked.
- Add SharePoint Silverlight client object model references
- In Solution Explorer, right-click the Silverlight.PieCharts node, and then click Add References.
- Click Browse tab.
- Navigate to the following folder: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin.
- Select Microsoft.SharePoint.ClientSilverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll
- Click OK
- Add Silverlight Charting object model references
- In Solution Explorer, right-click the Silverlight.PieCharts node, and then click Add References.
- Click .NET tab.
- Select System.Windows.Controls.DataVisualization.Toolkit
- Click OK
- Add References & Parameters passing to Silverlight
- Right-Click on App.xml
- Select View Code
- Add following using statements to top of page
using Microsoft.SharePoint.Client; using System.Threading;
- Find Application_Startup
- Change from:
private void Application_Startup(object sender, StartupEventArgs e) { this.RootVisual = new MainPage(); }
to:
private void Application_Startup(object sender, StartupEventArgs e) { ApplicationContext.Init(e.InitParams, SynchronizationContext.Current); this.RootVisual = new MainPage(e.InitParams); }
- Right-Click on MainPage.xml
- Select View Code
- Add following using statements to top of page
using Microsoft.SharePoint.Client;
- Find MainPage
- Change from:
public MainPage() { InitializeComponent(); }
to:
//Parameters private string _webFullURL = @"http://s22102:83//"; //url to your sharepoint site private string _Title = "Pie Chart"; private string _ListName = "Tasks"; //name of list on SharePoint Site //internal private ListItemCollection _listTasks; public MainPage(IDictionary<string, string> Parameters) { InitializeComponent(); #region Parameters if (Parameters.ContainsKey("WebURL")) { _webFullURL = Parameters["WebURL"].Replace("%20", " ").Replace("%28", "(").Replace("%29", ")"); } if (Parameters.ContainsKey("Title")) { _Title = Parameters["Title"].Replace("%20", " ").Replace("%28", "(").Replace("%29", ")"); } pieChart.Title = _Title; if (Parameters.ContainsKey("ListName")) { _ListName = Parameters["ListName"].Replace("%20", " ").Replace("%28", "(").Replace("%29", ")"); } #endregion GetData(); }
- Add Pie Chart container
- Open MainPage.asml
- Add reference to chart control
- in UserControl above d:DesignHeight= add following:
xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
- Add following inside grid section
<chartingToolkit:Chart x:Name="pieChart" Width="350" Height="250" Title="PieChart" BorderThickness="0" Background="White" VerticalAlignment="Top" HorizontalAlignment="Center"> <chartingToolkit:Chart.Series> <chartingToolkit:PieSeries ItemsSource="{Binding}" DependentValuePath="Value" IndependentValuePath="Key" AnimationSequence="FirstToLast" Title="Status" IsSelectionEnabled="True" /> </chartingToolkit:Chart.Series> </chartingToolkit:Chart>
- Add data to chart
- Add following two classes above MainPage class in MainPage.asml.cs:
public class SLGridData { public string Key { get; set; } public int Value { get; set; } } public class SPTasks { public string Title { get; set; } public DateTime StartDate { get; set; } public DateTime DueDate { get; set; } public string AssignedTo { get; set; } public string Status { get; set; } public double PercentComplete { get; set; } public string Priority { get; set; } }
- Now add folowing data functions after public MainPage(IDictionary<string, string> Parameters):
GetData():private void GetData() { ClientContext spContext = null; if (ApplicationContext.Current.Url != null) { spContext = new ClientContext(ApplicationContext.Current.Url); } if (spContext == null) { spContext = new ClientContext(_webFullURL); spContext.Load(spContext.Web); } List ProjectBooks = spContext.Web.Lists.GetByTitle(_ListName); spContext.Load(ProjectBooks); CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery(); string camlQueryXml = "<View>" + "<Query>" + "</Query>" + "<Where>" + "</Where>" + "<ViewFields>" + "<FieldRef Name='Title' />" + "<FieldRef Name='StartDate' />" + "<FieldRef Name='DueDate' />" + "<FieldRef Name='AssignedTo' />" + "<FieldRef Name='Status' />" + "<FieldRef Name='PercentComplete' />" + "<FieldRef Name='Priority' />" + "</ViewFields>" + "</View>"; query.ViewXml = camlQueryXml; _listTasks = ProjectBooks.GetItems(query); spContext.Load(_listTasks); spContext.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnRequestSucceeded), new ClientRequestFailedEventHandler(OnSiteLoadFailure)); }
OnRequestSucceeded():
private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args) { Dispatcher.BeginInvoke(BindData); }
OnSiteLoadFailure()
private void OnSiteLoadFailure(Object sender, ClientRequestFailedEventArgs args) { string msg = args.Exception.ToString(); }
BindData():
private void BindData() { List<SPTasks> tasks = new List<SPTasks>(); foreach (ListItem li in _listTasks) { tasks.Add(new SPTasks() { Title = Convert.ToString(li["Title"]), StartDate = li["StartDate"] != null ? Convert.ToDateTime(li["StartDate"]) : DateTime.MinValue, DueDate = li["DueDate"] != null ? Convert.ToDateTime(li["DueDate"]) : DateTime.MinValue, AssignedTo = li["AssignedTo"] != null ? Convert.ToString(li["AssignedTo"]) : string.Empty, Status = li["Status"] != null ? Convert.ToString(li["Status"]) : string.Empty, PercentComplete = li["PercentComplete"] != null ? Convert.ToDouble(li["PercentComplete"]) : 0.0, Priority = li["Priority"] != null ? Convert.ToString(li["Priority"]) : string.Empty }); } //Total by Status var grouped = tasks.GroupBy(p => new { p.Status }) .Select(p => new SLGridData() { Key = p.First().Status + " (" + p.Count() + ")", Value = p.Count(), }); List<SLGridData> listData = grouped.ToList(); //Bind to chart BindChart(listData); //Set Title pieChart.LegendTitle = _Title; }
BindChart()
private void BindChart(List<SLGridData> gridData) { List<KeyValuePair<string, int>> valueList = new List<KeyValuePair<string, int>>(); foreach (SLGridData pb in gridData) { valueList.Add(new KeyValuePair<string, int>(pb.Key, pb.Value)); } // Setting data for pie chart pieChart.DataContext = valueList; //Get Series }
- Press F5 to run
- Adding to SharePoint via Webpart
- Copy Silverlight.PieCharts\Silverlight.PieCharts\Bin\Debug\Silverlight.PieCharts.xap to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin
- Create a Visual WebPart project in the same solution called Silverlight.WebPart
- Copy contents (items between tags) of Silverlight.PieCharts.Web -> Silverlight.PieChartsTestPage.aspx into VisualWebPart1UserControl.ascx desinger page
- Change object section to this
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="_layouts/ClientBin/Silverlight.PieCharts.xap"/> <param name="onError" value="onSilverlightError" /> <param name="background" value="white" /> <param name="minRuntimeVersion" value="5.0.61118.0" /> <param name="autoUpgrade" value="true" /> <param name="initParams" value="WebURL=<%=WebUrl %>,ListName=<%=ListName %>,Title=Total Projects By Status"/> <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0" style="text-decoration:none"> <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/> </a> </object>
- Edit VisualWebPart1UserControl.ascx page
- Add following public objects before Page_Load
public string ListName = "Tasks"; public string WebUrl = "http://s22102:83/";
NOTE: You can create webpart parameters to this webpart and allow users to change the WebUrl and ListName
- Build and deploy to SharePoint
- Add your webpart to a page and see your chart!!
References: