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

12 comments:

Anonymous said...

Pretty nice post. I just stumbled upon your weblog and wished to say
that I have really enjoyed surfing around your blog posts.
In any case I will be subscribing to your rss feed and I hope
you write again soon!

Also visit my blog: Muscle building suplements

Anonymous said...

I am really grateful to the holder of this site
who has shared this enormous article at here.


Here is my web-site; Xtrasize

Anonymous said...

I'm very happy to uncover this web site. I wanted to thank you for ones time for this fantastic read!! I definitely appreciated every part of it and I have you book-marked to check out new stuff in your web site.

My website :: Slim Green Coffee Reviews

Anonymous said...

Heya i'm for the first time here. I found this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you helped me.

My blog - Buy Equinox

Anonymous said...

Hi there, I want to subscribe for this webpage to take latest
updates, therefore where can i do it please assist.

Feel free to visit my homepage; nuva genic review

Anonymous said...

Pretty nice post. I just stumbled upon your weblog and wished to say that I have
really enjoyed surfing around your blog posts. In any case I
will be subscribing to your rss feed and I hope you write again soon!


My web blog; Coffee PUre Cleanse Diet

Anonymous said...

Great article.

Here is my webpage: Buy Nutra Burn 10

Anonymous said...

Its like you read my mind! You appear to know a lot about
this, like you wrote the book in it or something.
I think that you could do with some pics to drive the message home
a little bit, but instead of that, this is great blog.
An excellent read. I will certainly be back.

My web page ... Max Robust

Anonymous said...

Write more, thats all I have to say. Literally, it seems
as though you relied on the video to make your point.
You obviously know what youre talking about, why waste your intelligence on just posting videos to
your blog when you could be giving us something enlightening to
read?

my blog muscle building

Anonymous said...

Hi Dear, are you truly visiting this website regularly, if so after that you will definitely take fastidious experience.


my web blog; no2 maximus review

Anonymous said...

You need to be a part of a contest for one of the finest websites on the net.
I'm going to highly recommend this blog!

my website; Nitric Oxide Supplements

Anonymous said...

e cigarettes, e cigarette forum, smokeless cigarettes, electronic cigarettes, electronic cigarettes, ecigs