468,121 Members | 1,570 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,121 developers. It's quick & easy.

Using LDAP Provider in C# to retrieve the First Name and Last Name

I am using the C# DirectoryEntry class to retrieve the Properties of
an user object in the Active Directory. I need to get the First Name
and Last Name as properties. I know it is not supported with the ADSI
NT Provider and only supported in the LDAP Provider.

So given an UserId (UID) how can I read the First Name and Last Name
using LDAP Provider. If anybody can help me with a C# sample code it
would of great help.

Thanks in advance.

regards,

Prasad
Nov 16 '05 #1
1 4607
Hi Prasad
this sample get user info using logen name , it is with vb.net but the
logic and class calls would be the same with c#. There is also a listing
c# example

Public Class ADengine
Sub testProperties(ByVal strUserName As String, ByVal strLDAP As
String, ByVal strWinsAdminName As String, ByVal strAdminPass As String)
Dim entry As New System.DirectoryServices.DirectoryEntry(strLDAP,
strWinsAdminName, strAdminPass)
'Dim Flag As System.DirectoryServices.DirectoryEntries
Dim MyUser As System.DirectoryServices.DirectoryEntry
Dim searcher As New
System.DirectoryServices.DirectorySearcher(entry)
searcher.Filter = "(&(objectClass=User)(|(mailNickname=" &
strUserName & ")))"
Dim result As System.DirectoryServices.SearchResultCollection
result = searcher.FindAll
Dim result1 As System.DirectoryServices.SearchResult
For Each result1 In result
Dim props As System.DirectoryServices.ResultPropertyCollection
props = result1.Properties

Dim propNames As System.Collections.ICollection
Dim propValues As System.Collections.ICollection

propNames = props.PropertyNames

Dim enumerator As IEnumerator

enumerator = propNames.GetEnumerator

'open file to write data to it
Dim fs As System.IO.FileStream =
System.IO.File.Create("c:\UserData.txt")
Dim sw As New System.IO.StreamWriter(fs)

For i As Integer = 0 To propNames.Count
If enumerator.MoveNext() Then
sw.Write(enumerator.Current.ToString() &
ControlChars.Tab)
Dim resultValuesColl As
System.DirectoryServices.ResultPropertyValueCollec tion
resultValuesColl =
props.Item(enumerator.Current.ToString)
For j As Integer = 0 To resultValuesColl.Count - 1
sw.Write(resultValuesColl(j).ToString & ",")
Next
sw.Write(ControlChars.CrLf)
End If
Next
sw.Flush()
sw.Close()
fs.Close()
Next
End Sub
Function GetActiveDirectoryUsers(ByVal strUserName As String, ByVal
strLDAP As String, ByVal strWinsAdminName As String, ByVal strAdminPass As
String) As String
Dim intCount As Integer
Dim strsAMAccountName As String = ""
Dim strmailname As String = ""
Dim strDept As String = ""
Dim strFullName As String = ""
Dim strUserData As String
Dim strUserStatus As String
Dim entry As New System.DirectoryServices.DirectoryEntry(strLDAP,
strWinsAdminName, strAdminPass)
'Dim Flag As System.DirectoryServices.DirectoryEntries
Dim MyUser As System.DirectoryServices.DirectoryEntry
Dim intAccountControl As Integer
Dim intResult As Integer
Dim searcher As New
System.DirectoryServices.DirectorySearcher(entry)
searcher.Filter = "(&(objectClass=User)(|(mailNickname=" &
strUserName & ")))"
Dim result As System.DirectoryServices.SearchResultCollection
result = searcher.FindAll
Dim result1 As System.DirectoryServices.SearchResult
For Each result1 In result
Try
MyUser = New
System.DirectoryServices.DirectoryEntry(result1.Pa th)
Dim x, y As System.Collections.ICollection
If
Microsoft.VisualBasic.Strings.InStr(result1.Proper ties("mailNickname")(0),
"SystemMailbox", Microsoft.VisualBasic.CompareMethod.Text) = 0 Then
'result1.GetDirectoryEntry()
strsAMAccountName =
result1.Properties("sAMAccountName")(0)
'The following is the Alias
Try
strmailname = result1.Properties("mail")(0)
Catch ex As Exception
'strmailname = "@" 'userPrincipalName
strmailname =
result1.Properties("userPrincipalName")(0)
End Try
Try
strDept = result1.Properties("department")(0)
Catch ex As Exception
strDept = "@"
End Try
Try
strFullName = result1.Properties("displayName")(0)
Catch ex As Exception
strFullName = "@"
End Try
intAccountControl =
result1.Properties("userAccountControl")(0) 'take care
intResult = intAccountControl And 2
If intResult = 0 Then
strUserStatus = "Enabled"
ElseIf intResult = 2 Then
strUserStatus = "Disabled"
End If
End If
Catch ex As Exception
Return "Error"
End Try
Next
strUserData = strUserName & "/" & strmailname & "/" & strDept & "/"
& strFullName & "/" & strUserStatus
Return strUserData
End Function
Public Function GetStrWinsAdminUserName(ByVal strDC As String) As String
Dim strWinsName, strAdminUserName As String
Dim arrstrDC() As String
arrstrDC = strDC.Split(".")
strWinsName = arrstrDC(0)
strAdminUserName =
System.Configuration.ConfigurationSettings.AppSett ings("AdminUserName")
Return strWinsName & "\" & strAdminUserName
End Function
Public Function FormatStrLDAP(ByVal strActiveDirectoryIP As String,
ByVal strDC As String) As String
Dim strconstDC, strLDAP As String
Dim arrstrDC() As String
Dim intCount As Integer
arrstrDC = strDC.Split(".")
strconstDC = "DC="
strDC = ""
For intCount = 0 To arrstrDC.Length - 1
strDC = strDC & strconstDC & arrstrDC(intCount) & ","
Next
strDC = strDC.Substring(0, strDC.Length - 1)
strLDAP = "LDAP://" & strActiveDirectoryIP & "/" & strDC
Return strLDAP
End Function

End Class

'The Above Function Gets All the details about specific user
'As I mentioned in my Previous statement,
'it seems that there is a problem in the UserAccountControl property value.
_____________________
c# sample
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;
using System.Runtime.InteropServices;

namespace PowerAD
{

public class ListViewTextSort: IComparer
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="sortColumn">Column to be sorted</param>
/// <param name="ascending">true, if ascending order, false
otherwise</param>
public ListViewTextSort(Int32 sortColumn, Boolean ascending)
{
m_column = sortColumn;
m_ascending = ascending;
}

/// <summary>
/// Implementation of IComparer.Compare
/// </summary>
/// <param name="lhs">First Object to compare</param>
/// <param name="rhs">Second Object to compare</param>
/// <returns>Less that zero if lhs is less than rhs. Greater than
zero if lhs greater that rhs. Zero if they are equal</returns>
public Int32 Compare(Object lhs, Object rhs)
{
ListViewItem lhsLvi = lhs as ListViewItem;
ListViewItem rhsLvi = rhs as ListViewItem;

if(lhsLvi == null || rhsLvi == null) // We only know how to
sort ListViewItems, so return equal
return 0;

ListViewItem.ListViewSubItemCollection lhsItems =
lhsLvi.SubItems;
ListViewItem.ListViewSubItemCollection rhsItems =
rhsLvi.SubItems;

String lhsText = (lhsItems.Count > m_column) ?
lhsItems[m_column].Text : String.Empty;
String rhsText = (rhsItems.Count > m_column) ?
rhsItems[m_column].Text : String.Empty;

Int32 result = 0;
if(lhsText.Length == 0 || rhsText.Length == 0)
result = lhsText.CompareTo(rhsText);

else
result = OnCompare(lhsText, rhsText);

if(!m_ascending)
result = -result;

return result;
}

/// <summary>
/// Overridden to do type-specific comparision.
/// </summary>
/// <param name="lhs">First Object to compare</param>
/// <param name="rhs">Second Object to compare</param>
/// <returns>Less that zero if lhs is less than rhs. Greater than
zero if lhs greater that rhs. Zero if they are equal</returns>
protected virtual Int32 OnCompare(String lhs, String rhs)
{
return String.Compare(lhs, rhs, false);
}

private Int32 m_column;
private Boolean m_ascending;
}

/// <summary>
/// Provides text sorting (case insensitive)
/// </summary>
public class ListViewTextCaseInsensitiveSort: ListViewTextSort
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="sortColumn">Column to be sorted</param>
/// <param name="ascending">true, if ascending order, false
otherwise</param>
public ListViewTextCaseInsensitiveSort(Int32 sortColumn, Boolean
ascending):
base(sortColumn, ascending)
{
}

/// <summary>
/// Case-insensitive compare
/// </summary>
protected override Int32 OnCompare(String lhs, String rhs)
{
return String.Compare(lhs, rhs, true);
}
}

/// <summary>
/// Provides date sorting
/// </summary>
public class ListViewDateSort: ListViewTextSort
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="sortColumn">Column to be sorted</param>
/// <param name="ascending">true, if ascending order, false
otherwise</param>
public ListViewDateSort(Int32 sortColumn, Boolean ascending):
base(sortColumn, ascending)
{
}

/// <summary>
/// Date compare
/// </summary>
protected override Int32 OnCompare(String lhs, String rhs)
{
return DateTime.Parse(lhs).CompareTo(DateTime.Parse(rhs)) ;
}
}

/// <summary>
/// Provides integer (32 bits) sorting
/// </summary>
public class ListViewInt32Sort: ListViewTextSort
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="sortColumn">Column to be sorted</param>
/// <param name="ascending">true, if ascending order, false
otherwise</param>
public ListViewInt32Sort(Int32 sortColumn, Boolean ascending):
base(sortColumn, ascending)
{
}

/// <summary>
/// Integer compare
/// </summary>
protected override Int32 OnCompare(String lhs, String rhs)
{
return Int32.Parse(lhs, NumberStyles.Number) - Int32.Parse(rhs,
NumberStyles.Number);
}
}

/// <summary>
/// Provides integer (64 bits) sorting
/// </summary>
public class ListViewInt64Sort: ListViewTextSort
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="sortColumn">Column to be sorted</param>
/// <param name="ascending">true, if ascending order, false
otherwise</param>
public ListViewInt64Sort(Int32 sortColumn, Boolean ascending):
base(sortColumn, ascending)
{
}

/// <summary>
/// Integer compare
/// </summary>
protected override Int32 OnCompare(String lhs, String rhs)
{
return (Int32)(Int64.Parse(lhs, NumberStyles.Number) - Int64.Parse(rhs,
NumberStyles.Number));
}
}

/// <summary>
/// Provides floating-point sorting
/// </summary>
public class ListViewDoubleSort: ListViewTextSort
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="sortColumn">Column to be sorted</param>
/// <param name="ascending">true, if ascending order, false
otherwise</param>
public ListViewDoubleSort(Int32 sortColumn, Boolean ascending):
base(sortColumn, ascending)
{
}

/// <summary>
/// Floating-point compare
/// </summary>
protected override Int32 OnCompare(String lhs, String rhs)
{
Double result = Double.Parse(lhs) - Double.Parse(rhs);

if(result > 0)
return 1;

else if(result < 0)
return -1;

else
return 0;
}
}

/// <summary>
/// Provides sorting of ListView columns
/// </summary>
public class ListViewSortManager
{
/// <summary>
///
/// </summary>
/// <param name="list">ListView that this manager will provide
sorting to</param>
/// <param name="comparers">Array of Types of comparers (One for
each column)</param>
public ListViewSortManager(ListView list, Type[] comparers)
{
m_column = -1;
m_sortOrder = SortOrder.None;

m_list = list;
m_comparers = comparers;

m_imgList = new ImageList();
m_imgList.ImageSize = new Size(8, 8);
m_imgList.TransparentColor = System.Drawing.Color.Magenta;

m_imgList.Images.Add(GetArrowBitmap(ArrowType.Asce nding)); // Add
ascending arrow
m_imgList.Images.Add(GetArrowBitmap(ArrowType.Desc ending)); // Add
descending arrow

SetHeaderImageList(m_list, m_imgList);

list.ColumnClick += new ColumnClickEventHandler(ColumnClick);
}

/// <summary>
/// Returns the current sort column
/// </summary>
public Int32 Column
{
get { return m_column; }
}

/// <summary>
/// Returns the current sort order
/// </summary>
public SortOrder SortOrder
{
get { return m_sortOrder; }
}

/// <summary>
/// Returns the type of the comparer for the given column
/// </summary>
/// <param name="column">Column index</param>
/// <returns></returns>
public Type GetColumnComparerType(Int32 column)
{
return m_comparers[column];
}

/// <summary>
/// Sets the type of the comparer for the given column
/// </summary>
/// <param name="column">Column index</param>
/// <param name="comparerType">Comparer type</param>
public void SetColumnComparerType(Int32 column, Type comparerType)
{
m_comparers[column] = comparerType;
}

/// <summary>
/// Reassigns the comparer types for all the columns
/// </summary>
/// <param name="comparers">Array of Types of comparers (One for each
column)</param>
public void SetComparerTypes(Type[] comparers)
{
m_comparers = comparers;
}

/// <summary>
/// Sorts the rows based on the given column and the current sort
order
/// </summary>
/// <param name="sortColumn">Column to be sorted</param>
public void Sort(Int32 column)
{
SortOrder order = SortOrder.Ascending;

if(column == m_column)
order = (m_sortOrder == SortOrder.Ascending) ? SortOrder.Descending :
SortOrder.Ascending;

Sort(column, order);
}

/// <summary>
/// Sorts the rows based on the given column and sort order
/// </summary>
/// <param name="column">Column to be sorted</param>
/// <param name="order">Sort order</param>
public void Sort(Int32 column, SortOrder order)
{
if(column < 0 || column >= m_comparers.Length)
throw new IndexOutOfRangeException();

if(column != m_column)
{
ShowHeaderIcon(m_list, m_column, SortOrder.None);
m_column = column;
}

ShowHeaderIcon(m_list, m_column, order);
m_sortOrder = order;

if(order != SortOrder.None)
{
ListViewTextSort comp = (ListViewTextSort)
Activator.CreateInstance(m_comparers[m_column], new Object[] { m_column,
order == SortOrder.Ascending } );
m_list.ListViewItemSorter = comp;
}
}

/// <summary>
/// ColumnClick event handler
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
private void ColumnClick(object sender, ColumnClickEventArgs e)
{
this.Sort(e.Column);
}

private Int32 m_column;
private SortOrder m_sortOrder;
private ListView m_list;
private Type[] m_comparers;
private ImageList m_imgList;
hope this helps
Mohamed Mahfouz
MEA Developer Support Center
ITworx on behalf of Microsoft EMEA GTSC

Nov 16 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Prasad Karunakaran | last post: by
1 post views Thread by elziko | last post: by
reply views Thread by sunmiester | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.