473,246 Members | 1,533 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

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 5007
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Nashat Wanly | last post by:
HOW TO: Call a Parameterized Stored Procedure by Using ADO.NET and Visual C# .NET View products that this article applies to. This article was previously published under Q310070 For a Microsoft...
1
by: Prasad Karunakaran | last post by:
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...
1
by: elziko | last post by:
Hi, I'm using the following code to create a user: Dim strNodeName As String = "test user" Dim NewUser As DirectoryEntry Dim AD As New DirectoryEntry("WinNT://MYCOMPUTER") 'delete user...
0
by: sunmiester | last post by:
I have an ASP page that retrieves user info. The page runs fine on XP Pro IIS 5.1, however, when i try to run it from a server running W2k Server SP4 or W2K3, it breaks and i get the following...
0
by: Tim | last post by:
Hello, I'm trying very (too) hard to log uses LDAP (via ADSI) to autheniticate users in an A2k2 application. We have AD and I have that working slick. We are in a tranistion from NDS to AD and...
3
by: Ram | last post by:
How to Authenticate NDS server using C#
1
by: Josephine | last post by:
HI, Do anyone know how to pass LDAP value from ldap_first.asp and post to value into MS Access Database? Please help. Billion thanks ----------------ldap_first.asp--------------------- <html>...
6
by: Mark Rae | last post by:
Hi, I'm in the process of updating an ASP.NET v1.1 web app to v2. The app uses ActiveDirectory a great deal, and I'm trying to use the new System.Collections.Generic namespace where possible,...
0
by: rbukkara | last post by:
Hi, I have got the following error while trying to add a user in the LDAP Directory. javax.naming.NameNotFoundException: ; remaining name 'uid=vassila,ou=People,dc=cs,dc=uno,dc=edu' I have...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.