Interacting with Data on the SharePoint Server

Exclusive offer: get 50% off this eBook here
Microsoft Silverlight 4 and SharePoint 2010 Integration

Microsoft Silverlight 4 and SharePoint 2010 Integration — Save 50%

Techniques, practical tips, hints, and tricks for Microsoft Silverlight 4 interactions with SharePoint 2010 in this book and eBook

$32.99    $16.50
by Gastón C. Hillar | August 2010 | Enterprise Articles Microsoft

In this article by Gastón C. Hillar, author of the book Microsoft Silverlight 4 and SharePoint 2010 Integration, we will cover many topics that help us create simple and complex Line-Of-Business Silverlight RIAs that run as Silverlight Web Parts to interact with data in the SharePoint Server.

In this article, we will:

  • Use a Silverlight RIA to insert items into a SharePoint list
  • Prepare code to handle errors when remote operations fail
  • Work with messages to allow multiple Silverlight RIAs to communicate with each other

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}\Template\Features\{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.
Microsoft Silverlight 4 and SharePoint 2010 Integration Techniques, practical tips, hints, and tricks for Microsoft Silverlight 4 interactions with SharePoint 2010 in this book and eBook
Published: July 2010
eBook Price: $32.99
Book Price: $54.99
See more
Select your format and quantity:

Inserting items in a SharePoint list with the Silverlight Web Part

Now, follow these steps to insert an item with the recently deployed Silverlight RIA running in a Silverlight Web Part.

  1. Enter the URL for the previously added page that contains the Silverlight Web Part in the web browser. This way, the Silverlight RIA will appear.
  2. Enter a value for the Title. Select a value for both the Priority and the Status drop-down lists and use the slider to specify the percentage of the work completed so far and select both the Start Date and the Due Date by clicking on the datetime pickers. The following screenshot shows some values and the elegant drop-down list that offers the five alternatives for Status:
  3. Click on the Insert button. The application is going to display its different status values in the label located at the bottom:
    1. Ready
    2. Started
    3. Web Connected. Adding new item to List...
    4. New item added to ProjectsList2010
  4. Open or refresh the items for the list in the corresponding SharePoint 2010 page and you will see the new item added to the list with the values entered in the application and the user logged on to the SharePoint server in the Assigned To column. The following screenshot shows the new item in the list:
  5. The Silverlight RIA doesn't include code to validate the data that is going to be added to the list in the SharePoint server. Thus, the user can enter inappropriate values for the fields. Enter a new title and delete the value for Start Date. Then, click on the Insert button and a new dialog box will appear, indicating that the request failed, because the String was not recognized as a valid DateTime. The problem is that the StartDate field has the invalid value 0. The following screenshot shows the dialog box with the error message:
  6. This dialog box is the result of the execution of the OnAddItemToListFailed callback, the second parameter of the _context.ExecuteQueryAsync method in AddItemToList. As something went wrong, this callback invokes a delegate that send the args instance as a parameter to the ShowErrorInformation method.

    Dispatcher.BeginInvoke(() => ShowErrorInformation(args));

  7. Debug the Silverlight RIA.This way, you will be able to understand the different steps that we are going to analyze in the following section.

Working with successful and failed asynchronous queries

The following sequence diagram shows the interaction between the methods defined in MainPage that are going to run in the UI thread, the Microsoft.SharePoint.Client.ClientContext instance, _context, and the methods defined in MainPage that are going to run in another thread, that is, a worker thread. This sequence represents the situation in which all the asynchronous operations against the SharePoint server have a successful completion:

When the user clicks the Insert button, the Click event handler calls the ConnectAndAddItemToList method, in the UI thread. This method uses the current URL to generate a ClientContext instance, saved in the private_context variable. Then, it calls the Load method to build a query to load the Web and its current user, the user that logged on to the SharePoint site. Then, it calls the ExecuteQueryAsync to run it with an asynchronous execution.

_context.Load(_context.Web);
_context.Load(_context.Web.CurrentUser);

If the query has a successful execution, the OnConnectSucceeded callback schedules the asynchronous execution of the AddItemToList method in the UI thread from a worker thread that runs this code after the query has succeeded.

private void OnConnectFailed(object sender,
ClientRequestFailedEventArgs args)
{
Dispatcher.BeginInvoke(() => ShowErrorInformation(args));
}

In this example, we also specified the OnConnectFailed callback and used it as the second parameter for the ExecuteQueryAsync method. If something goes wrong, it invokes a delegate that calls the ShowErrorInformation method and sends the ClientRequestFailedEventArgs args instance as a parameter to it. The code uses a lambda expression to define the delegate:

private void OnConnectFailed(object sender,
ClientRequestFailedEventArgs args)
{
Dispatcher.BeginInvoke(() => ShowErrorInformation(args));
}

Remember that a lambda expression, introduced in C# 3.0, is an anonymous function that can contains expressions and statements and can be used to create delegates or expression tree types. They are useful to simplify the code when we use delegates. All lambda expressions use the lambda operator => (read as goes to).

The following lines show equivalent code to define a delegate and invoke it to run asynchronously in the UI thread without using a lambda expression. It requires more lines of code, because it is necessary to declare a delegate type, create a new instance with the method to run, use the Dispatcher.BeginInvoke method to call the delegate instance, and send the args instance as a parameter encapsulated in an array of object.

private delegate void ShowErrorInformationCaller
(ClientRequestFailedEventArgs args);


private void OnConnectFailed(object sender,
ClientRequestFailedEventArgs args)
{
// This callback isn't called on the UI thread
// Create the delegate instance
ShowErrorInformationCaller ShowErrorInformationD =
new ShowErrorInformationCaller(ShowErrorInformation);
// Invoke the delegate
Dispatcher.BeginInvoke(
ShowErrorInformationD, new object[] { args });

}

It is convenient to use lambda expressions, because they require less code to achieve the same goal. However the previously shown lines make it easier to understand the way the method is called in the delegate.

If everything works as expected, then the AddItemToList method is going to run in the UI thread. This method calls the GetByTitle method to save a reference to the ProjectsList2010 list, in the _projects private variable. Then, it calls its AddItem method to add a new ListItemCreationInformation empty instance. This method returns a new ListItem instance that allows us to access the fields for the new item in the list and fill their values.

_projects = _context.Web.Lists.GetByTitle("ProjectsList2010");
ListItem listItem = _projects.AddItem(new
ListItemCreationInformation());

Then, the code completes the value for each field by using its InternalName and assigning a string value, as shown in the next line.

listItem["Title"] = txtTitle.Text;

The AssignedTo field is a special case, because it is a FieldUserValue that references a SharePoint server user through a lookup ID. Remember that this field had a Microsoft.SharePoint.SPFieldUserValue value in its FieldValueType property. Thus, it is necessary to use the Id for the user currently logged on the SharePoint server to assign it to the LookupId property of a new FieldUserValue instance, fieldUserValue. Then, it is possible to assign fieldUserValue to listItem["AssignedTo"] to store the current user as the value for this field.

var fieldUserValue = new FieldUserValue();
fieldUserValue.LookupId = _context.Web.CurrentUser.Id;
listItem["AssignedTo"] = fieldUserValue;

Remember, it is possible to access the _context.Web.CurrentUser.Id property because we queried _context.Web.CurrentUser in the ConnectAndAddItemToList method.

Once all the fields are filled with the corresponding values, the code calls the Update method for the new ListItem instance that holds the new row, listItem. At this point, the new item isn't still inserted in the list, because it is necessary to execute the query. The code requests the Title for the list as a response and then calls the ExecuteQueryAsync method:

listItem.Update();
_context.Load(_projects, list => list.Title);
_context.ExecuteQueryAsync(OnAddItemToListSucceeded,
OnAddItemToListFailed);

The following diagram shows the detailed execution flowchart for the asynchronous query that adds the item to the list. Besides, it indicates the code that runs in the UI thread. If the query execution isn't successful, the application will run the OnAddItemToListFailed callback and it will display information about the error that made the query fail in a dialog box. If the query execution succeeds, the application will run the OnAddItemToListSucceeded callback and it will display status information to let the user know that the item was inserted in the list.

Summary

In this article, we learned about developing and deploying Silverlight 4 applications in SharePoint 2010 sites that interact with data in lists by performing insert, update, and delete operations. Specifically, we created a new Silverlight 4 RIA that allowed us to insert new items into a remote SharePoint list. Then, we enhanced this simple application to retrieve metadata information for the fields that compose the list to offer the possible choices and default values for some of the fields.

Microsoft Silverlight 4 and SharePoint 2010 Integration Techniques, practical tips, hints, and tricks for Microsoft Silverlight 4 interactions with SharePoint 2010 in this book and eBook
Published: July 2010
eBook Price: $32.99
Book Price: $54.99
See more
Select your format and quantity:

About the Author :


Gastón C. Hillar

Gastón C. Hillar has been working with computers since he was eight. He began programming with the legendary Texas TI-99/4A and Commodore 64 home computers in the early 80s.
He has a Bachelor degree in Computer Science from which he graduated with honors, and an MBA from which he graduated with an outstanding thesis. Now, he is an independent IT consultant and a freelance author always looking for new adventures around the world.

To date he’s written more than 40 books in Spanish, and for Packt Publishing has written “C# 2008 and 2005 Threaded Programming: Beginner's Guide”. He usually writes articles for Spanish magazines Mundo Linux, Solo Programadores and Resistor.
He contributes to Dr. Dobb's Go Parallel programming portal http://www.ddj.com/go-parallel/ and he is a guest blogger at Intel Software Network http://software.intel.com

Gastón C. Hillar is the author of "Microsoft Silverlight 4 and SharePoint 2010 Integration".

Books From Packt


Microsoft Silverlight 4 Data and Services Cookbook
Microsoft Silverlight 4 Data and Services Cookbook

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide
Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

SharePoint Designer Tutorial: Working with SharePoint Websites
SharePoint Designer Tutorial: Working with SharePoint Websites

The Microsoft Outlook Ideas Book
The Microsoft Outlook Ideas Book

Microsoft Dynamics NAV 2009 Application Design
Microsoft Dynamics NAV 2009 Application Design

Refactoring with Microsoft Visual Studio 2010
Refactoring with Microsoft Visual Studio 2010

Microsoft Windows Workflow Foundation 4.0 Cookbook
Microsoft Windows Workflow Foundation 4.0 Cookbook

BlackBerry Enterprise Server for Microsoft® Exchange
BlackBerry Enterprise Server for Microsoft® Exchange


No votes yet
Insert, Update, Delete in SharePoint 2010 list using Client Obje by
This is one of the best article so far I have read online. No crap just useful information. Its really helpful for beginner as well as developer. Thanks for sharing with us. Check out this helpful link too its also having a wonderful discussion. http://mindstick.com/Articles/50c4e9b3-2190-4bbf-9e57-035f228f1516/?Insert,%20Update,%20Delete%20in%20SharePoint%202010%20list%20using%20Client%20Object%20Model Thanks

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Y
1
x
i
v
7
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software