Showing posts with label SharePoint Web Part. Show all posts
Showing posts with label SharePoint Web Part. Show all posts

Friday, November 13, 2009

SharePoint charting (Chart inside web part)


In my article on "SharePoint Web Part Development Tutorial" I discussed how we can develop and deploy custom SharePoint web part with visual designing. Now let’s see how we can add a chart for that web part. Finally you will be getting a result like following picture.



To create the above chart I’m getting data from a SharePoint list as follow.



You can see I’m showing the chart inside my custom web part called "My first custom Web Part". There I used the code from "Free Google Chart SharePoint Web Part" and customized it as I want. These are the steps to add nice chart to your web part for free.

First Create your custom web part, don’t deploy at this stage.

Then add a Class called “Chart.cs” and replace the code using following code.

View Code

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.SharePoint;

namespace ProjectView{
public class Chart{

protected string _BGColor = "FFFFFF";
protected string _ChartColor = "0099ff,ff0000";
protected int _ChartHeight = 400;
protected LegendPositions _ChartLegend;
protected string _ChartTitle = "Burn Down Chart";
protected ChartTypes _ChartType;
protected int _ChartWidth = 720;
protected string _DataField = "Planned Effort,Actual Effort";
protected string _LabelField = "Title";
protected string _ListName = "";
protected string _SiteName = "http://merdev-moss:5050/";
protected string _ViewName = "";

public enum ChartTypes{
Line,
VerticalBar,
Pie,
Pie3D,
HorizontalBar
}
public enum LegendPositions{
horizontal_top,
vertical_left,
horizontal_bottom,
vertical_top,
vertical_bottom,
vertical_right
}
public string createChartString(string listName){
_ListName = listName;

string str = "";
string str2 = "";

SPSite site = new SPSite(this._SiteName);
SPWeb web = site.OpenWeb();
try{
if (!string.IsNullOrEmpty(this._ListName)){
SPList list = null;
SPListItemCollection items = null;
try{
string[] strArray3;
int num5;
list = web.Lists[this._ListName];
if (!string.IsNullOrEmpty(this._ViewName)){
SPView view = list.Views[this._ViewName];
items = list.GetItems(view);
}
else{
items = list.Items;
}
string str3 = "";
float num2 = 0f;
int num3 = 0;
bool flag = true;
char[] separator = new char[] { ',', ';' };
string[] strArray = this._DataField.Split(separator);
string[] strArray2 = new string[strArray.Length];
foreach (string str4 in strArray){
str2 = str2 + "<br>Series=" + str4;
if (!list.Fields.ContainsField(str4)){
str = str + "<p>Data List column not specified or not found:" + str4 + "</p>";
flag = false;
}
}
if (!list.Fields.ContainsField(this._LabelField)){
str = str + "<p>Label List column not specified or not found:" + this._LabelField + "</p>";
flag = false;
}
if (!flag){
goto Label_0868;
}
foreach (SPListItem item in items){
num3++;
try{
int index = 0;
foreach (string str5 in strArray){
string[] strArray7;
IntPtr ptr2;
float num = Convert.ToSingle(item[str5]);
if (num > num2){
num2 = num;
}
if (!string.IsNullOrEmpty(strArray2[index])){
string[] strArray6;
IntPtr ptr;
(strArray6 = strArray2)[(int)(ptr = (IntPtr)index)] = strArray6[(int)ptr] + ",";
}
string str6 = num.ToString().Replace(",", ".");
(strArray7 = strArray2)[(int)(ptr2 = (IntPtr)index)] = strArray7[(int)ptr2] + str6;
index++;
}
}
catch{
str = str + "<p>Data column error:" + this._DataField + "</p>";
}
try{
if (str3 != ""){
str3 = str3 + "|";
}
if ((this._LabelField != "LinkTitle") && (item.Fields[this._LabelField].FieldValueType == typeof(DateTime))){
str3 = str3 + ((DateTime)item[this._LabelField]).ToString("MMM yyyy");
}
else if (item[this._LabelField] != null){
str3 = str3 + item[this._LabelField].ToString();
}
continue;
}
catch{
str = str + "<p>Label column error:" + this._LabelField + "</p>";
continue;
}
}
string str7 = "";
string str8 = "";
string str9 = "";
string str10 = "";
string str11 = "";
string str12 = "";
string str13 = "";
if (!string.IsNullOrEmpty(str3)){
str3 = str3.Replace("&", "%26");
}
string str14 = num2.ToString().Replace(",", ".");
switch (this._ChartType){
case ChartTypes.Pie:
str7 = "p";
str9 = str3;
str12 = "0," + str14;
goto Label_051D;

case ChartTypes.Pie3D:
str7 = "p3";
str9 = str3;
str12 = "0," + str14;
goto Label_051D;

case ChartTypes.Line:
str7 = "lc";
str8 = "x,y";
str10 = "0:|" + str3;
str11 = "1,0," + str14;
str12 = "0," + str14;
goto Label_051D;

case ChartTypes.VerticalBar:
str7 = "bvg";
str8 = "x,y";
str10 = "0:|" + str3;
str11 = "1,0," + str14;
str12 = "0," + str14;
str13 = "a";
goto Label_051D;

case ChartTypes.HorizontalBar:
str7 = "bhg";
str8 = "x,y";
strArray3 = str3.Split(new char[] { '|' });
str3 = "";
num5 = strArray3.Length - 1;
goto Label_04DE;

default:
str7 = "p";
goto Label_051D;
}
Label_04AE:
if (str3 != ""){
str3 = str3 + "|";
}
str3 = str3 + strArray3[num5];
num5--;
Label_04DE:
if (num5 >= 0){
goto Label_04AE;
}
str10 = "1:|" + str3;
str11 = "0,0," + str14;
str12 = "0," + str14;
str13 = "a";
Label_051D:
if (str == ""){
object obj2 = str;
str = string.Concat(new object[] { obj2, "?chs=", this._ChartWidth, "x", this._ChartHeight });
if (!string.IsNullOrEmpty(this._ChartTitle)){
string str15 = this._ChartTitle.Replace(" ", "+");
str = str + "&chtt=" + str15.Replace("&", "%26");
}
str = (str + "&cht=" + str7) + "&chts=000000,17" + "&chd=t:";
int num6 = 0;
string[] strArray8 = strArray;
for (int i = 0; i < strArray8.Length; i++){
string text1 = strArray8[i];
if (num6 > 0){
str = str + "|";
}
str = str + strArray2[num6];
num6++;
}
str = str + "&chf=bg,s," + this._BGColor;
if (this._ChartColor != ""){
str = str + "&chco=" + this._ChartColor;
}
if (str9 != ""){
str = str + "&chl=" + str9;
}
if (str8 != ""){
str = str + "&chxt=" + str8;
}
if (str10 != ""){
str = str + "&chxl=" + str10;
}
if (str11 != ""){
str = str + "&chxr=" + str11;
}
if (str12 != ""){
str = str + "&chds=" + str12;
}
if (str13 != ""){
str = str + "&chbh=" + str13;
}
str = str + "&chg=" + ((100.0 / ((double)num3))).ToString("F") + ",20";
if (strArray.Length > 1){
str = str + "&chdl=";
int num7 = 0;
foreach (string str16 in strArray){
if (num7 > 0){
str = str + "|";
}
str = str + str16;
num7++;
}
str = str + "&chdlp=";
switch (this._ChartLegend){
case LegendPositions.horizontal_top:
str = str + "t";
break;

case LegendPositions.horizontal_bottom:
str = str + "b";
break;

case LegendPositions.vertical_top:
str = str + "tv";
break;

case LegendPositions.vertical_bottom:
str = str + "bv";
break;

case LegendPositions.vertical_left:
str = str + "l";
break;

case LegendPositions.vertical_right:
str = str + "r";
break;
}
}
str2 = str2 + "<br>" + str.Replace("&", "<br>&");
str = "http://chart.apis.google.com/chart" + str;
}
}
catch{
str = this._ListName + ": Sharepoint List not found!";
}
}
else{
str = "No Sharepoint List defined!";
}
}
catch (Exception){
str = "<br>Site not found:" + this._SiteName;
}
Label_0868:
return str;
}
}
}

Now change the variable names according to your site, list and columns.

Then Add this line to your .ascx file.

Now replace your "Page_Load" method as follows.

Now you can built and deploy your web part to see the result. You can get VerticalBar,Pie,Pie3D and HorizontalBar charts by changing the "ChartType" in the above code.

Wednesday, September 30, 2009

SharePoint Web Part Development Tutorial

It is hard to find out simple way to create SharePoint web parts with visual designing. After looking at custom features, in this article I'm going to show you how to create custom SharePoint web part using Web User Control in Visual Studio.

Creating the Web Part

First Create New Project called "ProjectView" and select ASP.NET Web Application (Figure 1 & 2). Don’t use shortcuts.


Then Add new Web User Control called "ProjectViewControl" to your project (Figure 3 & 4).


Then Add reference to the “Microsoft.SharePoint.dll”. It can be found in your sharepoint server’s ISAPI folder (Figure 5 & 6).


You should copy this file along with “Microsoft.SharePoint.Search.dll” and “Microsoft.SharePoint.Search.xml” from the same directory to a directory on your local computer if you are developing your project on a machine not having SharePoint or MOSS.

Then go to your SharePoint site’s folder (You can find it in SharePoint server) and create a folder called “usercontroles” if does not exist (Figure 7).

Find your site’s “Web.config” file within the same folder and open it (Figure 7).

Then add new Class called “WebControl.cs” which inherits from “WebPart” Class to your project (Figure 8) and paste this code there.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace ProjectView
{
    public class WebControl : WebPart
    {
        protected string UserControlPath = @"~/usercontrols/";
        protected string UserControlName = @"ProjectViewControl.ascx";

        private ProjectViewControl mycontrol;
        private string exceptions = "";

        protected override void CreateChildControls()
        {
            try
            {
                mycontrol = (ProjectViewControl)this.Page.LoadControl(UserControlPath + UserControlName);
                Controls.Add(mycontrol);
            }
            catch (Exception CreateChildControls_Exception)
            {
                exceptions += "CreateChildControls_Exception: " + CreateChildControls_Exception.Message;
            }
            finally
            {
                base.CreateChildControls();
            }
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            try
            {
                base.RenderContents(writer);
            }
            catch (Exception RenderContents_Exception)
            {
                exceptions += "RenderContents_Exception: " + RenderContents_Exception.Message;
            }
            finally
            {
                if (exceptions.Length > 0)
                {
                    writer.WriteLine(exceptions);
                }
            }
        }
    }
}

There don’t forget to add following two lines to the top, now your “WebControl.cs” Class should like above.

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

Then drag and drop a text box and two buttons to ProjectViewControl.ascx. Double click those buttons to add custom code (Figure 9 & 10).


Signing your web part project

To deploy this Web Part and Web User Control to GAC and the Microsoft Office SharePoint Server, we should assign a Strong Name key and sign the control.

To do this, right click the “ProjectView” node in Solution Explorer and select Properties. Then select the Signing tab from the choices on the left. Check the "Sign the assembly" box and select from the "Choose a strong name key file" drop down list (Figure 11).

There give a key file name and click ok. Now you can build your project and ready to deploy.

Deploying the Web Part and Web User Control

Here is deploying steps;

1. Copy the "ProjectViewControl.ascx" file to the created usercontroles folder (Figure 7).

2. Drag and drop the compiled DLL (You can find it in your project folder's bin folder) into the Global Assembly Cache. The Global Assembly Cache is a special folder located at %WINDIR%\assembly where %WINDIR% is the full path to your Windows folder (e.g. C:\Windows or C:\Winnt).

3. Get the publicKeyToken property of our assembly. You can find it by right click on the file and select properties in "assembly" folder (Figure 12).

4. Update the "Web.config file"

4.1 Insert these three lines between <SafeControls> and </SafeControls> tags.

<SafeControl Assembly="ProjectView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a73871474819663" Namespace="ProjectView" TypeName="WebControl" Safe="True" />
<SafeControl Assembly="ProjectView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a73871474819663" Namespace="ProjectView" TypeName="ProjectViewControl" Safe="True" />
<SafeControl Assembly="ProjectView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a73871474819663" Namespace="ProjectView" TypeName="*" Safe="True" />

4.2 Insert this line between <assemblies> and </assemblies> tags.

<add assembly="ProjectView, Version=1.0.0.0, Culture=neutral,PublicKeyToken=9a73871474819663" />

5. Insert new XML file called "myprojectview.webpart" (Figure 13) and paste this code.

<?xml version="1.0" encoding="utf-8" ?>
<webParts>
    <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
        <metaData>
            <type name="ProjectView.WebControl, ProjectView, Version=1.0.0.0,Culture=neutral,PublicKeyToken=9a73871474819663" />
            <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
        </metaData>
        <data>
            <properties>
                <property name="Title" type="string">My first custom Web Part</property>
                <property name="Description" type="string">
                    webpart created by using web user controles
                </property>
                <property name="ChromeType">TitleOnly</property>
                <property name="ChromeState">Normal</property>
                <property name="ItemLimit" type="int">15</property>
                <property name="ItemStyle" type="string">Default</property>
            </properties>
        </data>
    </webPart>
</webParts>

6. Upload the "myprojectview.webpart" file to Share Point's Web Part gallery. (You should have permission to see the Site Action tab and upload) (Figure 14, 15, 17, 18 & 19)





Use your Web Part

To use your Web Part in a page, follow these steps;

1. Edit a SharePoint page (Figure 19, 20 & 21)

2. Select a zone into which you want to place your Web Part

3. Add the Web Part to the zone

4. Exit from the Edit mode



Remember that you cannot copy DLL from MyDocument folder. So first copy the DLL to some location in SharePoint Server and then drag and drop it into assembly folder.

If you are interested you can try SharePoint charting (Chart inside web part) to see how you can add nice chart inside to this web part. Also try custom features.