[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Get User Contact Details from AD using asp.net c#

Posted on 2012-09-20
6
Medium Priority
?
3,457 Views
Last Modified: 2012-09-26
Hi Experts,

New to this but I need to retrieve:

Displayname, telephonenumber, mobile, jobtitle from AD and display that information on a webpage by user login:

The code below gets me pretty close but i'd like some help to remove adspath from results
and have some control over formatting, I will need to display results in a specific order and be able to format each item differently, so no longer any good binding to a grid. I'll need to bind each item on its own as it were.
_My code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.Configuration;
using System.Data;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Security.Principal.IPrincipal user;

        user = System.Web.HttpContext.Current.User;

        System.Security.Principal.IIdentity identity;

        identity = user.Identity;

        Session["username"] = identity.Name.Substring(identity.Name.IndexOf(@"\") + 1);

        // Take the value from the input box and pull back a few AD details
        DataTable UserProperties = null;
        // UserProperties = GetUserByDisplayName(txtFullName.Text);
        UserProperties = GetUserByDisplayName(Session["username"].ToString());
        // Display data if we have any or show warning
        if (UserProperties != null)
        {
            ADUserProperties.DataSource = UserProperties;
            ADUserProperties.DataBind();
        }
        else
        {
            // Show no records
            SysMessage.Text = "Could not find any details for this user. Please check that the users name is correct.</p>";
        }
    }

    string ExtractUserName(string path)
    {
        string[] userPath = path.Split(new char[] { '\\' });
        return userPath[userPath.Length - 1];
    }

    bool IsExistInAD(string loginName)
    {
        string userName = ExtractUserName(loginName);
        DirectorySearcher search = new DirectorySearcher();
        search.Filter = String.Format("(SAMAccountName={0})", userName);
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();

        if (result == null)
        {
            return false;
        }
        else
        {
            return true;
        }


    }

    //protected void GetADDetails(Object sender, EventArgs e)
    //{
    //    // Take the value from the input box and pull back a few AD details
    //    DataTable UserProperties = null;
    //    // UserProperties = GetUserByDisplayName(txtFullName.Text);
    //    UserProperties = GetUserByDisplayName(Session["username"].ToString());
    //    // Display data if we have any or show warning
    //    if (UserProperties != null)
    //    {
    //        ADUserProperties.DataSource = UserProperties;
    //        ADUserProperties.DataBind();
    //    }
    //    else
    //    {
    //        // Show no records
    //        SysMessage.Text = "Could not find any details for this user. Please check that the users name is correct.</p>";
    //    }
    //}


    protected DataTable GetUserByDisplayName(String fullUserName)
    {
        DirectoryEntry de = new DirectoryEntry(ConfigurationManager.AppSettings.Get("ADPath")); // Authentication details
        de.Username = ConfigurationManager.AppSettings.Get("ADServiceAccount"); //DOMAIN\User
        de.Password = ConfigurationManager.AppSettings.Get("ADServiceAccountPassword");
        de.AuthenticationType = AuthenticationTypes.FastBind;


        DirectorySearcher DirectorySearcher = new DirectorySearcher(de);
        DirectorySearcher.ClientTimeout = TimeSpan.FromSeconds(30);

        // load the properties we are interested in
        DirectorySearcher.PropertiesToLoad.Add("cn");
        DirectorySearcher.PropertiesToLoad.Add("sAMAccountName");
        DirectorySearcher.PropertiesToLoad.Add("mail");
        DirectorySearcher.PropertiesToLoad.Add("displayName");
        DirectorySearcher.PropertiesToLoad.Add("mDBStorageQuota");
        DirectorySearcher.PropertiesToLoad.Add("title");
        DirectorySearcher.PropertiesToLoad.Add("Department");
        DirectorySearcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");
        DirectorySearcher.PropertiesToLoad.Add("telephoneNumber");
        DirectorySearcher.PropertiesToLoad.Add("mobile");
        DirectorySearcher.PropertiesToLoad.Add("fax");
        DirectorySearcher.PropertiesToLoad.Add("memberof");

        // filter it on exact entry - NOTE no wild card
        //DirectorySearcher.Filter = "(displayName=" + fullUserName.Trim() + ")";
        DirectorySearcher.Filter = "(sAMAccountName=" + fullUserName.Trim() + ")";

        SearchResult result; // There should only be one entry
        result = DirectorySearcher.FindOne();
        if (result != null)
        {
            // Create a table and populate it with properties to bind to gridview
            DataTable myTable = new DataTable("ActiveDir");
            myTable.Columns.Add(new DataColumn("Key", System.Type.GetType("System.String")));
            myTable.Columns.Add(new DataColumn("Value", System.Type.GetType("System.String")));
            DataRow myRow;
            foreach (string propname in result.Properties.PropertyNames)
            {
                foreach (Object objValue in result.Properties[propname])
                {
                    myRow = myTable.NewRow();
                    myRow[0] = propname;
                    myRow[1] = objValue.ToString();
                    myTable.Rows.Add(myRow);
                }
            }
            return myTable;
        }
        else
        {
            return null;
        }
    }

}

Open in new window


And page code:

 <form id="form1" runat="server">
  <asp:ScriptManager ID="AtlasScriptCore" runat="server" EnablePartialRendering="true" />
    <div id="content">
        <h3>
            Active Directory Searcher</h3>
      
        <br />
        <div id="Results">
            <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <asp:GridView ID="ADUserProperties" runat="server">
                    </asp:GridView>
                    <asp:Literal runat="server" ID="SysMessage" EnableViewState="false"></asp:Literal>
                </ContentTemplate>
             
            </asp:UpdatePanel>
        </div>
    </div>
    </form>

Open in new window


Many thanks in Advance
0
Comment
Question by:forsters
  • 4
  • 2
6 Comments
 
LVL 10

Assisted Solution

by:gavsmith
gavsmith earned 2000 total points
ID: 38417461
Hi, I think I'm following what you are trying to acheive. Now that you know what properties you wish to show, don't load them all into a grid. Pick out the strings that you want so you could manipulate them (if you want) and display in labels. Something like this:

Page code:

 <form id="form1" runat="server">
  <asp:ScriptManager ID="AtlasScriptCore" runat="server" EnablePartialRendering="true" />
    <div id="content">
        <h3>
            Active Directory Searcher</h3>
      
        <br />
        <div id="Results">
            <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                     <div><asp:Label ID="lblName" runat="server"></asp:Label></div>
                      <div><asp:Label ID="lblJobTitle" runat="server"></asp:Label></div>
                      <div><asp:Label ID="lblTel" runat="server"></asp:Label></div>
                             ...etc
                    <asp:Literal runat="server" ID="SysMessage" EnableViewState="false"></asp:Literal>
                </ContentTemplate>
             
            </asp:UpdatePanel>
        </div>
    </div>
    </form>

Open in new window


Code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.Configuration;
using System.Data;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Security.Principal.IPrincipal user;

        user = System.Web.HttpContext.Current.User;

        System.Security.Principal.IIdentity identity;

        identity = user.Identity;

        Session["username"] = identity.Name.Substring(identity.Name.IndexOf(@"\") + 1);

        // Take the value from the input box and pull back a few AD details
        DataTable UserProperties = null;
        // UserProperties = GetUserByDisplayName(txtFullName.Text);
        UserProperties = GetUserByDisplayName(Session["username"].ToString());
        // Display data if we have any or show warning
        if (UserProperties != null)
        {
            ADUserProperties.DataSource = UserProperties;
            ADUserProperties.DataBind();
        }
        else
        {
            // Show no records
            SysMessage.Text = "Could not find any details for this user. Please check that the users name is correct.</p>";
        }
    }

    string ExtractUserName(string path)
    {
        string[] userPath = path.Split(new char[] { '\\' });
        return userPath[userPath.Length - 1];
    }

    bool IsExistInAD(string loginName)
    {
        string userName = ExtractUserName(loginName);
        DirectorySearcher search = new DirectorySearcher();
        search.Filter = String.Format("(SAMAccountName={0})", userName);
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();

        if (result == null)
        {
            foreach (SearchResult r in result)
            {
              string displayName = r.Properties["displayName"].ToString();
              string title = r.Properties["title"].ToString();
              string tel = r.Properties["telephoneNumber"].ToString();
              etc...
             // if strings need manipulating do it here
             lblName.Text = displayName;
             lblJobTitle.Text = title;
             lblTel.Text = tel;
            }
            return false;
        }
        else
        {
            return true;
        }


    }

    //protected void GetADDetails(Object sender, EventArgs e)
    //{
    //    // Take the value from the input box and pull back a few AD details
    //    DataTable UserProperties = null;
    //    // UserProperties = GetUserByDisplayName(txtFullName.Text);
    //    UserProperties = GetUserByDisplayName(Session["username"].ToString());
    //    // Display data if we have any or show warning
    //    if (UserProperties != null)
    //    {
    //        ADUserProperties.DataSource = UserProperties;
    //        ADUserProperties.DataBind();
    //    }
    //    else
    //    {
    //        // Show no records
    //        SysMessage.Text = "Could not find any details for this user. Please check that the users name is correct.</p>";
    //    }
    //}


    protected DataTable GetUserByDisplayName(String fullUserName)
    {
        DirectoryEntry de = new DirectoryEntry(ConfigurationManager.AppSettings.Get("ADPath")); // Authentication details
        de.Username = ConfigurationManager.AppSettings.Get("ADServiceAccount"); //DOMAIN\User
        de.Password = ConfigurationManager.AppSettings.Get("ADServiceAccountPassword");
        de.AuthenticationType = AuthenticationTypes.FastBind;


        DirectorySearcher DirectorySearcher = new DirectorySearcher(de);
        DirectorySearcher.ClientTimeout = TimeSpan.FromSeconds(30);

        // load the properties we are interested in
        DirectorySearcher.PropertiesToLoad.Add("cn");
        DirectorySearcher.PropertiesToLoad.Add("sAMAccountName");
        DirectorySearcher.PropertiesToLoad.Add("mail");
        DirectorySearcher.PropertiesToLoad.Add("displayName");
        DirectorySearcher.PropertiesToLoad.Add("mDBStorageQuota");
        DirectorySearcher.PropertiesToLoad.Add("title");
        DirectorySearcher.PropertiesToLoad.Add("Department");
        DirectorySearcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");
        DirectorySearcher.PropertiesToLoad.Add("telephoneNumber");
        DirectorySearcher.PropertiesToLoad.Add("mobile");
        DirectorySearcher.PropertiesToLoad.Add("fax");
        DirectorySearcher.PropertiesToLoad.Add("memberof");

        // filter it on exact entry - NOTE no wild card
        //DirectorySearcher.Filter = "(displayName=" + fullUserName.Trim() + ")";
        DirectorySearcher.Filter = "(sAMAccountName=" + fullUserName.Trim() + ")";

        SearchResult result; // There should only be one entry
        result = DirectorySearcher.FindOne();
        if (result != null)
        {
             string s
        }
        else
        {
            return null;
        }
    }

}

Open in new window

0
 

Author Comment

by:forsters
ID: 38417698
Hi Thanks, yes thats the sort of thing i'm after.

Couple of things that i'm not sure how to get around:

I've got an error here:

if (UserProperties != null)
        {
            ADUserProperties.DataSource = UserProperties;
            ADUserProperties.DataBind();
        }
        else

Open in new window


because we've now removed the grid called ADUserProperties - is there a way to bind to individual lables or will I need to use a details view - they drive me nuts because you then have to FindControl everything?

I'm also getting an error on the dataTable now because it doesn't like the line to return string s (the variable s is declared but never used)

 if (result != null)
        {
             string s
        }

Open in new window



Do I need the table now? I tried to tweak code but was getting in more mess than I knew how to get out of, I can see the problems (binding user to results and results to lables but can't find my way out)
0
 

Accepted Solution

by:
forsters earned 0 total points
ID: 38421276
Ahh ok I've made some progress which I think means I'll be able to figure the rest out, so I'll post my code below and you get the points for getting me 80% there. Eternally grateful for your help.

My Code Behind:

using System;
using System.Configuration;
using System.DirectoryServices;


public partial class AD_GK_Default6 : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Security.Principal.IPrincipal user;

        user = System.Web.HttpContext.Current.User;

        System.Security.Principal.IIdentity identity;

        identity = user.Identity;

        Session["username"] = identity.Name.Substring(identity.Name.IndexOf(@"\") + 1);
   

        DirectoryEntry de = new DirectoryEntry(ConfigurationManager.AppSettings.Get("ADPath")); 
        de.Username = ConfigurationManager.AppSettings.Get("ADServiceAccount"); 
        de.Password = ConfigurationManager.AppSettings.Get("ADServiceAccountPassword");
        de.AuthenticationType = AuthenticationTypes.FastBind;

        DirectorySearcher dssearch = new DirectorySearcher(de);

        dssearch.Filter = "(sAMAccountName=" + Session["username"].ToString() + ")";

        SearchResult sresult = dssearch.FindOne();

        DirectoryEntry dsresult = sresult.GetDirectoryEntry();

        lblfname.Text = dsresult.Properties["givenName"][0].ToString();

        lbllname.Text = dsresult.Properties["sn"][0].ToString();

        lblemail.Text = dsresult.Properties["mail"][0].ToString();

   }  
}

Open in new window


Page Code

 <form id="form1" runat="server">

<div>

<table>

<tr>

<td align="right">

First Name:

</td>

<td>

<asp:Label ID="lblfname" runat="server" Font-Bold="true"></asp:Label>  

</td>

</tr>

<tr>

<td align="right">

Last Name:

</td>

<td>

<asp:Label ID="lbllname" runat="server" Font-Bold="true"></asp:Label>  

</td>

</tr>

<tr>

<td align="right">

Email:

</td>

<td>

<asp:Label ID="lblemail" runat="server" Font-Bold="true"></asp:Label>  

</td>

</tr>

</table>

</div>

</form>

Open in new window


So from here I can change the formatting of each label text independently and I can choose which items I want to display for my user.

Many thanks again, it was simpler than I  thought (usually is)
0
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

 
LVL 10

Expert Comment

by:gavsmith
ID: 38421307
I don't know what happened here. I definately replied yesterday with updated code, yet it doesn't appear to be on here now?!

I wrote that I had got distracted and put the code in the wrong place, if you look at my code above in the "IsExistInAD" method (lines 58-68). I accidently put it there instead of line 132 (where I actually started to write it in). Sorry for the confusion.
0
 

Author Comment

by:forsters
ID: 38421318
No problem, grateful for your help and the absence of an obvious reply made me think a bit longer/harder which is sometimes not such a bad thing...especially when it comes to understanding.
0
 

Author Closing Comment

by:forsters
ID: 38435841
My comment represents the code that runs for me without error and achieves (more or less) my original objective, however I would not have arrived at this without the help of the expert.
0

Featured Post

Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

Question has a verified solution.

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

Group policies can be applied selectively to specific devices with the help of groups. Utilising this, it is possible to phase-in group policies, over a period of time, by randomly adding non-members user or computers at a set interval, to a group f…
Here's a look at newsworthy articles and community happenings during the last month.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.
Suggested Courses

830 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