Thursday, April 25, 2013

Silverlight WebPart in SharePoint 2010

SharePoint 2010 supports fully integration with Silverlight application either of Silverlight In Browser  or as a Silverlight OOB ( Out Of Browser) aplications. In this blog post I am going to explain about High Touch Integration with Silverlight and Sharepoint using SharePoint 2010 Client Object Model (OM) with one example of Silverlight Task Lists for Sharepoint. I have also explained how to host a Silverlight web parts with in SharePoint using Sharepoint Out-Of-the-Box Silverlight Web Parts. As per my understanding below is the over all diagram for a High Touch Integration of Silverlight and SharePoint 2010

From the above diagram we can see, that we have SharePoint Client Object Model (OM) and  Services, Which can be consumed by a Silverlight Application.  Object model and services is not only for Silverlight, you can use them for different client applications.


Before start with the application, I just wanted to let you know about the different type of integration model that are available Silverlight and SharePoint Integration. We can display a Silverlight application inside SharePoint application either as Html, Iframe, Host as web parts or use Object Model or services with Silverlight Application etc. But there is no such hard and fast classification types on the same . I found this great classification from the Designing Enterprise Corporate Web Sites using SharePoint 2010 Presentation.  These classifications are

1. No Touch : By no touch means, there is no direct integration with SharePoint and Silverlight. You may have some different Silverlight web application and you are showing then inside Share Point using Iframe. You can use this kind of scenarios when you have some existing web sites which is based on silver light and you want to show it inside your Sharepoint application.


2. Low Touch : Low Touch does a bit more interaction with SharePoint. This is nothing but hosting a Silverlight Application with in SharePoint site using SharePoint Out-of-the-Box Silverlight Web Parts.  That application is an independent application which may call some other services apart from SharePoint API.




High Touch : High touch integration is nothing but using the power of using SharePoint Object model. Where we can use either point Client Object model or Web services to read and write information from SharePoint Server. We can use any kind of client application like Silverlight, ASP.NET or Win forms, WPF even JavaScript. Below diagram showing Silverlight as an Client Application.


Now, I am going to show a complete demonstration on High Touch Integration of Silverlight and SharePoint application using Silverlight Client Object Model. I will be describe below three scenarios in this application using Client Object Model

1. In Browser Silverlight Application
2. Out of Browser (OOB) Silverlight Application
3. Host XAP File as Silverlight Web Part inside SharePoint using OOB (Out-Of-The-Box) Silverlight Web parts

So, let’s start by Creating a Silverlight Application , Open Visual Studio > New > Project . Select Silverlight Project Template and Select .NET Framework 4.0 . Give the Project Name as “SilverlightSPIntegration” 


Once you click on “OK” button,  you will get another popup window automatically which will ask permission to create a web application which will host your silverlight application in a ASP.NET web application.

Once you have done with creation of your Silverlight application the next task is to add the Reference of Client Object Model API.  Right click on your Silverlight solution select “Add Reference”




and then we need select  “Microsoft.SharePoint.Client.Silverlight.dll” and “Microsoft.SharePoint.Client.Silverlight.Runtime.dll” from the location “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin”



Once you have done with adding reference, you will get the below Solution structure for your Silverlight Application


Now, before going forward do design the XAML for Silverlight application, let’s finished the work at SharePoint  site. As I have already said, In this application we are going to read some data from SharePoint Inbuilt “Task” List. So, Open the SharePoint Site and navigate to Task List from Quick Launch.

This is exact default task list for SharePoint. You can use any of the list, even your custom created list. But based on you have to design UI and code for the same. Now, Enter some dummy data in to task list.



Below is the list of dummy data that I have added inside Task List .




As of now we are done with the SharePoint part.  Now we have to create a custom UI using Silverlight to show these data in a Silverlight application . Again, the demo is kinda simple, but objective is to see how the integration things works with Object Model.

Go back to your visual studio Silverlight solution and design a simple screen with some line of XAML code.



To give a quick style, I did some color customization using Expression Blend.



Save the project from Expression Blend, and Open the Silverlight application from Visual Studio. It will ask for Reload the application as it has been modified out side of environment.


Below is the XAML code block for Silverlight UI


            <!--
                <Setter Property="MinWidth" Value="150" />
                <Setter Property="MaxWidth" Value="150" />
                <Setter Property="HorizontalAlignment" Value="Left" />

-->
            <!--
                <Setter Property="HorizontalAlignment" Value="Right" />
                <Setter Property="Foreground" Value="Orange" />

-->


Now you are almost done with the Designing with the application. At this point you can press “F5” to run the application to check how your UI looks like.



Above screen is your designed Silverlight application which is hosted inside ASP.NET Web application.  Now, it’s time to use SharePoint Client Object Model to read the data from SharePoint Task List.

As we are going to read the information of List of Class, so first create a Task type class which will be the place holder for Task. Below is code snippet for Task Class.


    public class Tasks
    {
        public string Title { get; set; }
        public string DueDate { get; set; }
        public string Status { get; set; }
        public string Priority { get; set; }
        public double PercentComplete { get; set; }
    }

Now, Open MainPage.XAML.CS file and first add the below name spaces

using Microsoft.SharePoint.Client;

When you are done the adding namespace you are ready to use OM API’s.

Below is the sample code  block to get the lists Instance for an given SharePoint site.

///
/// Handles the Loaded event of the MainPage control.
///
///
The source of the event.
///
The  instance containing the event data.
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
using (ClientContext SharePointContext = new ClientContext(this.SPWebSiteURL))
{
this.query = new CamlQuery();
SharePointContext.Load(SharePointContext.Web);
this.task = SharePointContext.Web.Lists.GetByTitle("Tasks");
this.strQuery = @" ";
query.ViewXml = this.strQuery;
this.taskLists = this.task.GetItems(this.query);
SharePointContext.Load(this.taskLists);
SharePointContext.ExecuteQueryAsync(this.OnSiteLoadSuccess, this.OnSiteLoadFailure);
}
}

SharePointContext.ExecuteQueryAsync  method  execution is asynchronous. This method used two different call back event handler for success and failure of the context operation.


As per my application If the asynchronous execution successed, it will invoked OnSiteLoadSuccess otherwise OnSiteLoadFailure. Below is the sample code snippet for those two methods.

       ///
        /// Called when [site load success].
        ///
        ///
The sender.
        ///
The  instance containing the event data.
       private void OnSiteLoadSuccess(object sender, ClientRequestSucceededEventArgs e)
       {
           foreach (ListItem item in this.taskLists)
           {
               Tasks objTask = new Tasks();
               objTask.Title = item["Title"].ToString();
               objTask.DueDate = item["DueDate"].ToString();
               objTask.Status = item["Status"].ToString();
               objTask.Priority = item["Priority"].ToString();
               double fraction = Convert.ToDouble(item["PercentComplete"]);
               objTask.PercentComplete = fraction * 100;
               this.SharePointTasks.Add(objTask);
           }
          AddTaskList( this.SharePointTasks);
       }

        ///
        /// Called when [site load failure].
        ///
        ///
The sender.
        ///
The  instance containing the event data.
       private void OnSiteLoadFailure(object sender, ClientRequestFailedEventArgs e)
       {
           MessageBox.Show(e.Message +  e.StackTrace);
       }

Now we have to create a delegate to update the UI using Dispatcher.BeginInvoke  to avoid the cross thread exception.

            ///
        /// Adds the task list.
        ///
        private void AddTaskList()
        {
            this.Dispatcher.BeginInvoke(new UpdateSilverLightUI(this.AddItemsToLists), this.SharePointTasks);
        }

        ///
        /// Updates the UI.
        ///
        ///
The tasks.
        private void AddItemsToLists(List tasks)
        {
            foreach (Tasks t in tasks)
            {
                TaskList.Items.Add(t.Title);
            }
        }

Now all tasks has been added to Silverlight Task List , after that we have to handled the Listbox Selection changed Event and showing the proper value to different text boxes.

       ///
        /// Handles the SelectionChanged event of the listBox1 control.
        ///
        ///
The source of the event.
        ///
The  instance containing the event data.
private void TaskList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var v = this.SharePointTasks.FirstOrDefault(item => item.Title.Equals(TaskList.SelectedItem.ToString()));
    if (v != null)
    {
        txtTitle.Text = v.Title;
        txtDueDate.Text = v.DueDate;
        txtPriority.Text = v.Priority;
        txtStatus.Text = v.Status;
        txtPercentage.Value = v.PercentComplete;
    }
}

Yes, we are now done with the implementation, But if you are trying to run the application now, you may get the exception for cross domain access as your SharePoint site hosted on IIS and You are running you application from VS. To resolve this issues, you have to place the clientAccessPolicy.xml file to root of your SharePoint Sites.
Press F5 and run your application. Yes, Below screen will appear with  exact same set of  sharepoint task list data that we have entered earlier in SharePoint Lists. You can click an of the Task from the list and get the details.



This is all about the first level of integration of Silverlight and SharePoint where you can host the application inside a ASP.NET Web sites separately.

Now, let’s make it more interesting by creating this application as Out Of Browser (OOB)  Silverlight Application. This is just kind of small configuration setting to convert this as OOB.

Right Click on Silverlight Application > Properties and Select the “Enable running application out of the Browser” check box as shown in below image.


To do some more configuration, Click on “Out-of-Browser Settings…”  . You can change the height as width and display names and click on OK.


After the OOB settings, run the application, you will find your application is ruining as a windows application as shown below.



Till now I have discussed about the In Browser Silverlight and OOB Silverlight application integration with SharePoint.

Now I am going to describe how you can  host this Silverlight Application Inside SharePoint as a SharePoint Web Parts.  Hosting Silverlight XAP file as SharePoint site is similar as I have already discussed in my Bing Map Control article

First create one sample SharePoint 2010 Project under same solution. Select “Empty Share Point Project



Give the Project name and click on “OK“. The next screen will appear as below.




This will ask you for the site location and trust level type. You can go with the default selection. Click on “OK”. You are done with the SharePoint Project Creation.


Now you have to add one SharePoint Module with this project. A module contains files that are included in a SharePoint application when it is deployed. To add a module, right click on SharePoint Project and Click on Add New Item.



Give the module name and click on “Add”. After that Right Click on the module and click on “Properties



In the properties windows “Select Project Output Reference” and do the setting as below diagram.



Keep in mind, you need to select the Deployment Type as “ElementFile” and Project name should be the name of your “Silverlight Solution”. Click on the OK. Now go to “Element.XML” File under the SharePoint Module. Verify the path for the Silverlight “.xap” File. You need to provide the same url while you will add the Silverlight Web part inside SharePoint Site.

Now, you are done with SharePoint Project. Build and Deploy it. Just right click on the SharePoint Project and select Deploy. You are done with the deployment.



Host Silverlight Web Part to SharePoint Site

Hosting of Silverlight Web Part is quite similar that we generally used for our normal web parts. First of all you need to open the SharePoint Page in Edit Mode, Go To Insert and Select Web Part. Under the category section select “Media and Content” category and select SharePoint Out-Of-The-Box  “Silverlight Web Part” from Web Part .  Click on Add.


You will see one AJAX Popup will apear and you need to input the url for the Silverlight Application Package (xap) file. Provide the url which you have already specified in Element. XML file inside the SharePoint Module.



Click on OK.  You will get the below screen after successfully adding Silverlight Web Parts.



You are done. Save the page and Browse. :)  Sometimes you may get this below error screen after providing the XAP file path.


 For that, you have to make sure you have given the valid XAP deployed path. If the path is valid, you have to check the Corresponding features is activated or not. You can check that from Site Actions > Site Settings

 If you check the below screen where I have shown both the SharePoint Task List and Silverlight Task Control in a single Page.




If you add any new task in you task list that will also be reflected in your Silverlight Task Control.

If you want to avoid this long process of hosting just upload the XAP File in a document library provide the XAP file path in Silverlight Web Part.




You can also create custom web part with this Silverlight Control in SharePoint 2010 Project and then deploy the web part.

1 comment:

  1. I am inspired with your post writing style & how continuously you describe this topic on sharepoint training for beginners. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.

    ReplyDelete