Sunday, 3 June 2012

Silverlight Graph using SharePoint List 2010

Assuming SharePoint Site(http://sp2010:22913/sites/sc2/) has following List called  "Programming-Languages"(as shown below)



Step1) Create Silverlight project using .Net 3.5 (GRAPHDEMO)

Step 2)  Add Sharepoint Silverlight dll reference
             Located in 
             %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS\ClientBin 

            1)Microsoft.SharePoint.Client.Silverlight.dll 
            2) Microsoft.SharePoint.Client.Silverlight.Runtime.dll 


Step 3)  Add reference System.Windows.Controls.DataVisualization.Toolkit.


Step 4)  Add another namespace in MainPage.xaml for charting
           xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"


Step 5) Drap & drop  Chart Control into MainPage.xaml



        <chartingToolkit:Chart  x:Name="Chart1" HorizontalAlignment="Left" Margin="10,10,0,0"  Title="Programming Language Usage" VerticalAlignment="Top" Height="225" Width="390">
            <chartingToolkit:ColumnSeries DependentValuePath="Usage"  ItemsSource="{Binding}"
                                          IndependentValuePath="Name" 
                                           AnimationSequence="FirstToLast"
                                            IsSelectionEnabled="True"
                                          >
            </chartingToolkit:ColumnSeries>
        </chartingToolkit:Chart>

Step 6) Add new class ProgramUsage.cs
  it has 2 properties , 1 for Programming Language 2 for Usage
public class ProgramUsage
    {
        public string Name { get; set; }
        public int Usage { get; set; } 
    }

Step 7)    Add following varibles to  MainPage.xaml.cs

        ClientContext ctx = null; //sharepoint client context
        Web web = null;  //web
        List list = null;  //list refernce
        ListItemCollection allItems = null; //lits item collection
        List<ProgramUsage> pUsage= new List<ProgramUsage>(); //list of items parsed added to List of ProgramUsage 


in the constrcutor  ad\fter InitializeComponent() add this
this.Loaded += new RoutedEventHandler(MainPage_Loaded);

Add MainPage_Loaded method and try to get   list asynchronously

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                ctx = new ClientContext("http://sp2010:22913/sites/sc2/");//ApplicationContext.Current.Url);
               // ClientContext.Current;
                
                web = ctx.Web;
                
                ctx.Load(web);
               // ctx.ExecuteQuery();

                list = web.Lists.GetByTitle("Programming-Languages");
                CamlQuery query = CamlQuery.CreateAllItemsQuery();
                allItems
                  = list.GetItems(query);
                ctx.Load(allItems);

                ctx.ExecuteQueryAsync(successEventHandler, FailedEventHandler);
            }
            catch (Exception ex)
            {
                label1.Content = ex.Message;
            }
        }

//Add success,failed delagates methods

        void successEventHandler(object sender, ClientRequestSucceededEventArgs args)
        {
            //Bind datagrid asynchronously with delegate
            Action a = new Action(UpdateGrid);
            this.Dispatcher.BeginInvoke(a);
        }

     //Update chart with delegate/ashynchronously
        void UpdateGrid()
        {
            try
            {
                foreach (ListItem item in allItems)
                {
                    ProgramUsage ProgramL =
                        new ProgramUsage
                        {
                            Name = item["Title"].ToString(),
                            Usage = (item["Usage"] != null) ? System.Convert.ToInt16(item["Usage"]) : 0
                        };
                    
                    pUsage.Add(ProgramL);

                }

                Chart1.DataContext = pUsage;
            }
            catch (Exception ex)
            {
                label1.Content = ex.Message;
                
            }
        }
        void FailedEventHandler(object sender, ClientRequestFailedEventArgs args)
        {
            label1.Content = args.Message;
        }

Step 8)  BUILD THE PROJECT  GRAPHDEMO.XAP FILE WILL BE GENERATED.

STEP 9)  DEPLOY SILVERLIGHT .XAP FILE IN SHAREPOINT
               Upload generated .xap file into document library .
 in this example: http://sp2010:22913/sites/sc2/doclib/GRAPHDEMO.XAP
            GRAPHDEMO.XAP  uploaded to doclib --> document library.

STEP 10)  Create a Web page IN SHAREPOINT SITE,   insert Silverlight Web part
              note: Silverlight Web part located in   "Media & Content"-->Silverlight Web part.


STEP 11)   In Silverlight webpart, it asks for .xap file path
                  give same path  in Step 9)

Step 12)  OUTPUT


complete  MainPage.xaml code 

<UserControl x:Class="SilverlightApplication4.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
    mc:Ignorable="d"
    d:DesignHeight="400" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">


    <Grid x:Name="LayoutRoot" Background="White" Height="346" Width="400">
        <chartingToolkit:Chart  x:Name="Chart1" HorizontalAlignment="Left" Margin="10,10,0,0"  Title="Programming Language Usage" VerticalAlignment="Top" Height="225" Width="390">
            <chartingToolkit:ColumnSeries DependentValuePath="Usage"  ItemsSource="{Binding}"
                                          IndependentValuePath="Name" 
                                           AnimationSequence="FirstToLast"
                                            IsSelectionEnabled="True"
                                          >
            </chartingToolkit:ColumnSeries>
        </chartingToolkit:Chart>
        <sdk:Label  Height="47"   HorizontalAlignment="Left" Margin="0,241,0,0" Name="label1" VerticalAlignment="Top" Width="388" />
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="0,302,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</UserControl>


complete MainPage.xaml.cs code
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;
namespace SilverlightApplication4
{
    public partial class MainPage : UserControl
    {
        ClientContext ctx = null;
        Web web = null;
        List list = null;
        ListItemCollection allItems = null;
        List<ProgramUsage> pUsage= new List<ProgramUsage>();
        public MainPage()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                ctx = new ClientContext("http://sp2010:22913/sites/sc2/");//ApplicationContext.Current.Url);
               // ClientContext.Current;
                
                web = ctx.Web;
                
                ctx.Load(web);
               // ctx.ExecuteQuery();

                list = web.Lists.GetByTitle("Programming-Languages");
                CamlQuery query = CamlQuery.CreateAllItemsQuery();
                allItems
                  = list.GetItems(query);
                ctx.Load(allItems);

                ctx.ExecuteQueryAsync(successEventHandler, FailedEventHandler);
            }
            catch (Exception ex)
            {
                label1.Content = ex.Message;
            }
        }

        //On success this method gets executed.

        void successEventHandler(object sender, ClientRequestSucceededEventArgs args)
        {
            //Bind datagrid asynchronously with delegate
            Action a = new Action(UpdateGrid);
            this.Dispatcher.BeginInvoke(a);
        }

        void UpdateGrid()
        {
            try
            {
                foreach (ListItem item in allItems)
                {
                    ProgramUsage ProgramL =
                        new ProgramUsage
                        {
                            Name = item["Title"].ToString(),
                            Usage = (item["Usage"] != null) ? System.Convert.ToInt16(item["Usage"]) : 0
                        };
                    
                    pUsage.Add(ProgramL);

                }

                Chart1.DataContext = pUsage;
            }
            catch (Exception ex)
            {
                label1.Content = ex.Message;
                
            }
        }
        void FailedEventHandler(object sender, ClientRequestFailedEventArgs args)
        {
            label1.Content = args.Message;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
           // MessageBox.Show(web.Context.Url);
            //MessageBox.Show(label1.Content.ToString());
            if (list != null)
            {
                MessageBox.Show("title" + list.Title + list.ItemCount.ToString());
                MessageBox.Show("fields" + list.Fields.Count().ToString());
            }
            else MessageBox.Show("list is null");
        }
    }
}

ProgramUsage.cs

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication4
{
    public class ProgramUsage
    {
        public string Name { get; set; }
        public int Usage { get; set; } 
    }
}

No comments:

Post a Comment