9 min read

Managing data in a Silverlight RIA included in a SharePoint solution

So far, we have been able to create, deploy, and debug a Silverlight RIA that read data from a list in the SharePoint server. It is also possible to insert, update, and remove items from these lists. In fact, the typical LOB (Line-Of-Business) RIA performs CRUD (Create, Read, Update, and Delete) operations. Therefore, we can create a Silverlight RIA to perform some of the CRUD operations with the existing list of tasks, by using more features provided by the SharePoint 2010 Silverlight Client OM.

We could improve our existing Silverlight RIA that displays data from the existing list in a grid. However, we are going to create a new Silverlight RIA and then, we will improve both applications to work together to offer a complex LOB solution.

We will analyze diverse alternatives to simplify the deployment process and show how to debug a Silverlight RIA that queries data from a SharePoint server.

Working with the SharePoint 2010 Silverlight Client Object Model to insert items

Now, we are going to create a new solution in Visual Studio. It will include two new projects:

  • A Silverlight application project, SLTasksCRUD
  • An empty SharePoint 2010 project with a module, SPTasksCRUD

Follow these steps to create the new Silverlight RIA that allows a user to insert a new item into the list in the SharePoint server:

This example requires the ProjectsList2010 list created in SharePoint

  1. Start Visual Studio as a system administrator user.
  2. Select File New | Project…| or press Ctrl+Shift+N. Select Other Project Types Visual Studio Solutions under Installed Templates in the New Project dialog box. Then, select Blank Solution and enter TasksCRUD as the project’s name and click OK. Visual Studio will create a blank solution with no projects.
  3. Right-click on the solution’s name in Solution Explorer and select Add New Project from the context menu that appears.
  4. Select Visual C# Silverlight under Installed Templates in the New Project dialog box. Then, select Silverlight Application, enter SLTasksCRUD as the project’s name and click OK.
  5. Deactivate the Host the Silverlight application in a new Web site checkbox in the New Silverlight Application dialog box and select Silverlight 4 in Silverlight Version. Then, click OK. Visual Studio will add the new Silverlight application project to the existing solution.
  6. Follow the necessary steps to add the following two references to access the new SharePoint 2010 Silverlight Client OM:
    • Microsoft.SharePoint.Client.Silverlight.dll
    • Microsoft.SharePoint.Client.Silverlight.Runtime.dll

  7. Open App.xaml.cs and add the following using statement:
    using Microsoft.SharePoint.Client;
  8. Add the following code in the StartUp event handler to initialize the Microsoft.SharePoint.Client.ApplicationContext with the same initialization parameters and the synchronization context for the current thread (the UI thread).
  9. private void Application_Startup(object sender, StartupEventArgs e)
    {
    this.RootVisual = new MainPage();
    // Initialize the ApplicationContext
    ApplicationContext.Init(e.InitParams,
    System.Threading.SynchronizationContext.Current);
    }

  10. Open MainPage.xaml, define a new width and height for the Grid, 800 and 600, add the following controls, and align them as shown in the following screenshot:
    • Six Label controls aligned at the left with the following values for their Content properties. They are Title, Priority, Status, % Complete, Start Date and Due Date.
    • One Label control, located at the bottom, lblStatus.
    • One TextBox control, txtTitle.
    • One ComboBox control, cboPriority.
    • One ComboBox control, cboStatus.
    • One Slider control, sldPercentComplete. Set LargeChange to 10, Maximum to 100, and Minimum to 0. This slider will allow the user to set the percentage of the total work that has been completed.
    • One DatePicker control, dtStartDate.
    • One DatePicker control, dtDueDate.
    • One Button control, butInsert. Set its Title property to Insert
  11. Select the Grid, LayoutRoot. Click on the Categorized button to arrange the properties by category. Then, click on Brushes Background| and a color palette with many buttons located at the top and the bottom will appear. Click on the Gradient Brush button, located at the top and then on the Vertical Gradient one, located at the bottom. Define both the start and the stop colors. The rectangle that defines the background Grid will display a nice linear gradient, as shown in the previous screenshot.
  12. Open MainPage.xaml.cs and add the following using statements to include the Microsoft.SharePoint.Client namespace:
  13. using Microsoft.SharePoint.Client;
    using SP = Microsoft.SharePoint.Client;
    Add the following two private variables
    private SP.ClientContext _context;
    private SP.List _projects;

    Add the following method to fill the drop-down lists that will display the different options for the priority and the status:

    private void FillComboBoxes()
    {
    cboPriority.Items.Add("(1) High");
    cboPriority.Items.Add("(2) Normal");
    cboPriority.Items.Add("(3) Low");
    cboStatus.Items.Add("Not Started");
    cboStatus.Items.Add("In Progress");
    cboStatus.Items.Add("Completed");
    cboStatus.Items.Add("Deferred");
    cboStatus.Items.Add("Waiting on someone else");
    }

    It is possible to retrieve the possible choices for both the Priority and Status fields.In this case, we add the possible values in this method and then we will learn how to retrieve the choices through queries to the SharePoint server.

  14. Add the following line to the page MainPage constructor:
  15. public MainPage()
    {
    InitializeComponent();
    FillComboBoxes();
    }

  16. Now, it is necessary to add code to execute the following tasks:
    • Connect to the SharePoint server and load the current user that logged on the server, ConnectAndAddItemToList method.
    • Add a new item to the ProjectsList2010 list, considering the values entered by the user in the controls, AddItemToList method.
  17. private void ConnectAndAddItemToList()
    {
    // Runs in the UI Thread
    lblStatus.Content = "Started";
    _context = new
    SP.ClientContext(SP.ApplicationContext.Current.Url);
    _context.Load(_context.Web);
    // Load the current user
    _context.Load(_context.Web.CurrentUser);
    _context.ExecuteQueryAsync(OnConnectSucceeded, null);
    }
    private void AddItemToList()
    {
    // Runs in the UI Thread
    lblStatus.Content = "Web Connected. Adding new item to List...";
    _projects = _context.Web.Lists.GetByTitle("ProjectsList2010");
    ListItem listItem = _projects.AddItem(new
    ListItemCreationInformation());
    listItem["Title"] = txtTitle.Text;
    listItem["StartDate"] =
    Convert.ToString(dtStartDate.SelectedDate);
    listItem["DueDate"] = Convert.ToString(dtDueDate.SelectedDate);
    listItem["Status"] = "Not Started";
    var fieldUserValue = new FieldUserValue();
    // Assign the current user to the Id
    fieldUserValue.LookupId = _context.Web.CurrentUser.Id;
    listItem["AssignedTo"] = fieldUserValue;
    listItem["Priority"] = "(2) Normal";
    listItem["PercentComplete"] =
    Convert.ToString(Math.Round(sldPercentComplete.Value, 0)/100);
    listItem.Update();
    // Just load the list Title proprty
    _context.Load(_projects, list => list.Title);
    _context.ExecuteQueryAsync(OnAddItemToListSucceeded,
    OnAddItemToListFailed);
    }

  18. All the previously added methods are going to run in the UI thread. The following methods, which are going to be fired as asynchronous callbacks, schedule the execution of other methods to continue with the necessary program flow in the UI thread:
    • When the connection to the SharePoint server, requested by the ConnectAndAddItemToList method, is successful, the OnConnectSucceeded method schedules the execution of the AddItemToList method in the UI thread. If the ConnectAndAddItemToList method fails, the OnConnectFailed method schedules the execution of the ShowErrorInformation method in the UI thread, sending the ClientRequestFailedEventArgs args instance as a parameter to the delegate.
    • When the insert operation performed on the list available in the SharePoint server, requested by the AddItemToList method, is successful, the OnAddItemToListSucceeded method schedules the execution of the ShowInsertResult method in the UI thread. If the AddItemToList method fails, the OnAddItemToList method schedules the execution of the ShowErrorInformation method in the UI thread, sending the ClientRequestFailedEventArgs args instance as a parameter to the delegate.
  19. private void ShowErrorInformation(ClientRequestFailedEventArgs
    args)
    {
    System.Windows.Browser.HtmlPage.Window.Alert(
    "Request failed. " + args.Message + "n" +
    args.StackTrace + "n" +
    args.ErrorDetails + "n" + args.ErrorValue);
    }
    private void ShowInsertResult()
    {
    lblStatus.Content = "New item added to " + _projects.Title;
    }
    private void OnConnectSucceeded(Object sender, SP.ClientRequestSuc
    ceededEventArgs args)
    {
    // This callback isn't called on the UI thread
    Dispatcher.BeginInvoke(AddItemToList);
    }
    private void OnConnectFailed(object sender,
    ClientRequestFailedEventArgs args)
    {
    // This callback isn't called on the UI thread
    // Invoke a delegate and send the args instance as a parameter
    Dispatcher.BeginInvoke(() => ShowErrorInformation(args));
    }
    private void OnAddItemToListSucceeded(Object sender, SP.ClientRequ
    estSucceededEventArgs args)
    {
    // This callback isn't called on the UI thread
    //Dispatcher.BeginInvoke(GetListData);
    Dispatcher.BeginInvoke(ShowInsertResult);
    }
    private void OnAddItemToListFailed(object sender,
    ClientRequestFailedEventArgs args)
    {
    // This callback isn't called on the UI thread
    // Invoke a delegate and send the args instance as a parameter
    Dispatcher.BeginInvoke(() => ShowErrorInformation(args));
    }

    Add the following line to the Click event for the butInsert Button. This way, when the user clicks on this button, the application will connect to the SharePoint server and will insert the new item.

    private void butInsert_Click(object sender, RoutedEventArgs e)
    {
    ConnectAndAddItemToList();
    }

Now, follow these steps to create a new SharePoint module and link it to the previously created Silverlight RIA, SLTasksCRUD.

  1. Stay in Visual Studio as a system administrator user.
  2. Right-click on the solution’s name in Solution Explorer and select Add | New Project… from the context menu that appears.
  3. Select Visual C# SharePoint | 2010| under Installed Templates in the New Project dialog box. Then, select Empty SharePoint Project, enter SPTasksCRUD as the project’s name, and click OK. The SharePoint Customization Wizard dialog box will appear.
  4. Enter the URL for the SharePoint server and site in What local site do you want to use for debugging?
  5. Click on Deploy as a sandboxed solution. Then, click on Finish and the new SPTasksCRUD empty SharePoint 2010 project will be added to the solution.
  6. Add a new item to the project, that is a SharePoint 2010 module, Module1.
  7. Expand the new SharePoint 2010 module, Module1, in the Solution Explorer and delete the Sample.txt file.
  8. Now, right-click on Module1 and select Properties in the context menu that appears. In the Properties palette, click the ellipsis (…) button for the Project Output References property. The Project Output References dialog box will appear.
  9. Click on Add, below the Members list. The empty SharePoint 2010 project’s name, SPTasksCRUD, will appear as a new member.
  10. Go to its properties, shown in the list, located at the right. Select the Silverlight application project’s name, SLTasksCRUD, in the Project Name drop-down list.
  11. Select ElementFile in the Deployment Type drop-down list. The following value will appear in Deployment Location: {SharePointRoot}TemplateFeatures{FeatureName}Module1, as shown in the next screenshot:
  12. Click OK and the SharePoint project now includes the Silverlight application project, SLTasksCRUD.

  13. Now, right-click on the SharePoint 2010 project, SPTasksCRUD, and select Properties in the context menu that appears. Click on the SharePoint tab in the properties panel and different options for the SharePoint deployment configuration will be shown.
  14. Activate the Enable Silverlight debugging (instead of Script debugging) checkbox. Remember that this option will allow us to debug code in the Silverlight application that adds items to the list in the SharePoint server.
  15. Right-click on the solution’s name in Solution Explorer and select Properties from the context menu that appears. Select Startup Project in the list on the left, activate Single startup project, and choose the SharePoint project’s name in the drop-down list below it, SPTasksCRUD. Then, click OK.
  16. Build and deploy the solution.
  17. Now that the WSP package has been deployed to the SharePoint site, follow the necessary steps to create a new web page, add the Silverlight Web Part, and include the Silverlight RIA in it. Remember that in this case, it is not necessary to upload the .xap file because it was already deployed with the WSP package.

LEAVE A REPLY

Please enter your comment!
Please enter your name here