Showing posts with label Chart. Show all posts
Showing posts with label Chart. Show all posts

Monday, 3 October 2011

Embedding Google charts into Sharepoint Web Parts

The other day I was developing a portal and at some point the “client” asked to provide a simple pie chart in the landing page. I said to him; “that should be ok”. At that point I was thinking obviously in the lovely Chart Web Part that comes from default in Sharepoint 2010. After talking with him for a while I realised that requirements where quite high, in terms of data collection. I want to clarify I am trying to avoid PerformancePoint Services because I don’t want to activate the service just for one chart.

Obviously I always have plan A,B,C,D…well sometimes I reach Z. I tried to play around a little bit with the Out Of The Box web part, unfortunately plan A was not good enough, I was looking for something sharp, something elegant, something independent from the whole system, and going for plan A should require to create few extra workflows.

Then I tried to create a Visual Webpart, thinking that the System.Web.UI chart control will work properly in Sharepoint 2010. Unfortunately, it didn’t. Big mistake in my side, I was playing with a .NET 4.0 control, obviously Sharepoint 2010 only support .NET 3.5, so I had to abort plan B.

I asked Trev, one of the web developers, and he suggested me Google Charts. In fact he said that they look much better than the .NET ones, because they use AJAX. I went to the Google Chart Tools website and I was amazed about what I saw. Google provides all the information about the API + all the code required, so with a copy paste you can get a nice example in five minutes.

What I did was to create a nice method where you can pass the parameters , build the JavaScript code and embedded into the Web Part. You can use, either a Web Part or a Visual Web Part. In my case I decided to use a Visual Web Part. There is not a particular reason for that.

I am going to do a Step by Step, so you know how to implement it. The result will be a simple pie chart (remember you can create something similar with another Google chart). I will post the project at the end of the article so you can implement it.

- Step 1
Go to Visual Studio 2010->New Project->Sharepoint->2010->Empty Project->call it CPDPointsWebPart and click OK. Select you want to deploy in your farm.

- Step 2
Go to the project, Right click and add->new item…->Sharepoint->2010->Visual Webpart and call it CPDWebPart.

- Step 3
Go to the Feature (Feature1)-> Right click and rename it to CPDWebPartFeature. Your solution should look like this now:
image

- Step 4
Go to CPDWebPartUserControl.ascx.cs, remove all the code and paste this one:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
namespace CPDPointsWebPart.CPDWebPart
{
    public partial class CPDWebPartUserControl : UserControl
    {       
        protected void Page_Load(object sender, EventArgs e)
        {
            
            Dictionary<string, int> _dValues = new Dictionary<string, int>();
            _dValues.Add("CPD Training done", 4);
            _dValues.Add("CPD Training Left to be done", 6);
            
            List<string> _lColumns = new List<string>();
            _lColumns.Add("CPD");
            _lColumns.Add("Hours");
            
            Page.RegisterClientScriptBlock("PieChart", GooglePieChart("CPD Points",_dValues,_lColumns,450,300));
        }        
        public string GooglePieChart(string _sTitle, Dictionary<string, int> _dChartParameters, List<string> _lColumns, int _iWidth, int _iHeight)
        {
            System.Text.StringBuilder _Chart = new System.Text.StringBuilder();
            _Chart.Append(@"<script type='text/javascript' src='https://www.google.com/jsapi'></script>");
            _Chart.Append(@"<script type='text/javascript'> ");
            _Chart.Append(@"google.load('visualization', '1', {packages:['corechart']}); ");
            _Chart.Append(@"google.setOnLoadCallback(drawChart);");
            _Chart.Append(@"function drawChart() {  ");
            _Chart.Append(@"var data = new google.visualization.DataTable();  ");
            _Chart.Append(@"data.addColumn('string', '" + _lColumns[0] + "');");
            _Chart.Append(@"data.addColumn('number', '" + _lColumns[1] + "');");
            _Chart.Append(@"data.addRows(" + _dChartParameters.Count.ToString()+ ");");
    
            int i=0;
            foreach (var item in _dChartParameters)
         {
          _Chart.Append(@"data.setValue("+i.ToString()+", 0, '"+item.Key+"'); ");
                _Chart.Append(@"data.setValue(" + i.ToString() + ", 1, " + item.Value+ "); ");   
                i++;
         }
            _Chart.Append(@"var chart = new google.visualization.PieChart(document.getElementById('chart_div'));");
            _Chart.Append(@"chart.draw(data, {width: " + _iWidth.ToString() + ", height: " + _iHeight.ToString() + ", title: '" + _sTitle + "'}); ");
            _Chart.Append(@"}");
            _Chart.Append(@"</script>");
            return _Chart.ToString();
        }
    }             
}


Notice I use Page.RegisterClientScriptBlock(…) to post the JavaScript code into the Visual Web Part.


- Step 5
Double click on CPDWebPartUserControl.ascx and copy and paste this code. The only line I am going to add is “<div id="chart_div"></div> “ . You can add this line from your code as well, but I think by doing it like this we can see the interaction between the JavaScript code and the ascx code.


- Step 6
Deploy the Visual Web Part, go to your site edit the page, insert the webpart (it will be under custom). This should be the result:
image


Conclusion: Google can provide a very good solution for your charts. There are more chart engines out there you can use, but I find Google the fastest one in terms of performance.


To download the code click in the image.
image