CAML Query – Show element not assigned to me or my groups

SP2013

Hello everyone,

Some time ago, I made a summary post on « Filter on current user and current user groups »

This query uses the “membership” parameter to recover the current user groups. However, some time ago, a request was made on the msdn forums for reverse query! Namely, retrieve elements which are not assigned either to the current user or to one of its groups!

After doing several tests, I did not find any conclusive parameter and I turned to a solution of dynamic creation of the query.

Here it is


SPQuery query = new SPQuery();

query.Query = CreateQuery(web.SiteGroups);

.....

string CreateQuery(SPGroupCollection groups)

{

string queryToReturn = "<Where>";

int countAnd = 0;

List<string> listGroupName=new List<string>();

//Get list of group Name and count the number

foreach (SPGroup group in groups)

{

if (group.ContainsCurrentUser)

{

listGroupName.Add(group.Name);

countAnd++;

}

}

//If there is a least one group where the current user is in, we will need an 'And' and to add all the possibilities

if (countAnd > 0)

{

queryToReturn += "<And>";

for (int i = 0; i < countAnd - 2; i++)

{

queryToReturn += string.Format(@"<And><Neq><FieldRef Name='BelongsTo'/><Value Type='User'>{0}</Value></Neq>", listGroupName[i].ToString());

}

queryToReturn += string.Format(@"<Neq><FieldRef Name='BelongsTo'/><Value Type='User'>{0}</Value></Neq>", listGroupName[countAnd - 1].ToString());

for (int i = 0; i < countAnd  - 2; i++)

{

queryToReturn += @"</And>";

}

}

queryToReturn += @"<Neq><FieldRef Name='BelongsTo'/><Value Type='Integer'><UserID/></Value></Neq>";

//Close the And tag if needed

if (countAnd > 0)

{

queryToReturn += "</And>";

}

queryToReturn += "</Where>";

return queryToReturn;

}

Some explanations:

This function will do a check of all the groups in the collection, if the user is present in the group, a counter is incremented and the group name is saved in a list. Then the query is build based on those elements.

Hope this helps !

Christopher

Advertisements
This entry was posted in SharePoint 2007, SharePoint 2010, SharePoint 2013 and tagged , . Bookmark the permalink.

One Response to CAML Query – Show element not assigned to me or my groups

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