locked
UserName from Active Directory RRS feed

  • Question

  • User13622593 posted

    I am trying to get the user name from active directory.  I used the code given but seem to get an error :Unknown error (0x80005000) on line
     using (SearchResultCollection src = ds.FindAll())


    protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string adPath = "ldap://oscar:389/OU=Atlanta,DC=datadist,DC=com";
                //use current login as search key
                string sFilter = String.Format(
                    "(&(objectCategory=person)(sAMAccountName={0}))",
                    HttpContext.Current.User.Identity.Name.Split(new char[] { '\\' })[1]
                     );
               
                //this is optional, but more efficient
                string[] attribs = new string[] { "cn", "sn", "givenName" };
                DirectoryEntry de = new DirectoryEntry(
                    adPath,
                    null,
                    null,
                    AuthenticationTypes.Secure
                    );

                using (de)
                {
                    DirectorySearcher ds = new DirectorySearcher(
                        de,
                        sFilter,
                        attribs, //set this to null to retrieve all attribs
                        SearchScope.Subtree
                        );

                    SearchResult sr = null;

                    using (SearchResultCollection src = ds.FindAll())
                    {
                        if (src.Count > 0)
                            sr = src[0];
                    }

                    if (sr == null)
                    {
                        Label1.Text = "User not found...";
                        return;
                    }

                    StringBuilder sb = new StringBuilder();

                    //dump everything we have
                    foreach (string key in sr.Properties.PropertyNames)
                    {
                        if (sr.Properties.Contains(key))
                        {
                            foreach (object o in sr.Properties[key])
                            {
                                //output every item
                                sb.AppendFormat("{0} : {1}<br>", key, o);
                            }
                        }
                    }

                    Label1.Text = "Hello " + sb.ToString();
                }
            }

        }

    Monday, January 22, 2007 12:07 PM

All replies

  • User-508806111 posted

    Here is a sample code with comments to retrieve appropriate fields:

     

            Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://YOURACTIVEDIRECTORY", "USERNAME-ADMIN, "PASSWORD")
            Dim osearcher As DirectorySearcher = New DirectorySearcher(oroot)
            Dim oresult As SearchResultCollection
            Dim result As SearchResult
    
            osearcher.Filter = "(&(objectCategory=person))" ' search filter
            osearcher.PropertiesToLoad.Add("cn") ' username
            osearcher.PropertiesToLoad.Add("name") ' full name
            osearcher.PropertiesToLoad.Add("givenname") ' firstname
            osearcher.PropertiesToLoad.Add("sn") ' lastname
            osearcher.PropertiesToLoad.Add("mail") ' mail
            osearcher.PropertiesToLoad.Add("initials") ' initials
            osearcher.PropertiesToLoad.Add("ou") ' organizational unit
            osearcher.PropertiesToLoad.Add("userPrincipalName") ' login name
            osearcher.PropertiesToLoad.Add("distinguishedName") ' distinguised name
            oresult = osearcher.FindAll()
    
            For Each result In oresult
                If Not result.GetDirectoryEntry.Properties("sn").Value Is Nothing Then
                    ' writes specific values retrieved from above - this is just a sample.
                    response.write(result.GetDirectoryEntry.Properties("cn").Value & ":" & result.GetDirectoryEntry.Properties("userPrincipalName").Value)
                End If
            Next

     hope this helps.

    Jae.

    Monday, January 22, 2007 11:19 PM
  • User13622593 posted
    Jae I need it in C#
    Tuesday, January 23, 2007 10:14 AM
  • User-496071636 posted

    I am trying to get the user name from active directory.  I used the code given but seem to get an error :Unknown error (0x80005000) on line
     using (SearchResultCollection src = ds.FindAll())


    protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string adPath = "<STRIKE>ldap</STRIKE>://oscar:389/OU=Atlanta,DC=datadist,DC=com";
                //use current login as search key
                string sFilter = String.Format(

    Firstly, thanks for your code, it really helped with my own Active Directory using.

    I just wanted to say that if you notice the strikethrough I put in your quote above, it was causin the exact same error when I used it. But after changing that to LDAP instead of ldap, it moved past that message.

    Also I noticed the weirdest functionality, if I had Authentication=Windows and Impersonate=True (both in web.config), it would give me a different error message. However with Auth=Win and Impersonate=False, it worked perfectly. I suppose that the Network Service on my web server has rights to use the AD server, whereas using my credentials really didn't work.

    Hope it helps,

    J

    Sunday, February 25, 2007 8:46 PM
  • User1674234528 posted

    Try this. I have used an online converter to change it from VB.NET to C# but it should be ok.
     

    public void getUser()
    {
     DirectoryServices.SearchResult myResult;
     string filterString = string.Empty;
     string EntryString = "LDAP:// <Your AD Domain here>";
     DirectoryServices.DirectorySearcher myDirectorySearcher = new DirectoryServices.DirectorySearcher(new DirectoryServices.DirectoryEntry(EntryString, "Username", "Password"));
     string tempStr;
     string[] splStr = new string[3];
     try {
       filterString = "(sAMAccountName=" + Username + ")";
       myDirectorySearcher.Filter = filterString;
       myDirectorySearcher.PropertiesToLoad.Add("cn");
       myResult = myDirectorySearcher.FindOne();
       splStr = Regex.Split(myResult.Properties("cn").Item(0).ToString, " ");
       tempStr = splStr(1).ToString + " " + splStr(0).ToString;
       Label1.Text = "Hello " + tempStr;
     } catch (Exception ex) {
     }
    }

    Friday, March 9, 2007 5:08 AM
  • User590000598 posted

    Hi, Can you translate it in vb.net? thanks [;)]

    Thursday, September 6, 2007 1:01 PM
  • User590000598 posted

     Hi, Guys! Can somebody help me?

    I am currently developing a web application where in I have user management, allows adding AD user or non-AD user. If Active Direcory (AD) user, I will not ask for password at all, I just need to check if the user exist in active directory. During log-in, that's the time the user will be asked for authentication info, e.i. Username and password, then authenticate against active directory.

    My problem is How can I validate user (not authenticate, but just check existence) using LDAP? or How can I verify whether an account exists in an Active Directory? and without providing any password at all. in vb.net plss...

    Thanks in advance! [;)]

    Thursday, September 6, 2007 1:16 PM
  • User1191518856 posted

    You can use a DirectorySearcher to check if a user exists in the AD. Only problem is that the DirectorySearcher needs to authenticate before beginning searching. And AD does not allow anonymous access, so to do a search routine like this you would need to create a service account in your AD that this code can use. Once you have done this, it's a piece of cake to get the searching done.

    Here's a page that should get you started: Active Directory and VB.NET 

    Most AD examples are pretty straight forward to translate between VB and C# too. Or you could make use of an online converter such as http://www.dotnetspider.com/convert/CSharp-To-Vb.aspx

    Wednesday, September 26, 2007 11:22 AM