Get all users email from a group using Active Directory c# - c#

I need all email address of a particular group. Please help me
string filter1 = string.Format("(&(objectClass=group)(cn={0}))", "groupname");
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = filter1;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("member");
SearchResult res = searcher.FindOne();
ArrayList userNames = new ArrayList();
if (res != null)
{
for (int counter = 0; counter <res.Properties["member"].Count; counter++)
{
string user = (string)res.Properties["member"][counter];
userNames.Add(user);
}
}
I am getting uesr name and other details but not get email. Please tell me the way to find email address of each user directly.

You can try with this code - based on PrincipalContext class
var username = "username";
var domain = "domain";
var emailAddresses = new List<string>();
var principalContext = new PrincipalContext(ContextType.Domain, domain);
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, username);
// Add the "mail" entry
emailAddresses.Add(userPrincipal.EmailAddress);
Link : http://msdn.microsoft.com/fr-fr/library/bb344891(v=vs.90).aspx

Related

Iterate groups of user in AD and save them in list

I have a procedure that retrieves the user node out of AD:
public static void ConnectActiveDirectory()
{
List<string> lstGroups = new List<string>();
DirectoryEntry entry;
string user = "username";
string server = ConfigurationManager.AppSettings["ActiveDirectory.Server"];
entry = new DirectoryEntry(#"LDAP://" + server);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "sAMAccountName=" + user;
searcher.PropertiesToLoad.Add("MemberOf");
SearchResult result = searcher.FindOne();
}
The idea is to save all the groups in the list of strings without doing something like:
foreach (ResultPropertyValueCollection s in result.Properties.Values)
{
string groupname = null;
for (int i = 0; i < s.Count; i++)
{
dn = s[i].ToString();
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
groupname = dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1);
lstGroups.Add(groupname);
}
}
Is there any method that I can use in 'DirectorySearcher' Class?
Also, is there any way to delete the first Hashtable? the adspath one from the SearchResult object.
Instead of parsing the distinguished name by yourself, you can use the DirectoryEntry object to ask AD for the display name. For example:
var directoryEntry = new DirectoryEntry(#"LDAP://address");
var directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = "samaccountname=user";
directorySearcher.PropertiesToLoad.Add("memberOf");
var result = directorySearcher.FindOne();
foreach (var i in result.Properties["memberOf"])
{
var group = new DirectoryEntry(#"LDAP://" + i);
Console.WriteLine(group.Properties["DisplayName"]);
}

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;

Can i get Active directory users info such as email, Telephone & Manager using UserPrinciple

I have the following code inside my asp.net mvc5 web application:-
List<DomainContext> results = new List<DomainContext>();
using (var context = new PrincipalContext(ContextType.Domain, ADServerName, ADusername, ADpassword))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
var searchResults = searcher.FindAll();
foreach (Principal p in searchResults)
{
{
DomainContext dc = new DomainContext();
dc.DisplayName = p.DisplayName;
dc.UserPrincipalName = p.UserPrincipalName;
dc.Name = p.Name;
dc.SamAccountName = p.SamAccountName ;
dc.DistinguishedName = p.DistinguishedName;
results.Add(dc);
i am able to get these AD info such as Display Name, Name, etc but can i also get these info using the above code:-
email address.
Telephone.
Manager
Thanks?
You need the username, first, last and the smtp.
If you have them, here's the code:
var adService = new DirectorySearcher(new DirectoryEntry());
adService.Filter = "(&(objectClass=user)(anr=LOGON))";
adService.PropertiesToLoad.Add("FirstName");
adService.PropertiesToLoad.Add("LastName");
adService.PropertiesToLoad.Add("SMTP");
return adService.FindOne();
Below I have updated your existing code to use a UserPrincipal.
List<UserPrincipal> results = new List<UserPrincipal>();
using (var context = new PrincipalContext(ContextType.Domain, ADServerName, ADusername, ADpassword))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
var searchResults = searcher.FindAll();
foreach (Principal p in searchResults)
{
{
UserPrincipal userPrincipal = p as UserPrincipal;
if (userPrincipal != null)
results.Add(userPrincipal);
And here I have added code to show you how to get the additional properties you need at a higher level.
//Get information you need from UserPrincipal..
var matchingUsers = results.Where(p => p.DisplayName.ToLower() == "bob");
foreach (var matchedUser in matchingUsers)
{
string telephone = matchedUser.VoiceTelephoneNumber;
string email = matchedUser.EmailAddress;
var directoryEntry = matchedUser.GetUNderlyingObject() as DirectoryEntry;
string manager = directoryEntry.Properties["manager"] as string;
}

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();

How can I obtain the OU of the logged in user in C#?

I'm looking for a method to obtain the current logged in user's full Active Direcory LDAP path. e.g.
LDAP://CN=john.smith,OU=UK,OU=Sales,DC=Company,DC=local
Query the LDAP directory (e.g. the AD) with this filter:
(&(objectCategory=user)(sAMAccountName=<user-logon-name-here>))
The DN of the object returned is the thing you are looking for.
Something like this:
DirectorySearcher ds = new DirectorySearcher();
string userName = WindowsIdentity.GetCurrent().Name;
string userFilter = "(&(objectCategory=user)(sAMAccountName={0}))";
ds.SearchScope = SearchScope.Subtree;
ds.PropertiesToLoad.Add("distinguishedName");
ds.PageSize = 1;
ds.ServerPageTimeLimit = TimeSpan.FromSeconds(2);
ds.Filter = string.Format(userFilter, userName);
SearchResult sr = ds.FindOne();
// now do something with sr.Properties["distinguishedName"][0]

Categories

Resources