Consuming Silverlight Data in SharePoint 2010

Accessing SharePoint data in Silverlight involves using the SharePoint client side object model. The following DLLs represent the APIs for accessing SharePoint data in Silverlight:

• Microsoft.SharePoint.Client.Silverlight.dll

• Microsoft.SharePoint.Client.Silverlight.Runtime.dll

In this section you create a Silverlight web part that displays data from a list in a grid. It will show data from a custom list called Books. The user can filter the data according to the book category, which he can select from a drop-down list.

Create a new custom list and call it Books. Add the custom columns listed in Table 9.2.

Table 9.2. Columns for Books List

Image

Create a new Silverlight project named ListDataSLApp.

Add a reference to the Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll from the <14 Hive>TemplatesLayoutsClientBin folder.

Edit the MainPage.xaml as follows:

<UserControl x:Class="ListDataSLApp.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"
    mc:Ignorable="d"
    d:DesignHeight="350" d:DesignWidth="550" xmlns:dataInput="clr-namespace: System.Windows.Controls;assembly=System.Windows.Controls.Data.Input" xmlns: data="clr-namespace:System.Windows.Controls;assembly= System.Windows.Controls.Data">
    <Grid x:Name="LayoutRoot" Background="White" Height="350" Width="550">
        <Grid.RowDefinitions>
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <dataInput:Label Height="20" HorizontalAlignment="Left" Margin="10,10,0,0" Name="label1" VerticalAlignment="Top" Width="200" Content="Select the Category" />
        <ComboBox Grid.Row="1" Height="20" HorizontalAlignment="Left" Margin="10,10,0,0" Name="ComboCategory" VerticalAlignment="Top" Width="211" SelectionChanged="ComboCategory_SelectionChanged" />
        <data:DataGrid AutoGenerateColumns="False" Grid.Row="2" Height="200" HorizontalAlignment="Left" Margin="10,10,10,10" Name="dataGrid1" VerticalAlignment="Top" Width="525" >
            <data:DataGrid.Columns>
                <data:DataGridTextColumn Header="Title" Binding="{Binding BookTitle}" />
                <data:DataGridTextColumn Header="Author" Binding="{Binding Author}" />
                <data:DataGridTextColumn Header="Publisher" Binding="{Binding Publisher}" />
                <data:DataGridTextColumn Header="Year" Binding="{Binding Year}" />
            </data:DataGrid.Columns>
        </data:DataGrid>
    </Grid>
</UserControl>

The preceding code defines a drop-down list and a data grid. It also specifies the handler for a drop-down list selection changed event. In addition the example defines the columns and binds to the data grid.

Open the MainPage.xaml.cs and update as shown in the following 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;
using System.Collections.ObjectModel;

namespace ListDataSLApp
{
    public partial class MainPage : UserControl
    {
        ClientContext ctx = null;
        IEnumerable<ListItem> categoryItems = null;
        IEnumerable<ListItem> filteredItems = null;

        public MainPage()
        {
            InitializeComponent();
            using (ctx = ClientContext.Current)
            {
                CamlQuery camlQuery = new CamlQuery();

                var query = from item in ctx.Web.Lists.GetByTitle("Books").GetItems(camlQuery)
                            select item;

                categoryItems = ctx.LoadQuery(query);

                ctx.ExecuteQueryAsync(categorySucceededCallBack, categoryFailedCallback);
            }
        }

        void categorySucceededCallBack(object sender, ClientRequestSucceededEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                List<string> categories = new List<string>();

                foreach (var item in categoryItems)
                {
                    categories.Add(item["Category"].ToString());
                }

                ComboCategory.ItemsSource = categories.Distinct();
            });
        }

        void categoryFailedCallback(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show("Failed to retrieve list of categories .. " + e.Message);
        }

        private void ComboCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string category = ComboCategory.SelectedItem.ToString();
            CamlQuery camlQuery = new CamlQuery()
            {
                ViewXml = string.Format(
                @"<View>
                     <Query>
                      <Where>
                        <Eq>
                          <FieldRef Name='Category'/>
                          <Value Type='Text'>{0} </Value>
                        </Eq>
                      </Where>
                    </Query>
                   </View>", category)
            };

            var query = from item in ctx.Web.Lists.GetByTitle("Books").GetItems(camlQuery)
                        select item;

            filteredItems = ctx.LoadQuery(query);
            ctx.ExecuteQueryAsync(listItemSucceededCallBack, listItemFailedCallback);
        }

        void listItemSucceededCallBack(object sender, ClientRequestSucceededEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                var data = from item in filteredItems
                           select new BookData {  BookTitle = item["Title"]. ToString(), Author = item["Author0"].ToString(), Publisher = item["Publisher"].ToString(), Year = item["Year"].ToString(), Category = item["Category"].ToString() };
                dataGrid1.ItemsSource = data.ToList();
            });
        }

        void listItemFailedCallback(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show("Failed to retrieve data from Books list.. " + e.Message);
        }
    }
}

public class BookData
{
    public string BookTitle {  get; set; }
    public string Author {  get; set; }
    public string Publisher {  get; set; }
    public string Year {  get; set; }
    public string Category {  get; set; }
}

The preceding code first populates the drop-down list for Categories. Then ClientContext.Current retrieves the ClientContext instance. Next the LoadQuery method is called to load the list item collection, and then the query is executed asynchronously. The code then retrieves the distinct categories in categorySucceededCallBack method and populates it in the items collection of the category drop-down list.

The ComboCategory_SelectionChanged method gets called when the user selects a category. The filtered records are retrieved and a collection of the BookData class is populated. Finally this collection is bound to the data grid.

You now need to deploy the Silverlight application to your SharePoint site:

1. Add a new Empty SharePoint project to the solution and name it ListDataSLDeploy.

2. Add the SharePoint Mapped Layouts folder to the Empty SharePoint project.

3. Add the following to the Post Build command of the Silverlight project:

xcopy /Y $(ProjectDir)$(OutDir)ListDataSLApp.XAP $(SolutionDir)ListDataSLDeployLayoutsListDataSLDeploy

4. Rebuild the solution and the XAP file gets copied to the LayoutsListDataSLDeploy folder in the SharePoint project. Include the file in the project.

5. Deploy the ListDataSLDeploy SharePoint project.

6. Open the SharePoint site and add a Silverlight web part to the home page. Set the URL for the Silverlight application as /_Layouts/ListDataSLDeploy/ListDataSLApp.xap.

7. Set the width of the Silverlight web part as 550 pixels and height as 350 pixels.

If you added some data to the Books list you can select a category and see the data in the Grid as shown in Figure 9.8.

Image

Figure 9.8. ListDataSLAppSilverlight application

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.116.20