Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to Return all user attributes given their samaccountname

Posted on 2009-07-01
13
Medium Priority
?
2,545 Views
Last Modified: 2013-12-24
I'm trying to return the First Name and Last Name of a user by only providing the samaccountname to the search filter.
protected void Page_Load(object sender, EventArgs e)
    {
        GetActiveADUsers("LDAP://adBox.company.com", "CN=samaccountname=domain\\user");
    }
 
    public void GetActiveADUsers(string ldapString, string adSearchFilter)
    {
        DirectoryEntry de = new DirectoryEntry(ldapString,"domain\\username","password");
        DirectorySearcher deSearch = new DirectorySearcher();
        deSearch.SearchRoot = de;
 
        deSearch.SearchScope = SearchScope.Subtree; //Including the sub OU's
        deSearch.Filter = adSearchFilter;
        SearchResultCollection result = deSearch.FindAll();
 
        //Get User Array Here
        for (int x = 0; x < result.Count; x++)
        {
            string firstLastName = Convert.ToBoolean(result[x].Properties["name"].Count > 0) ? result[x].Properties["name"][0].ToString() : "";
            
            System.Web.HttpContext.Current.Response.Write(firstLastName + "<br />");
 
        }
    }

Open in new window

0
Comment
Question by:kvigor
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
13 Comments
 
LVL 71

Expert Comment

by:Chris Dent
ID: 24757007

Hey :)

I would do this...

Chris
protected void Page_Load(object sender, EventArgs e)
    {
        // Modified the ldapFilter so it searches for sAMAccountName
        GetActiveADUsers("LDAP://adBox.company.com", "(samaccountname=user)");
    }
 
    public void GetActiveADUsers(string ldapString, string adSearchFilter)
    {
        DirectoryEntry de = new DirectoryEntry(ldapString,"domain\\username","password");
        DirectorySearcher deSearch = new DirectorySearcher(de, adSearchFilter);
        // Passed in the constructor
        // deSearch.SearchRoot = de;
 
        // SubTree is the default, so really not required here. 
        deSearch.SearchScope = SearchScope.Subtree; //Including the sub OU's
        // Passed in the constructor
        // deSearch.Filter = adSearchFilter;
        // The sAMAccountName is a unique attribute in the search scope (single domain)
        // FindOne() saves us a loop or two
        SearchResult result = deSearch.FindOne();
 
        string firstName = result.Properties["givenname"][0].ToString();
        string lastName = result.Properties["sn"][0].ToString();
        string fullName = result.Properties["name"][0].ToString();
        string displayName = result.Properties["displayname"][0].ToString();        
    
        System.Web.HttpContext.Current.Response.Write(firstLastName + "<br />");
    }

Open in new window

0
 

Author Comment

by:kvigor
ID: 24759396
I'll try this solution in the morning.
0
 

Author Comment

by:kvigor
ID: 24764453
I get the following error with your code:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:
Line 41:         //string lastName = result.Properties["sn"][0].ToString();
Line 42:         //string fullName = result.Properties["name"][0].ToString();
Line 43:         string displayName = result.Properties["displayname"][0].ToString();
Line 44:
Line 45:         System.Web.HttpContext.Current.Response.Write(displayName + "<br />");
 I'm using the exact code you posted???
0
NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

 
LVL 71

Expert Comment

by:Chris Dent
ID: 24764480

Suggests that displayName is blank (in AD). Does name return correctly?

Chris
0
 

Author Comment

by:kvigor
ID: 24764529
All properties returned blank: sn, name, and displayName.  I commented them out one by one thinking the same thing but I know I have a name and displayname as I tested my account.
0
 
LVL 71

Expert Comment

by:Chris Dent
ID: 24764535

Okay, I must have done something wrong then. One sec.

Chris
0
 

Author Comment

by:kvigor
ID: 24764606
I inserted the domain\username here:
(samaccountname=domain\\username)
0
 
LVL 71

Expert Comment

by:Chris Dent
ID: 24764619

That won't work.

sAMAccountName in the directory is just the username, domain doesn't get a look in there.

Chris
0
 
LVL 71

Accepted Solution

by:
Chris Dent earned 1600 total points
ID: 24764773

I get no problems provided the search filter is correct. You could always test to see if the result is null? But that doesn't help much if it's supposed to return something :)

Anyway, take out the domain from the search filter, it can't be included there.

Chris
0
 

Author Comment

by:kvigor
ID: 24764827
So what am I not getting, I'm using this to get the samaccountname:
   username = User.Identity.Name.ToString();
and I'm passing in username var to here:
   GetActiveADUsers("LDAP://adBox.company.com", "HERE");  is there way this will work
 I'm actually going to get the fullname/display name from a different namespace because the directoryservices namespace may not be as user friendly as I need it to be.
0
 
LVL 71

Expert Comment

by:Chris Dent
ID: 24764863

As long as the "Name" value above is only the user name, and not "domain\username" then it's fine. Although with the code above it's expecting you to pass a valid LDAP filter (perhaps like "(samAccountName=" + username + ")").

That'll break a bit if you use the same user name in the authentication string for the directory entry and expect it to have the domain name there. If that is the case I would say pass user and domain as separate values, or build the filter in the function, parsing the username out of "domain\user".

Chris
0
 

Author Comment

by:kvigor
ID: 24764897
ohhhh! So Sorry that DID work I didn't understand what you meant by:
ID: 24764619 "domain doesn't get a look in there."
So I removed the "domain\" and all returned well. Thanks you saved me alot of time.

Your Solution like Ambien it Worked like a Dream : ^)
0
 

Author Closing Comment

by:kvigor
ID: 31598874
User was perfect in solution.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After seeing many questions for JRNL_WRAP_ERROR for replication failure, I thought it would be useful to write this article.
How to deal with a specific error when using the Enable-RemoteMailbox cmdlet to create a mailbox in the cloud-based service, for an existing user in an on-premises Active Directory.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question