I need to get sAMAccountName by passing EmployeeId to the active directory.
Please help me.
I don't know what is the EmployeeId for you but here is how to access all the users and display some fields :
Domain domain = Domain.GetCurrentDomain();
var searchRoot = domain.GetDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("sAMAccountName");
search.PropertiesToLoad.Add("userPrincipalName");
search.PropertiesToLoad.Add("displayName");
SearchResultCollection results = search.FindAll();
if (results != null)
{
foreach(SearchResult result in results)
{
Console.WriteLine("{0} ({1}) sAMAccountName={2}",
result.Properties["displayName"].OfType<object>().FirstOrDefault(),
result.Properties["userPrincipalName"].OfType<object>().FirstOrDefault(),
result.Properties["sAMAccountName"].OfType<object>().FirstOrDefault());
}
}
To discover all the fields present on your schema you can use AdExplorer.
Try this (with many thanks to VirtualBlackFox)
string employeeId ="someEmployeeId";
Domain domain = Domain.GetCurrentDomain();
var searchRoot = domain.GetDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.PropertiesToLoad.Add("EmployeeID");
search.PropertiesToLoad.Add("sAMAccountName");
search.Filter = String.Format("(&(objectCategory=person)(EmployeeID={0}))", employeeId );
SearchResult searchResult =search.FindOne();
if (searchResult != null)
{
object o = searchResult.Properties["sAMAccountName"].OfType<object>().FirstOrDefault();
if (o != null)
{
string sAMAccountName= o.ToString();
}
}
Related
I am trying to query AD to get the list of users
The query is success, and I am getting 90 records as results, the problem is that I am expecting more over than 15000 records.
Before I go to the IT and check the right domain path, it would be great if I am sure that my code is not the issue.
Thank you for every much
Already tried changing the search page size
DataTable resultSet = new DataTable();
resultSet.Columns.Add(new DataColumn("mail", typeof (string)));
resultSet.Columns.Add(new DataColumn("username", typeof (string)));
resultSet.Columns.Add(new DataColumn("displayname", typeof (string)));
try
{
string DomainPath = "LDAP://MyDomain";
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("mail");
search.PageSize = 1001;
search.PropertiesToLoad.Add("displayname");//first name
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter < resultCol.Count; counter++)
{
result = resultCol[counter];
if (result.Properties.Contains("samaccountname") && result.Properties.Contains("mail") && result.Properties.Contains("displayname"))
{
var row = resultSet.NewRow();
resultSet.Rows.Add(row);
var Email = (String) result.Properties["mail"][0];
row["mail"] = Email;
var UserName = (String) result.Properties["samaccountname"][0];
row["username"] = UserName;
var DisplayName = (String) result.Properties["displayname"][0];
row["displayname"] = DisplayName;
row.AcceptChanges();
}
}
resultCol.Dispose();
}
}
catch (Exception ex)
{
App.Log.Write("Exception while read user from AD: " + ex.ToString());
}
return resultSet;
Expected over 15000 records getting 90 only
i am creating new user in Active Directory but after creating it when i am retrieving created user the fo llowing error is coming " An operations error occurred "
following is my code
private static DirectoryEntry GetUser(string userName)
{
var de = Utility.GetDirectoryObject();
var deSearch = new DirectorySearcher
{
SearchRoot = de,
Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))",
SearchScope = SearchScope.Subtree
};
var results = deSearch.FindOne();
if (results != null)
{
de = new DirectoryEntry(results.Path, Utility.AdUser, Utility.AdPassword, AuthenticationTypes.Secure);
return de;
}
return null;
}
try this :
var deSearch = new DirectorySearcher
{
SearchRoot = de,
Filter = $"(&(objectClass=person)(sAMAccountName={userName}))",
SearchScope = SearchScope.Subtree
};
I don't know if "nested" is the word for what I need, but here's the explanation:
I have a user, "John". "John" is member of the group "A". Group "B" has group "A" as a member.
So, transitively, "John" should also be member of the group "B".
When I retrieve the John's group, I only get "A", and not "B", doing it like this:
DirectorySearcher searcher = new DirectorySearcher();
DirectoryEntry rootEntry = new DirectoryEntry(_ldap, _loginName, _password, AuthenticationTypes.ReadonlyServer);
searcher.SearchRoot = rootEntry;
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = "(&(sAMAccountName=" + filter.Split('\\')[1] + ")(objectClass=user))";
searcher.PropertiesToLoad.Add("memberOf");
searcher.PropertiesToLoad.Add("displayname");
SearchResult sr = searcher.FindOne();
How can I achieve this?
Thank you!
I ended up using the "tokenGroups" property of the user, which seems to return all the groups the user is in, even the ones in which he is member transitively.
here's my code:
DirectorySearcher searcher = new DirectorySearcher();
DirectoryEntry rootEntry = new DirectoryEntry(_ldap, _loginName, _password, AuthenticationTypes.ReadonlyServer);
searcher.SearchRoot = rootEntry;
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = "(&(sAMAccountName=" + filter.Split('\\')[1] + ")(objectClass=user))";
searcher.PropertiesToLoad.Add("memberOf");
searcher.PropertiesToLoad.Add("displayname");
SearchResult sr = searcher.FindOne();
DirectoryEntry userDirectoryEntry = result.GetDirectoryEntry();
userDirectoryEntry.RefreshCache(new string[] { "tokenGroups" });
foreach (byte[] byteEntry in userDirectoryEntry.Properties["tokenGroups"])
{
if (CompareByteArrays(byteEntry, objectSid))
{
isMember = true;
break;
}
}
It's a mix of this and this link, where objectSid is the objectSID of the group which I find by name.
Thanks a lot for your help!
I want to assign all my User properties from active directory into a List< User > properties by using LINQ.
For that I have tried some code but I am not able to assign Manager attribute on List User Manager property.
Because , assign the Manager attribute value from Active directory we need to search the manager user on active directory and based on the search result we need to assign manager attribute value to List of User.Manager property.
Here is my Code,
public List< User > GetADUsers()
{
DirectorySearcher searcher = new DirectorySearcher(ADEntry);
searcher.Filter = "(&(objectClass=user)objectCategory=person)";
SearchResultCollection resultCol = searcher.FindAll();
return
(from serachresult in resultCol.OfType<SearchResult>()
let result = serachresult.GetDirectoryEntry()
result.Properties["sAMAccountName"].Value != null
select new User
{
GivenName = result.Properties.Contains("givenname") ?
Convert.ToString(result.Properties["givenname"][0]) : "",
SurName = result.Properties.Contains("sn") ?
Convert.ToString(result.Properties["sn"][0]) : "",
Location = result.Properties.Contains("physicalDeliveryOfficeName") ?
Convert.ToString(result.Properties["physicalDeliveryOfficeName"][0]) : "",
Manager= ?// Here I need to assign the manager attribute from active directory
}
).ToList();
}
By using below mentioned code, I am taking the manager attribute from Active Directory by using directory entry object. I want to place this code on above mentioned LINQ query
on Manager property. How can we achieve this inside of LINQ Select clause.
DirectoryEntry DomainRoot = AD.GetDirectoryEntry();
using (DirectorySearcher Search = new DirectorySearcher())
{
Search.SearchRoot = DomainRoot;
Search.Filter = "(&(distinguishedName=" +
Convert.ToString(result.Properties["manager"][0]) + "))";
SearchResult Result = Search.FindOne();
if (Result != null)
{
DirectoryEntry Manager = Result.GetDirectoryEntry();
//This Manager.Name value I have assign above mentioned LINQ
user.Manager = Manager.Name.Substring(3);
Manager.Close();
}
}
Please help me to assign the manager name on the LINQ query Manager property place! Thanks.
Try to move your manager evaluation to a new function that takes 'result' and returns Manager name.
And then call it from your link statement: Manager = GetManagerName(result)
public string GetManagerName(DirectoryEntry dirEntry)
{
DirectoryEntry DomainRoot = AD.GetDirectoryEntry();
using (DirectorySearcher search = new DirectorySearcher())
{
search.SearchRoot = DomainRoot;
search.Filter = "(&(distinguishedName=" + Convert.ToString(dirEntry.Properties["manager"][0]) + "))";
SearchResult result = search.FindOne();
if (result != null)
{
using (DirectoryEntry mgr = result.GetDirectoryEntry())
{
return mgr.Name.Substring(3);
}
}
return string.Empty;
}
}
I have checked the two other threads and even used code from one but it never populates a list. When I open up Active Directory Users and Computers and go to my Manager under Organization I see his list of direct reports.
What I am trying to do is gain access to that list through code. Nothing I have found so far seems to work.
public void GetDirectoryEntry(string adUserName)
{
DirectoryEntry de = new DirectoryEntry("LDAP://server.server.com");
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + adUserName + "))";
ds.SearchScope = SearchScope.Subtree;
SearchResult rs = ds.FindOne();
string distinguishedName = rs.Properties["distinguishedName"][0].ToString();
string department = rs.Properties["department"][0].ToString();
string manager = rs.Properties["manager"][0].ToString();
//string temp3 = rs.Properties["Reports"][0].ToString();
}
I have tried using Reports and directReports and neither work both error out.
This method loads up the logged in user or any user I pass into it. I can access all of their properties but I cannot seem to get access to their direct reports.
What am I missing?
Found the answer:
foreach (string objProperty in rs.Properties["DirectReports"])
{
isManager = true;
string emp = objProperty.ToString();
string[] setp = new string[1];
setp[0] = "DC"; //If your users are in a OU use OU
emp = emp.Split(setp, StringSplitOptions.None)[0];
emp = emp.Replace("CN=", "");
emp = emp.TrimEnd(',');
emp = emp.Replace("\\, ", ", ");
emp = emp.Split(',')[0];
//emps.Add(emp);
}
foreach (string objProperty in rs.Properties["DirectReports"])
{
isManager = true;
string emp = objProperty.ToString();
string[] setp = new string[1];
setp[0] = "DC"; //If your users are in a OU use OU
emp = emp.Split(setp, StringSplitOptions.None)[0];
emp = emp.Replace("CN=", "");
emp = emp.TrimEnd(',');
emp = emp.Replace("\\, ", ", ");
emp = emp.Split(',')[0];
//emps.Add(emp);
}