Client Object Model Basic Example – CAMLQuery


I was able to make a nice CAML Query Work in my Silverlight application so though it might be worth posting it over here as it might help some one. It is a query to read all items assigned to me or the group I am part of and the status is not completed. Now you can go ahead by your self and play with Query as you wish and make it to complex. But it is a working example.

void DoIt()
{
using (ClientContext ctx = ClientContext.Current)
{

string OrderBy = <OrderBy><FieldRef Name=’Created’ Ascending=’FALSE’/></OrderBy>;
                string Where = <View><Query><Where><And> +
                        <Or> +
                            <Membership Type=’CurrentUserGroups’> +
                                <FieldRef Name=’AssignedTo’/> +
                            </Membership> +
                            <Eq> +
                                <FieldRef Name=’AssignedTo’/> +
                                <Value Type=’Integer’> +
                                    <UserID/> +
                                </Value> +
                            </Eq> +
                        </Or> +
                        <Neq> +
                            <FieldRef Name=’Status’/> +
                            <Value Type=’Text’>Completed</Value> +
                        </Neq> +
                    </And></Where></Query> + OrderBy + </View>;

CamlQuery Query = new CamlQuery();
Query.ViewXml = Where;

TasksListItemCollection = ctx.Web.Lists.GetByTitle(“Tasks”).GetItems(Query);
ctx.Load(TasksListItemCollection);

ctx.ExecuteQueryAsync(Success, Fail);

};
}

void Success(object sender, ClientRequestSucceededEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
try
{
txtTaskCount.Text = TasksListItemCollection.Count.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString() + ex.StackTrace);
}
finally
{

}
});
}

void Fail(object sender, ClientRequestFailedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(“Failed to Load Items ” + e.Exception.ToString());
});
}

Thanks to Thousands of Blogers who blogged about Silverlight and SharePoint Client Object Model.