Friday, October 31, 2008

Silverlight 2 Charts : Building Charts using Silverlight 2 Toolkit

Another milestone in Silverlight journey, Release of excellent Toolkit for Silverlight on Codeplex, to know more about it, do visit at :

http://www.codeplex.com/Silverlight

There are few new controls added to the Silverlight Arena as :

    • AutoCompleteBox
    • ButtonSpinner
    • Chart
    • DockPanel
    • Expander
    • HeaderedItemControl
    • HeaderedContentControl
    • ImplicitStyleManager
    • Label
    • NumericUpDown
    • TreeView
    • ViewBox
    • WrapPanel
    I guess rest are very much easy and some are familiar to Web Developers which are relevent to some of the controls in AJAX Control Toolkit e.g AutoCompleteBox,NumericUpDown etc.
    Silverlight Toolkit which exclusively supports Silverlight 2 RTW and easily installable too, To download the bits, you need to visit :

http://www.codeplex.com/Silverlight/Release/ProjectReleases.aspx?ReleaseId=18804

I personally recommend to copy all the DLL files from the Toolkit to C:\Program Files\Microsoft Silverlight\2.0.31005.0\..

This will ease to add to project as reference,and it will be like central repository of all main dll files.This is just for convenience.

Step 1 : Install Silverlight Toolkit by adding reference to DLLs inside Toolkit.

Process is very similar the way we implement for AJAX Control Toolkit, Once you do that successfully, All the controls will be available on Toolbox.

Step 2 : Implement LINQ to SQL to get data for Graph.

Step 3 : Write a Silverlight Enabled WCF service to fetch data.

For Step 2 & 3 , kindly follow my old article step-by-step :

http://pendsevikram.blogspot.com/2008/10/silverlight-2-grid-with-silverlight.html

and

http://pendsevikram.blogspot.com/2008/10/silverlight-2-grid-linq-to-sql.html

Step 4 : Configure the Chart Control and Bind it with Data.

Here I am showing first demo of Pie Chart with List<> [Collection] and then I will show it with service.

XAML Code :

<Grid x:Name="LayoutRoot" Background="White">
        <StackPanel>
            <charting:Chart Height="250" Width="400" Title="PUG –Silverlight Forum Monthly Activity" x:Name="MyPieChart" >
                <charting:Chart.Series>
                    <charting:PieSeries ItemsSource="{Binding}"
                                        IndependentValueBinding="{Binding ProductName}"
                                        DependentValueBinding="{Binding Sales                    </charting:PieSeries>
                </charting:Chart.Series>
            </charting:Chart></StackPanel>
   </Grid>

C# Code :

public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Page_Loaded);
        }

        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            GetProductSales();
         }

        public void GetProductSales()
        {
            List<ProductSales> PieData = new List<ProductSales>();
            PieData.Add(new ProductSales() { ProductName = "Vikram Pendse", Sales = 10.5 });
            PieData.Add(new ProductSales() { ProductName = "Rashi Agarwal", Sales = 20.2 });
            PieData.Add(new ProductSales() { ProductName = "Prachi Oke", Sales = 30.2 });
            PieData.Add(new ProductSales() { ProductName = "Ekta Shetty", Sales = 40.1 });
            MyPieChart.DataContext = PieData;
            MyPieChart.LegendTitle = "User Activity on forums in %";
         }
    }

    public class ProductSales
    {
        public string ProductName { get; set; }
        public double Sales { get; set; }
    }

And output will be something like this :

SLPieUData

Next Step is to bind it with Service and this time I am using Bar charts along with Pie Chart.

XAML Code :

<Grid x:Name="LayoutRoot" Background="White">
        <StackPanel>
            <charting:Chart Height="250" Width="400" Title="ABC Ltd.- Q2 Business Development Report" x:Name="MyPieChart" >
                <charting:Chart.Series>
                   <charting:PieSeries ItemsSource="{Binding}"
                                        IndependentValueBinding="{Binding Salesperson}"
                                        DependentValueBinding="{Binding Percentage}" >
                    </charting:PieSeries>
                </charting:Chart.Series>
            </charting:Chart>
            <charting:Chart Height="250" Width="400" Title="ABC Ltd.- Q2 Business Development Report" x:Name="MyBarChart">
                <charting:Chart.Series>
                    <charting:ColumnSeries ItemsSource="{Binding}" Title="Sales"
                                        IndependentValueBinding="{Binding Salesperson}"
                                        DependentValueBinding="{Binding Percentage}" >
                    </charting:ColumnSeries>
                </charting:Chart.Series>
            </charting:Chart>
            </StackPanel>
    </Grid>

C# Code :

Service Code :

public class MySvc
    {
        [OperationContract]
        public List<MonthlySale> GetSalesData()
        {
            MyDatabaseDataContext db = new MyDatabaseDataContext();
            var temp = from sales in db.MonthlySales
                       where sales.Salesperson.Length > 0
                       select sales;
            return temp.ToList();
        }

    }

[Note : I have created a Table MonthlySales in Northwind Database for testing purpose.]

C# Code with Proxy of the Service after consumption :

public partial class Page : UserControl
   {
       public Page()
       {
           InitializeComponent();
           this.Loaded += new RoutedEventHandler(Page_Loaded);
       }

       void Page_Loaded(object sender, RoutedEventArgs e)
       {
           Proxy.MySvcClient svc = new Proxy.MySvcClient();
           svc.GetSalesDataCompleted += new EventHandler<SL_SilverlightToolkit.Proxy.GetSalesDataCompletedEventArgs>(svc_GetSalesDataCompleted);
           svc.GetSalesDataAsync();
       }

       void svc_GetSalesDataCompleted(object sender, SL_SilverlightToolkit.Proxy.GetSalesDataCompletedEventArgs e)
       {
           MyPieChart.DataContext = e.Result;
           MyPieChart.LegendTitle = "Business Generated in %";

           MyBarChart.DataContext = e.Result;
           MyBarChart.LegendTitle = "Business Generated in %";
       }

   }

And the result will look like :

SLFinalCharts

This is how we can implement Charts in Silverlight 2 using Silverlight Toolkit, Soon I will post more interesting demos in coming days with more and more controls and unique ideas, Hope this will help you to start doing development with Silverlight Toolkit.

Vikram.

3 comments:

Adi said...

Hi Vikram,

Which database you are using, since northwind database doesn't have Monthly sales table. Can you publish the database

Vikram Pendse said...

Hi Adi,

I have created it, I know its not built-in though, but code snippet should work for any of the table, let me know if its not, Thanks.

Vikram.

Mahesh said...

Hello,

My service results the following data:
ID Count Month
1 10 Jan
1 12 May
2 23 Jan
2 22 May
2 19 Jun

How can I create a Column chart in Silverlight, to show count on Y-axis, Month in X-axis and 2 columns for the 2 ids (2 legends). Any help will be greatly appreciated.

Thanks