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.

Advertisements

One thought on “Client Object Model Basic Example – CAMLQuery

  1. Jerry, Nice article; have a tip to share replace string concatenation with stringbuilder object, reason behind doing is that its more memory efficient. When we concatenate a string variable CLR always create a new variable in background process thats not a case when we call StringBuilder.Append method.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s