Exercise 4: Editing an existing SPListItem

This exercise builds on top of the previous three Exercises and adds code to the starter solution to show how you can use the Silverlight client object model delete a list item.

Task 1 – Adding the Client OM Code

In this task, you will add more Silverlight client object model code to the starter solution. This code will delete an existing item from the Announcements list.

  1. If the browser is still open from Exercise 1, close it and return to Visual Studio.
  2. From Solution Explorer, in the SilverlightApplication1 project, double-click the file MainPage.xaml to open it and display the Silverlight design canvas.
  3. Double-click on the Delete button in the canvas to open up the MainPage.xaml.cs code-behind file for the Silverlight page.
  4. Make sure that the cursor is located inside the ButtonDelete_Click event that was added when we double-clicked the button from the XAML.
  5. Add the following code

    C#

    ClientContext spContext = new ClientContext(siteUrl); list = spContext.Web.Lists.GetByTitle("Announcements"); spContext.Load(list); item = list.GetItemById(2); item.DeleteObject(); spContext.ExecuteQueryAsync(OnDeleteSuccess, OnFailure);

  6. This code operates the same as the code we added in the previous exercises with regard to batching and its asynchronous nature. However, because we are not really accessing the list item to read or work with its column values, we can set all of that up before committing to the server with the ExecuteQueryAsync call. We simply get the item by its ID, as we’ve done previously, and then call its DeleteObject method.
  7. Position your cursor after the closing curly brace for the ButtonDeleteClick method and add the following code:

    C#

    private void OnDeleteSuccess(object sender, ClientRequestSucceededEventArgs args) { Dispatcher.BeginInvoke(() => { MessageBox.Show("Item Deleted"); }); }

  8. This code is called when our call to the server succeeds. Our item has already been deleted on the server, so this code simply utilizes the Dispatcher.BeginInvoke method to tell the UI thread to show the message that our item has been deleted.
  9. This completes the coding, so hit F5 to test out the solution. After Visual Studio launches the browser, navigate to https://intranet.contoso.com/sites/IntroducingSLCOM/SitePages/SilverlightApplication1WebPartPage.aspx.
  10. Click the Delete button in the Silverlight web part to call our code. You should see a popup:

    Figure 6

    Displayed popup

Exercise 4 Verification

In order to verify that you have correctly performed all steps of exercise 4, proceed as follows:

Verification 1

In this verification, you can compare the anticipated output shown in step 8 with the actual output shown on your screen. If the two match, you have completed the exercise successfully.