I am using the LDAP for retrieving the hierarchy in my organisation. Under the property directreports I am getting all the names of the employees reporting under me. But I want to get their unique Identification (may be some employee id). How can I do that?
You can try this-
Add System.DirectoryServices.AccountManagement references in your project and import the namespaces.
var listOfDirectReportsNames = // Get the list of all the directreports user names and store in list- List<string>();
var pc = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, Environment.UserDomainName);
foreach (string name in listOfDirectReportsNames)
{
var up = new System.DirectoryServices.AccountManagement.UserPrincipal(pc);
up.Name = name; //to test this, pass the exact LDAP Name/DisplayName/GivenName of any user
System.DirectoryServices.AccountManagement.PrincipalSearcher searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher(up);
var res = searcher.FindOne();
string empID = ((System.DirectoryServices.AccountManagement.UserPrincipal)res).EmployeeId;//here you will get employee ID
up.Dispose();
}
Related
I want to read Parent-GUID attribute from ActiveDirectory.
I have tried below code to read all attributes of AD object from ActiveDirectory.
Code
var dirEntry = new DirectoryEntry(directoryEntryPath);
var directorySearcher = new DirectorySearcher(dirEntry, filter)
{
CacheResults = false,
Tombstone = true,
};
var searchResult = directorySearcher.FindAll(); // get mutiple AD Objects
foreach (SearchResult search in searchResult)
{
foreach (DictionaryEntry prop in search.Properties) // here I get all attributes values But not able to find parent-GUID attribute
{
}
}
Using above code I am able to get all properties of AD Object but I am not able to get value of Parent-GUID attribute.
According to https://learn.microsoft.com/en-us/windows/desktop/adschema/a-parentguid this is a constructed attribute. This means it won't be included in search results. The docs also imply it's there to support DirSync which tells me that it might not be available outside of a DirSync search.
Do you mean something like that?:
string path = "CN=someone,OU=yourOrganizationalUnit,DC=example,DC=com";
DirectoryEntry root = new DirectoryEntry(path);
root.Parent.Guid.ToString(); // this will display you the GUID from the parent of your path
Hope this is what you meant!
Cheers,
ov4rlrd
var searchResult = directorySearcher.FindAll();
foreach(SearchResult search in searchResult)
{
DirectoryEntry de = search.GetDirectoryEntry();
Guid ParentGUID = new Guid((byte[])de.Parent.Properties["objectGUID"][0]);
...
}
I have been searching around for a solution on getting both users and contacts from a group in Active Directory, but cant find one.
I understand that I cant get contacts the same way as users because they are not security principals?
I use this code to get all users in my group, is it possible to extend this to retrieve name, and mobile number from contacts? Or do I need to write something new?
var context = new PrincipalContext(ContextType.Domain, "MY_DOMAIN");
using (var searcher = new PrincipalSearcher())
{
var groupName = "MY_GROUP";
var sp = new GroupPrincipal(context, groupName);
searcher.QueryFilter = sp;
var group = searcher.FindOne() as GroupPrincipal;
if (group == null)
Console.WriteLine("Invalid Group Name: {0}", groupName);
foreach (var f in group.GetMembers())
{
var principal = f as UserPrincipal;
if (principal == null || string.IsNullOrEmpty(principal.Name))
continue;
DirectoryEntry entry = (principal.GetUnderlyingObject() as DirectoryEntry);
DirectorySearcher entrySearch = new DirectorySearcher(entry);
entrySearch.PropertiesToLoad.Add("mobile");
entrySearch.PropertiesToLoad.Add("sAMAccountName");
entrySearch.PropertiesToLoad.Add("name");
SearchResultCollection results = entrySearch.FindAll();
ResultPropertyCollection rpc = results[0].Properties;
foreach (string rp in rpc.PropertyNames)
{
if (rp == "mobile")
Console.WriteLine(rpc["mobile"][0].ToString());
if(rp == "sAMAccountName")
Console.WriteLine(rpc["sAMAccountName"][0].ToString());
}
You cannot use the System.DirectoryServices.AccountManagement namespace to query contact information from Active Directory because as you point out, they are not security principles. You'll need to read and parse the member property of the group directly from the group's DirectoryEntry. This will be a list of distinguished names of all the objects which are a member of the group. There's no way to know from this what kind of object they are so you'll need to query AD for each to find out.
You have all the code needed to accomplish this already in what you posted, just add the member property to the load list and then loop though it loading new DirectoryEntry objects. The objectClass property will tell you if it's a user, group or contact.
I am accessing SharePoint List data via WCF and listdata.svc
One of my lists called Tasks has a field named 'AssignedTo'. When I loop through the list items, the AssignedTo field returns a UserInformationListItem rather than a string value.
How do I get the username of the person to which the task is assigned? It should come from the UserInformationList, but I can't figure out how to get it.
Here is my code:
SpIMDLists.InformationManagementDivisionDataContext dc = new SpIMDLists.InformationManagementDivisionDataContext(new Uri("https://myurl/SiteDirectory/IMD/_vti_bin/ListData.svc/"));
dc.Credentials = System.Net.CredentialCache.DefaultCredentials;
var source = dc.Tasks;
foreach (var task in source)
{
string taskTitle = task.Title;
string taskDesc = task.TaskDescription;
string taskDueDate = task.DueDate.ToString();
string taskStartDate = task.StartDate.ToString();
string taskStatusValue = task.StatusValue;
string taskOutcome = task.TaskOutcome;
string taskAssignedTo ="";
System.Collections.ObjectModel.Collection<SpIMDLists.UserInformationListItem> assignedTo = task.AssignedTo;
}
If the AssignedTo field is a Person or Group field, it holds the SharePoint ID of the user or group. For example:
<d:AssignedToId m:type="Edm.Int32">8</d:AssignedToId>
In this case, the SharePoint ID of the user is 8. To get the users name, you'll have to look at the UserInformationList located at /_vti_bin/ListData.svc/UserInformationList. You can either get all the users in the UserInformationList and store it in an array, or you can lookup a specific user by creating the URL as follows (using the User ID of 8 from our example): /_vti_bin/ListData.svc/UserInformationList(8)
If you want to see this user in your browser, you can do so at the following URL: /_layouts/userdisp.aspx?ID=8.
Alternatively, you can use the following endpoint to get the same information: _vti_bin/ListData.svc/Tasks(1)/AssignedTo
Where 1 in this example, is the ID of the task. Your approach depends on your needs.
More information:
http://yetanothersharepointblog.wordpress.com/2012/12/11/working-with-sharepoint-lookup-columns-in-knockout-js/
http://social.technet.microsoft.com/Forums/office/en-US/8e6badbf-a270-4b8e-9a62-c9f7be44ada2/rest-api-how-to-get-author-name?forum=sharepointdevelopmentprevious
UPDATE: Appreciate the input. It led me to the following solution. This is how I was able to get the user's name. AssignedTo is a complex field, so I had to use Expand in order to populate it. Then I just looped through the AssignedTo collection to get the user (in this case the tasks are assigned to 1 user only).
Here is my new working code:
SpIMDLists.InformationManagementDivisionDataContext dc = new SpIMDLists.InformationManagementDivisionDataContext(new Uri("https://myurl/SiteDirectory/IMD/_vti_bin/ListData.svc/"));
dc.Credentials = System.Net.CredentialCache.DefaultCredentials;
var source = dc.Tasks;
foreach (var task in source.Expand("AssignedTo")
{
string taskTitle = task.Title;
string taskDesc = task.TaskDescription;
string taskDueDate = task.DueDate.ToString();
string taskStartDate = task.StartDate.ToString();
string taskStatusValue = task.StatusValue;
string taskOutcome = task.TaskOutcome;
var assignedTo = task.AssignedTo;
foreach (var usr in assignedTo)
{
string taskAssignedTo = usr.Name;
}
}
I'm trying to get Home Directory attribute value from active directory..
I used the following code:
public static void GetExchangeServerByWwidLdap(string wwid)
{
var exchange = string.Empty;
using (var ds = new DirectorySearcher())
{
ds.SearchRoot = new DirectoryEntry("GC:something");
ds.SearchScope = SearchScope.Subtree;
//construct search filter
string filter = "(&(objectclass=user)(objectcategory=person)";
filter += "(employeeid=" + wwid + "))";
ds.Filter = filter;
string[] requiredProperties = new string[] { "homeDirectory", "homemta" };
foreach (String property in requiredProperties)
ds.PropertiesToLoad.Add(property);
SearchResult result = ds.FindOne();
}
}
When I check result object data, I'm seeing only 2 values: "homemta" and "adspath".
Where is the "homeDirectory" value?
I entered AD website and searched the same values for same users - through the website I can see the all the data I searched for so I assuming that I have code issue somewhere.
What am I doing wrong?
You're trying to retrieve homeDirectory from global catalog.
It’s not there.
You can e.g. bind to the user by ADsPath property (i.e. “LDAP://…” string), then query the homeDirectory attribute of that user.
Or, if you only have a single domain, you can search within that domain instead of searching the GC. In this case you'll be able to retrieve all the properties you want.
What is the easiest way to query the Active directory to get a strings list of departments names. Example: "Finance", "Marketing", "IT",etc.
My case is an active directory for an enterprise with well over 3000 users.
Assuming that you just want to get a list of objects with the Department attribute returned you could use a DirectorySearcher in the System.DirectoryServices namespace.
Then your filter would be something like:
ds.Filter = "(objectClass=user)";
and you could then tell the searcher to just load the department attribute:
ds.PropertiesToLoad.Add("department");
Then enumerate throught the result set:
SearchResultCollection results = ds.FindAll();
Then add each department property to a Dictionary to get all the unique values
foreach (SearchResult result in results)
{
string dept = String.Empty;
DirectoryEntry de = result.GetDirectoryEntry();
if (de.Properties.Contains("department"))
{
dept = de.Properties["department"][0].ToString();
if (!dict.ContainsKey(dept))
{
dict.Add(result.Properties["department"][0].ToString();
}
}
}
Alternatively, there are command-line tools which will give you this information such as dsquery or adfind.
adfind -default -f "(objectclass=user)" department -list | sort
will give you a sorted list of the department attributes for all users.