Wednesday, September 19, 2012

SharePoint Client Object Model: Using lambda expression for ExecutequeryAsync

When using "ExecuteQueyAsync" method of client object model we genarally write two different callback methods for success and failure. Instead of that we can use "Lambda Expression" and avoid two separate methods. This will also avoid class level variables and we  can access parameters of calling method in callback too.
Here is one simple example of usage of lambda expression.

private void UpdateItem(int itemId, string fieldName, object fieldValue)

{
ListItem item = clientContext.Web.Lists.GetByTitle("MyList").GetItemById(itemId);

item[fieldName] = fieldValue;

item.Update();

clientContext.ExecuteQueryAsync((sender, args) =>

{
//On update success

MessageBox.Show("Item with id "+ itemId.ToString()+" updated successfuly");

},

(s, args) =>

{
//on update failure

MessageBox.Show("Error occurred updating item: " + itemId.ToString());

});

}
Hope this helps to those who are unaware of using lambda expression.

No comments:

Post a Comment