forsters
asked on
Get User Contact Details from AD using asp.net c#
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:
And page code:
Many thanks in Advance
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;
}
}
}
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>
Many thanks in Advance
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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.
ASKER
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.
ASKER
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.
ASKER
Couple of things that i'm not sure how to get around:
I've got an error here:
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)
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)