Get all groups of a User in Sharepoint programmatically in C# - c#

What is the best way to access all groups of a SPUser including the Active Directory groups?
SPUser u = someWeb.EnsureUSer(...);
//Only gives SharePoint groups
SPGroupCollection coll = user.Groups;
//Also gives only SharePoint groups
SPGroupCollection groupsonSite = someSPSite.rootWeb.siteGroups
Is there a way to access all groups a user is in, including AD groups?

If you need all users from current site collection , you can access it from hidden list UserInformationList
The User Information List can be accessed (Only if you’re admin) via the browser by navigating to /_catalogs/users/simple.aspx
Read more here :
https://zimmergren.net/sharepoints-hidden-user-list-user-information-list/
From AD :
DirectoryEntry myLdapConnection = new DirectoryEntry("LDAP://YouDomainName");
DirectorySearcher search = new DirectorySearcher(myLdapConnection) { Filter = ("(objectClass=user)") };
search.CacheResults = true;
SearchResultCollection allResults = search.FindAll();
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("UserID");
resultsTable.Columns.Add("EmailID");
foreach (SearchResult searchResult in allResults)
{
MembershipUser myUser = Membership.GetAllUsers()[searchResult.Properties["sAMAccountName"][0].ToString()];
if (myUser == null)
{
DataRow dr = resultsTable.NewRow();
dr["UserID"] = searchResult.Properties["sAMAccountName"][0].ToString();
if (searchResult.Properties["mail"].Count > 0)
{
dr["EmailID"] = searchResult.Properties["mail"][0].ToString();
}
else
{
dr["EmailID"] = "";
}
resultsTable.Rows.Add(dr);
}
else
{ }
}
http://www.dotnetcodesg.com/Article/UploadFile/2/223/Get%20List%20of%20Active%20Directory%20Users%20in%20ASP.NET%20Csharp.aspx

Related

How to get a list of all objects under organization unit from LDAP?

How can I get a list of every user and/or Group that is located inside of an LDAP organization unit?
I am trying to query my LDAP server using c#. I want to get a list of all my distribution lists. All of my distribution lists are grouped under an organization-unit (OU) called "General Distributions." How can I get a list of all members under the "General Distributions" OU?
Below is the code I am using to query the LDAP service which is returning no results.
try
{
DirectoryEntry objADAM = new DirectoryEntry("LDAP://my_domain.com", "user#my_domain.com", "password");
DirectorySearcher objSearchADAM = new DirectorySearcher(objADAM);
objSearchADAM.Filter = "(&(OU=General Distributions,DC=my_domain,DC=com)";
objSearchADAM.SearchScope = SearchScope.Subtree;
SearchResultCollection objSearchResults = objSearchADAM.FindAll();
// Binding path.
List<string> result = new List<string>();
if (objSearchResults.Count != 0)
{
foreach (SearchResult objResult in objSearchResults)
{
DirectoryEntry objGroupEntry = objResult.GetDirectoryEntry();
result.Add(objGroupEntry.Name);
}
return result;
}
throw new Exception("No result found");
}
catch (Exception e)
{
throw e;
}
I know this question is a bit old, but the answer is fairly simple. Use the OU itself as the DirectoryEntry you're using as the SearchRoot:
DirectoryEntry objADAM = new DirectoryEntry(
"LDAP://my_domain.com/OU=General Distributions,DC=my_domain,DC=com",
"user#my_domain.com", "password");
DirectorySearcher objSearchADAM = new DirectorySearcher(objADAM);
objSearchADAM.Filter = "(|(objectClass=user)(objectClass=group))"; //only get users and groups
objSearchADAM.SearchScope = SearchScope.Subtree;
SearchResultCollection objSearchResults = objSearchADAM.FindAll();

Can I get more than 1000 records from a PrincipalSearcher?

I am trying to get all users from Active Directory using code:
PrincipalContext ad = new PrincipalContext(contextType, adserviceName, adContext, ContextOptions.SimpleBind, username, password);
UserPrincipal u = new UserPrincipal(ad) {Name = "*"};
PrincipalSearcher search = new PrincipalSearcher { QueryFilter = u };
foreach (var principal in search.FindAll())
{
//do something
}
But it returns only first 1000 rows. How I can retrieve All users and without using DirectorySearcher.
Thanks.
I don't think you will be able to do that without using DirectorySearcher.
Code snippet -
// set the PageSize on the underlying DirectorySearcher to get all entries
((DirectorySearcher)search.GetUnderlyingSearcher()).PageSize = 1000;
Also see If an OU contains 3000 users, how to use DirectorySearcher to find all of them?
You need to get the underlying DirectorySearcher and set the PageSize property on it:
using (PrincipalContext ad = new PrincipalContext(contextType, adserviceName, adContext, ContextOptions.SimpleBind, username, password))
{
UserPrincipal u = new UserPrincipal(ad) {Name = "*"};
PrincipalSearcher search = new PrincipalSearcher { QueryFilter = u };
// get the underlying "DirectorySearcher"
DirectorySearcher ds = search.GetUnderlyingSearcher() as DirectorySearcher;
if(ds != null)
{
// set the PageSize, enabling paged searches
ds.PageSize = 500;
}
foreach (var principal in search.FindAll())
{
//do something
}
}
You can:
((DirectorySearcher)myPrincipalSearcher.GetUnderlyingSearcher()).SizeLimit = 20;

In Active Directory, how do I find all groups I'm the secretary for?

We use the secretary property of Active Directory, which is a multivalued DN property. I want to efficiently find all the groups for which a given user is a listed secretary. What is the best way to perform this query in C#/.NET?
This code will return a list of sAMAccountNames of groups in context's OU that include distinguishedName as one of the secretaries listed:
var filter = "(&(objectClass=group)(secretary=" + distinguishedName + "))";
PrincipalContext context = new PrincipalContext(...); // place to search from
var up = new GroupPrincipal(context);
var list = new List<string>();
using (var searcher = new PrincipalSearcher(up))
{
var ds = searcher.GetUnderlyingSearcher() as DirectorySearcher;
// if you only want to search in a single OU (as defined by 'context')
ds.SearchScope = SearchScope.OneLevel;
ds.Filter = filter;
ds.PropertiesToLoad.Add("sAMAccountName");
var results = ds.FindAll();
foreach (SearchResult r in results)
{
var name = r.GetDirectoryEntry().Properties["sAMAccountName"].Value as string;
list.Add(name);
}
}

How I can built a QBE for Active Directory Users with activate users,email or telephonenumber and a username?

I work with the Active Directory. I write a method how I can get all Users from the Active Directory with a filter and list the Users in a ArrayList for my DropDownList.
The Code:
private ArrayList GetReceiverList(string Domain)
{
ArrayList List = new ArrayList();
DirectoryEntry Entry = new DirectoryEntry(Domain);
string filter = "(&(objectClass=user)(objectCategory=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(sn=*)(|(telephoneNumber=*)(mail=*))(cn=*))";
DirectorySearcher Searcher = new DirectorySearcher(Entry, filter);
foreach (SearchResult usr in Searcher.FindAll())
{
List.Add(GetLdapProperty(usr, "displayName"));
}
return List;
}
This work and I want now do use System.DirectoryServices.AccountManagement and for this I write a Method and this works, too. But I want do use the filter how in my first Method. How I can do this?
the code of my new method:
public static ArrayList GetAllActiveDirectoryUsersByDisplayName(string dc)
{
ArrayList list = new ArrayList();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);
UserPrincipal u = new UserPrincipal(ctx);
u.Surname = "*";
PrincipalSearcher ps = new PrincipalSearcher(u);
PrincipalSearchResult<Principal> results = ps.FindAll();
foreach (UserPrincipal usr in results)
{
list.Add(usr.Name);
}
list.Sort();
return list;
}
Update:
I want di use this filter in my new method :
string filter = "(&(objectClass=user)(objectCategory=user)(!userAccountControl:1.2.840.113556.1.4.803:=2)(sn=*)(|(telephoneNumber=*)(mail=*))(cn=*))";

Query PrincipalSearcher for containing multiple strings

I want to be able to query the active directory give a list of all groups containing certain words like Users or Administrators below is what i've got so far
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
qbeGroup.DisplayName = "Administrators";
qbeGroup.DisplayName = "Users";
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
return srch.FindAll().Select(g => g.Name).ToArray();
This code doesn't even seem to filter out the the Group names that is not Administrators or Users. But anyway what I can't figure out is how to query if the group name contains? and not if group name is equal to and how to do this of multiple strings.
I can do the same thing using DirectoryEntry so I put it here for referance
var groups = new List<string>();
var path = string.Format("LDAP://CN=Users,DC=company,DC=com");
var computerEntry = new DirectoryEntry(path);
if (computerEntry != null)
{
using (computerEntry)
{
var userNames =
from DirectoryEntry childEntry
in computerEntry.Children
where childEntry.SchemaClassName == "Group"
select childEntry.Name;
foreach (var name in userNames)
{
if (name.Contains("Administrators") || name.Contains("Users"))
{
groups.Add(name);
}
}
}
}
return groups.ToArray();
I did this by using a foreach loop But the following code still doesn't answer my question on how to do it for Principalsearcher
var groups = new List<string>();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
foreach (var group in srch.FindAll())
{
if (group.Name.Contains("Administrators") || group.Name.Contains("Users"))
{
groups.Add(group.Name);
}
}
return groups.ToArray();

Categories

Resources