locked
Querying Active Directory for Department RRS feed

  • Question

  • hi all

    I Need to Query the active directoy for department name by providing user id of a person.

     

    can any one tell me how to do this?


    • Edited by roma_victa Thursday, December 29, 2011 8:32 AM
    Thursday, December 29, 2011 8:03 AM

Answers

  • Hi,

    I hope you are refering to this

    DirectoryEntry de = new DirectoryEntry(); 
    
    de.Path = "LDAP://dnsNameOfYourDC.my.company.com"; 
    
    DirectorySearcher deSearch = new DirectorySearcher(de); 
    
    deSearch.PropertiesToLoad.Add("department");
    
     deSearch.PropertiesToLoad.Add("company");  
    
    deSearch.SearchScope = SearchScope.Subtree; deSearch.Filter = "(&(objectClass=User)(userPrincipalName=MyPrincipalName))"; 
    
    SearchResultCollection results = deSearch.FindAll(): 
    
     foreach (SearchResult result in results) 
    {    
         ResultPropertyCollection props = result.Properties;         foreach (string propName in props.PropertyNames)    
         {      
      //Loop properties and pick out company,department            string tmp = (string)props[propName][0];   
          } 
    } 
    

    Regards,
    A.Murugan


    If it solved your problem,Please click "Mark As Answer" on that post and "Mark as Helpful". Happy Programming!
    • Marked as answer by roma_victa Tuesday, January 3, 2012 4:33 AM
    Thursday, December 29, 2011 9:13 AM
  • Hi,
       Check this code using directory entry.

    using System.DirectoryServices;

    public class Department
    {


     DirectoryEntry Dentry = new DirectoryEntry(path, username, password);

     string strResult = Dentry.Properties("department").Value;
    }

     The reason for choosing DirectoryEntry instead of Directory searcher is to refresh the Active Directory cache .When querying the constructed attributes like 'department' DirectoryEntry should be used as it refreshes the cache when the code is executed.


    If a post answers your question, please click Mark As Answer on that post and Mark as Helpful. Happy Coding...

    • Edited by Ragu.R Thursday, December 29, 2011 1:12 PM
    • Marked as answer by roma_victa Tuesday, January 3, 2012 4:33 AM
    Thursday, December 29, 2011 12:10 PM

All replies

  • Hi Roma,

    there is a codeproject article explaining active directory access:
    http://www.codeproject.com/KB/system/everythingInAD.aspx
    (And there are a lot of more articles covering Active Directory. You might want to search for Active Directory on Codeproject.com!)

    You also might check the Namespace System.DirectoryServices and System.DirectoryServices.ActiveDirectory:
    http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx
    http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectory.aspx

    With kind regards,

    Konrad Neitzel

    Thursday, December 29, 2011 8:54 AM
  • Hi,

    I hope you are refering to this

    DirectoryEntry de = new DirectoryEntry(); 
    
    de.Path = "LDAP://dnsNameOfYourDC.my.company.com"; 
    
    DirectorySearcher deSearch = new DirectorySearcher(de); 
    
    deSearch.PropertiesToLoad.Add("department");
    
     deSearch.PropertiesToLoad.Add("company");  
    
    deSearch.SearchScope = SearchScope.Subtree; deSearch.Filter = "(&(objectClass=User)(userPrincipalName=MyPrincipalName))"; 
    
    SearchResultCollection results = deSearch.FindAll(): 
    
     foreach (SearchResult result in results) 
    {    
         ResultPropertyCollection props = result.Properties;         foreach (string propName in props.PropertyNames)    
         {      
      //Loop properties and pick out company,department            string tmp = (string)props[propName][0];   
          } 
    } 
    

    Regards,
    A.Murugan


    If it solved your problem,Please click "Mark As Answer" on that post and "Mark as Helpful". Happy Programming!
    • Marked as answer by roma_victa Tuesday, January 3, 2012 4:33 AM
    Thursday, December 29, 2011 9:13 AM
  • Hi Murugan,

     

    I have tried your code but it doesnt show the department. I logged in to server and checked manually the active directory is there department .

    what would be the problem. i am running windows 2008 server, will this code work on that???

    Thursday, December 29, 2011 11:51 AM
  • i have run this code and it can't find the department. is it because its running on windows 2008 server??.  I manually logged into the server and checked and the department is there
    Thursday, December 29, 2011 11:55 AM
  • Hi,
       Check this code using directory entry.

    using System.DirectoryServices;

    public class Department
    {


     DirectoryEntry Dentry = new DirectoryEntry(path, username, password);

     string strResult = Dentry.Properties("department").Value;
    }

     The reason for choosing DirectoryEntry instead of Directory searcher is to refresh the Active Directory cache .When querying the constructed attributes like 'department' DirectoryEntry should be used as it refreshes the cache when the code is executed.


    If a post answers your question, please click Mark As Answer on that post and Mark as Helpful. Happy Coding...

    • Edited by Ragu.R Thursday, December 29, 2011 1:12 PM
    • Marked as answer by roma_victa Tuesday, January 3, 2012 4:33 AM
    Thursday, December 29, 2011 12:10 PM
  • Hi Ragu,

    when i try to run this code it gives me

    "Error 3 Non-invocable member 'System.DirectoryServices.DirectoryEntry.Properties' cannot be used like a method. "

    Thursday, December 29, 2011 2:17 PM
  • For A.Murugan's suggestion, you need to get it in the loop:

     foreach (string propName in props.PropertyNames)    
         {      
      //Loop properties and pick out company,department            
    string tmp=props[propName][0].ToSting();
          } 
    For Ragu's suggestion, you can modify it as below:

    DirectoryEntry Dentry = new DirectoryEntry(path, username, password);

     string strResult = Dentry.Properties["department"].Value;

    In the case, "department" is that the property name that stores "department" information.


    Paul Zhou [MSFT]
    MSDN Community Support | Feedback to us
    Friday, December 30, 2011 1:57 PM
  • I have got the error "Object reference not set to an instance of an object." in line

     

    string strResult = Dentry.Properties["department"].Value.ToString();
    Monday, January 2, 2012 4:44 AM
  • Hi Roma,
        You are getting this error because the value returned by the code
    'Dentry.Properties["department"].Value' is a null value and when converting a null value to the string You get the 'null reference exception' which throws the error
    'Object reference not set to an instance of an object'.

    To avoid this error.Code as follows


    DirectoryEntry Dentry = new DirectoryEntry(path, username, password);

    If Dentry.Properties("department").Value != null Then
     
    string strResult = Dentry.Properties("department").Value;

    End If

    Secondly, its looking strange that you are not getting the department value.Follow the steps and reply me.
     
    1) Login to AD users and computers console.
    2) Right click the 'Properties' of the user that you want to see take the department value.
    3) In the 'Organization' Tab see if the user has the department value.
     
    Reply me whether there is value. Be sure that you are using a 'Domain admin account' to retrieve every properties of an object.

     

     

        


    If a post answers your question, please click Mark As Answer on that post and Mark as Helpful. Happy Coding...
    Monday, January 2, 2012 6:56 AM
  • Hi,

    I would suggest that you get familar with the debugger! Even when you receive the exception you might be able to investigate the content of the variables (if started inside the debugger e.g. through F5 in Visual Studio!):

    Inside the debugger you can check:
    - Is Dentry null?
    - Is Dentry.Properties["department"] null?
    - Is Dentry.Properties["department"].Value null?

    It is nothing we can answer you, because we cannot see the debugger. But it is a question you can answer yourself in less than 1 min if you know the debugger and how to use it. (And it is nothing complicated!)

    Regarding the answer of Ragu: You might extend the code with more checks, but I would be carefull with such code: Your code will blow up until you get something unreadable! And what is missing: You have to decide what to do in case Value is null! If you throw an exception, then you might even let the runtime throw the exception. In case you want a default value returned, you should create a small helper class with some methods e.g. something that can be used like:
    DirectoryEntryHelper.GetProperty<String>(Dentry, "department", null); // Get the property "department" of Dentry and return a default value of null.
    (Which gets quite near to some helper methods we wrote for our AD code - where we have a central place to do all the casting stuff e.g. casting an Byte[] to a Guid and also very important: Handling paging on very large properties (e.g. when reading the group members of the properties storing information about the replication!)

    With kind regards,

    Konrad

    Monday, January 2, 2012 8:52 AM
  • Thank you all I got .

    • Edited by roma_victa Tuesday, January 3, 2012 5:14 AM
    Monday, January 2, 2012 4:48 PM