get users by group in sharepoint - c#

can anyone show me how to get the users within a certain group using sharepoint?
so i have a list that contains users and or groups. i want to retrieve all users in that list. is there a way to differentiate between whether the list item is a group or user. if its a group, i need to get all the users within that group.
im using c#, and im trying to do thins by making it a console application.
im new to sharepoint and im really jumping into the deep end of the pool here, any help would be highly appreciated.
cheers..

The first thing you need to know is that when you have a list with a User / Group field you must be aware of its type. When you have one user or group within the item value, the field type is SPFieldUserValue. However, if the field has multiple user / group selection the field type is SPFieldUserValueCollection.
I'll assume that your field allows a single user / group selection and you already has the following objects:
SPSite site;
SPWeb web;
SPListItem item;
Now, we'll check the field value for a user / group and retrieve a list of users, independant of which kind it is (the field's name is "Users").
SPFieldUserValue usersField = new SPFieldUserValue(mainWeb, item["Users"].ToString());
bool isUser = SPUtility.IsLoginValid(site, usersField.User.LoginName);
List<SPUser> users = new List<SPUser>();
if (isUser)
{
// add a single user to the list
users.Add(usersField.User);
}
else
{
SPGroup group = web.Groups.GetByID(usersField.LookupId);
foreach (SPUser user in group.Users)
{
// add all the group users to the list
users.Add(user.User);
}
}
I hope it helps you.
Tks,
Pedro José Batista

note: an SPUser object can also be an AD Group (that is to say, an SPUser object might exist for "DOMAIN\Domain Users"... which is why the SPUser object also contains the property IsDomainGroup.
From this information you can start to traverse through AD groups using the SPPrincipalInfo objects... however it's not always pleasant.
One thing worth keeping in mind is that the SPGroup object includes the ContainsCurrentUser property which can traverse AD groups... this assumes you've got an SPGroup object to work from, however.
Enjoy.
-Scott

private bool IsMember()
{
bool isMember;
SPSite site = new SPSite(SiteURL);
SPWeb web = site.OpenWeb();
isMember = web.IsCurrentUserMemberOfGroup(web.Groups["GroupName"].ID);
web.Close();
site.Close();
return isMember;
}

This is better to use web.SiteGroups instead of web.Groups as a group might be inherited by that site.

Related

c# LDAP membership enumeration

here is my problem: I need to enumerate the members of certain groups in our Active Directory. The complication is that the DN of the objects that are in the 'membersOf' property of the groups do not contain the identifier I need. Specifically, the CN of the user object is useless to me, only a property of the user object (the userID) is useful.
So three approaches comes to mind:
I can first enumerate the group to get a list of DN's in the group, and then do a lookup on each user DN to find out their userID
I can enumerate every user in the AD, grabbing their userID & their membersOf collection, and then check afterwards if they have the right memberships.
I could grab a list of all users with their CN's and userID's, and then enumerate the groups to get the member CN's. Then I could join the lists on the original list to get my list of member userID's.
Some problems immediately appear - option 1) will generate an extremely large number of subqueries and congest network traffic (undesirable), and option 2) pulls a HUGE amount of data from AD (something like 30mb). Option 3) is middle of the road - but it still pulls quite a bit of data and has multiple queries. Is there another option for how to do this which does not have these problems?
I am doing this in c# using the System.DirectoryServices tools.
Thank you in advance for your time and consideration.
Maybe there's an option #4, too:
you could set up a DirectorySearcher which enumerates users
you could define memberOf=....... as one of your search criteria
you can define what attributes you need from the directory searcher very easily
If this works (and I'm under the impression I got this to work before - but it's been quite a while!) then you could do one, single fairly focused search and automatically get your information that you need.
Try something like this:
// define the "root" of your search (where to begin)
DirectoryEntry searchRoot = new DirectoryEntry("LDAP://cn=users,dc=yourcompany,dc=com");
DirectorySearcher searcher = new DirectorySearcher(searchRoot);
// set properties
searcher.SearchScope = SearchScope.Subtree;
// define search filter
searcher.Filter = "(&(objectCategory=Person)(memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))";
// define attributes to load
searcher.PropertiesToLoad.Add("userid");
... add more if needed .....
foreach(SearchResult entry in searcher.FindAll())
{
string userid = entry.Properties["userid"][0].ToString();
}

Using LDAP/AD to find mailing lists user is subscribed to

I am currently looking into getting a list of mailing distribution lists that a user is subscribed to. I have never used Active Directories before, and after reading into various answers here and on MSDN, I'm very confused.
I have my query set up like this:
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("LDAP://CN={0},OU=<value here>,DC=<value>...", userName);
search.SearchScope = SearchScope.Subtree;
search.PropertiesToLoad.Add("memberOf");
SearchResult result = search.FindOne();
if(result != null)
{
// Do stuff here
}
Here are my questions:
What does the SearchRoot property within DirectorySearcher do? Do I need to set that up to have this query return a value?
Do I need to set the SearchScope value to be Subtree is I list only 1 OU as the base OU and have it search all sub OUs?
Is the string sent in to PropertiesToLoad.Add() generic, or does that need to be a string that is defined by my company?
Thanks for the advice!
(1) What does the SearchRoot property within DirectorySearcher do? Do I need to set that up to have this query return a value?
It defines the starting point of your search; compare it to a file system - it defines the starting directory from which you start your search. You'll be looking inside the SearchRoot and possibly you'll be looking at all its child containers. It's just used to reduce the possible number of containers to search for something
(2) Do I need to set the SearchScope value to be Subtree is I list only 1 OU as the base OU and have it search all sub OUs?
If you want to search OU or other container under your SearchRoot - then yes, you have to search the SearchScope.Subtree - otherwise the search will only look at your SearchRoot container itself (at all the objects like users, computers, groups inside that container - but not at sub-containers).
(3) Is the string sent in to PropertiesToLoad.Add() generic, or does that need to be a string that is defined by my company?
Those are LDAP attribute names - these can be both, the standard ones as well as possible custom extensions your company might have defined and installed. Here's a really nice list of all AD attributes as an Excel sheet (several, actually).

Using System.DirectoryServices.xxx is it possible to determine what AD Groups a user can manage?

I'm attempting to load a list of groups for a user and wanting to show if they have authority to edit group membership or not.
What in the Active Directory indicates that a user can edit the members of a group and how can i look this up using System.DirectoryServices in 3.5+
Im using the following to obtain the groups for a user
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, userName);
if ( user != null)
{
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
foreach(Principal p in groups)
{
if ( p is GroupPrincipal)
...
}
}
Any help appreciated
This is very time consuming, due to the way that permissions are managed on objects. A similar question might be, "How do I list every folder on the domain that an account can write data to". The reason this is time consuming is because each object holds it's own Access Control List (ACL).
I'm fairly sure the only way to find out every group you can manage would be to check every group and see what the permissions are on that group, then compare your group membership to the permissions on the group.
In Active Directory, how do I determine type of ActiveDirectoryAccessRule? has some code which may prove helpful if this is the route you end up going.
A saner approach might be to use the "Delegate" field to delegate permissions to certain groups, this field could be easily queried using LDAP, or let the person pick any group and then check the group's permissions after it's been selected.

Generic questions about best practice while developing in sharepoint

I have a few generic questions about what are the best practices for SharePoint(2010).
I am currently implementing a feature that requires me to fetch information from a list. I am not quite sure on how to manage these information. I created a class that helps me manage theses information (User.cs). I have a getter in the class that currently searches for a value in a specific list. How should i handle the value ? Should i keep it in a member and refresh only when its subject to changes or should i refresh the value from the list each time i get it ?
private void doesUserHasActivities(){
using(SPSite site = new SPSite("http://vmsharepoint2010/")){
using(SPWeb web = site.openWeb("http://vmsharepoint2010/")){
SPList list = web.list["Users"];
SPListItem user;
/*Information values is refresh each time its accessed, is this bad ?*/
for(int i=0; i < list.items.length; i++){
user = list.item[i];
string accName = user["Acc_Name"];
if(accName == this.providedAccountname){//providedAccountname from a TextBox
//found the user i wanted into the list
//look if the list has data
bool hasActivities = user["Activities"] != null;
}
}
}
}
}
Also, is there other ways to access specific data, in this case the activities list without looping through each rows trying to match the correct user and then looking up the values in the activities list ?
Can i store the row itself as a member for my meta data ? Will my reference still point to the row of the user list i want to if another user is added ?
You'll need to learn CAML and perform a CAML query.
Create an SPQuery object. Set it's Query property to be what you need it to be, then use list.getItems(SPQuery query) to get just the items that match your query.
You can figure out the CAML for it yourself; you'll need to learn it if you want to deal with SharePoint code at all. There is lots of information on basic syntax, and tools for helping auto-generate it based on more user friendly syntax.
The items won't update dynamically when items are added to the list or updated in the list; you will need to re-run the query.

SPWeb.Groups vs SPWeb.AssociatedGroups

I've seen three types of group properties for an SPWeb object - Groups, SiteGroups, AssociatedGroups.
I understand that SiteGroups will fetch all the groups in the current site collection. But what is the difference between Groups and AssociatedGroups. MSDN definition says that Groups will get all the 'cross-site'(!) groups for that web site. AssociatedGroups are fairly easily to understand just from the very name.
So what does Groups return? Can somebody explain me with an example?
Groups return all groups which have security roles assigned to the current site.
AssociatedGroups return all groups visible in the left menu of the People and Group page. Those groups may not have access to the current site (if the security settings do not inherit from parent site). In this case, some of them will not be listed in the Groups property.
To view the difference, in a subsite, create a new group without giving any permission. The group will be visible in the AssociatedGroups and Left menu, but will not be listed in Groups or Site Permissions page.
I believe msdn has the answer
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.sitegroups.aspx
Gets a collection that contains all the groups in the site collection.
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.groups.aspx
Gets a collection that contains all the groups for the website. The following code example uses the Groups property to return the collection of groups for a specified site in the current site collection.
Which means, the SPGroup has been used in (ie assigned a permission in) the SPWeb somewhere.

Categories

Resources