Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Friday, December 02, 2011

Programmatically get all users and groups using client object model.


The code below shows you how to query users and groups using client object model. The client
OM includes the GroupCollection,Group,UserCollection,and User objects to make working with
users and groups easier.The client OM also has access to built – in groups such as the owners,
members, and visitors groups. You can
access these off your context object using the
AssociatedOwnerGroup,AssociatedMemberGroup,and AssociatedVisitorGroup properties,
which return a Group object.

function GetUsersGroups()
{

ClientContext context = new Microsoft.SharePoint.Client.ClientContext(“http://SPSite”);

GroupCollection groupCollection = context.Web.SiteGroups;
context.Load(groupCollection,
groups = > groups.Include(
group = > group.Users));

context.ExecuteQuery();

foreach (Group group in groupCollection)
{
UserCollection userCollection = group.Users;

foreach (User user in userCollection)
{
MessageBox.Show(“User Name: ” + user.Title + ” Email: ” +
user.Email + ” Login: ” + user.LoginName);
}
}
//Iterate the owners group
Group ownerGroup = context.Web.AssociatedOwnerGroup;
context.Load(ownerGroup);
context.Load(ownerGroup.Users);
context.ExecuteQuery();
foreach (User ownerUser in ownerGroup.Users)
{
MessageBox.Show(“User Name: ” + ownerUser.Title + ” Email: ” +
ownerUser.Email + ” Login: ” + ownerUser.LoginName);
}
context.Dispose();
}

2 comments:

  1. i am trying to use this code it is throwing some errors.

    ReplyDelete
  2. i want to check particular user exist in which site collection & which group using client object model. help me on this.

    ReplyDelete