473,545 Members | 529 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5043
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 strWinsAdminNam e As String, ByVal strAdminPass As String)
Dim entry As New System.Director yServices.Direc toryEntry(strLD AP,
strWinsAdminNam e, strAdminPass)
'Dim Flag As System.Director yServices.Direc toryEntries
Dim MyUser As System.Director yServices.Direc toryEntry
Dim searcher As New
System.Director yServices.Direc torySearcher(en try)
searcher.Filter = "(&(objectClass =User)(|(mailNi ckname=" &
strUserName & ")))"
Dim result As System.Director yServices.Searc hResultCollecti on
result = searcher.FindAl l
Dim result1 As System.Director yServices.Searc hResult
For Each result1 In result
Dim props As System.Director yServices.Resul tPropertyCollec tion
props = result1.Propert ies

Dim propNames As System.Collecti ons.ICollection
Dim propValues As System.Collecti ons.ICollection

propNames = props.PropertyN ames

Dim enumerator As IEnumerator

enumerator = propNames.GetEn umerator

'open file to write data to it
Dim fs As System.IO.FileS tream =
System.IO.File. Create("c:\User Data.txt")
Dim sw As New System.IO.Strea mWriter(fs)

For i As Integer = 0 To propNames.Count
If enumerator.Move Next() Then
sw.Write(enumer ator.Current.To String() &
ControlChars.Ta b)
Dim resultValuesCol l As
System.Director yServices.Resul tPropertyValueC ollection
resultValuesCol l =
props.Item(enum erator.Current. ToString)
For j As Integer = 0 To resultValuesCol l.Count - 1
sw.Write(result ValuesColl(j).T oString & ",")
Next
sw.Write(Contro lChars.CrLf)
End If
Next
sw.Flush()
sw.Close()
fs.Close()
Next
End Sub
Function GetActiveDirect oryUsers(ByVal strUserName As String, ByVal
strLDAP As String, ByVal strWinsAdminNam e As String, ByVal strAdminPass As
String) As String
Dim intCount As Integer
Dim strsAMAccountNa me 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.Director yServices.Direc toryEntry(strLD AP,
strWinsAdminNam e, strAdminPass)
'Dim Flag As System.Director yServices.Direc toryEntries
Dim MyUser As System.Director yServices.Direc toryEntry
Dim intAccountContr ol As Integer
Dim intResult As Integer
Dim searcher As New
System.Director yServices.Direc torySearcher(en try)
searcher.Filter = "(&(objectClass =User)(|(mailNi ckname=" &
strUserName & ")))"
Dim result As System.Director yServices.Searc hResultCollecti on
result = searcher.FindAl l
Dim result1 As System.Director yServices.Searc hResult
For Each result1 In result
Try
MyUser = New
System.Director yServices.Direc toryEntry(resul t1.Path)
Dim x, y As System.Collecti ons.ICollection
If
Microsoft.Visua lBasic.Strings. InStr(result1.P roperties("mail Nickname")(0),
"SystemMailbox" , Microsoft.Visua lBasic.CompareM ethod.Text) = 0 Then
'result1.GetDir ectoryEntry()
strsAMAccountNa me =
result1.Propert ies("sAMAccount Name")(0)
'The following is the Alias
Try
strmailname = result1.Propert ies("mail")(0)
Catch ex As Exception
'strmailname = "@" 'userPrincipalN ame
strmailname =
result1.Propert ies("userPrinci palName")(0)
End Try
Try
strDept = result1.Propert ies("department ")(0)
Catch ex As Exception
strDept = "@"
End Try
Try
strFullName = result1.Propert ies("displayNam e")(0)
Catch ex As Exception
strFullName = "@"
End Try
intAccountContr ol =
result1.Propert ies("userAccoun tControl")(0) 'take care
intResult = intAccountContr ol 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 GetStrWinsAdmin UserName(ByVal strDC As String) As String
Dim strWinsName, strAdminUserNam e As String
Dim arrstrDC() As String
arrstrDC = strDC.Split("." )
strWinsName = arrstrDC(0)
strAdminUserNam e =
System.Configur ation.Configura tionSettings.Ap pSettings("Admi nUserName")
Return strWinsName & "\" & strAdminUserNam e
End Function
Public Function FormatStrLDAP(B yVal strActiveDirect oryIP 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(intCou nt) & ","
Next
strDC = strDC.Substring (0, strDC.Length - 1)
strLDAP = "LDAP://" & strActiveDirect oryIP & "/" & 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 UserAccountCont rol property value.
_______________ ______
c# sample
using System;
using System.Collecti ons;
using System.Drawing;
using System.Windows. Forms;
using System.Globaliz ation;
using System.Runtime. InteropServices ;

namespace PowerAD
{

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

/// <summary>
/// Implementation of IComparer.Compa re
/// </summary>
/// <param name="lhs">Firs t Object to compare</param>
/// <param name="rhs">Seco nd 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.Li stViewSubItemCo llection lhsItems =
lhsLvi.SubItems ;
ListViewItem.Li stViewSubItemCo llection 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.Leng th == 0 || rhsText.Length == 0)
result = lhsText.Compare To(rhsText);

else
result = OnCompare(lhsTe xt, rhsText);

if(!m_ascending )
result = -result;

return result;
}

/// <summary>
/// Overridden to do type-specific comparision.
/// </summary>
/// <param name="lhs">Firs t Object to compare</param>
/// <param name="rhs">Seco nd 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(Strin g 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 ListViewTextCas eInsensitiveSor t: ListViewTextSor t
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="sortColum n">Column to be sorted</param>
/// <param name="ascending ">true, if ascending order, false
otherwise</param>
public ListViewTextCas eInsensitiveSor t(Int32 sortColumn, Boolean
ascending):
base(sortColumn , ascending)
{
}

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

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

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

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

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

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

/// <summary>
/// Integer compare
/// </summary>
protected override Int32 OnCompare(Strin g lhs, String rhs)
{
return (Int32)(Int64.P arse(lhs, NumberStyles.Nu mber) - Int64.Parse(rhs ,
NumberStyles.Nu mber));
}
}

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

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

if(result > 0)
return 1;

else if(result < 0)
return -1;

else
return 0;
}
}

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

m_list = list;
m_comparers = comparers;

m_imgList = new ImageList();
m_imgList.Image Size = new Size(8, 8);
m_imgList.Trans parentColor = System.Drawing. Color.Magenta;

m_imgList.Image s.Add(GetArrowB itmap(ArrowType .Ascending)); // Add
ascending arrow
m_imgList.Image s.Add(GetArrowB itmap(ArrowType .Descending)); // Add
descending arrow

SetHeaderImageL ist(m_list, m_imgList);

list.ColumnClic k += new ColumnClickEven tHandler(Column Click);
}

/// <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">C olumn index</param>
/// <returns></returns>
public Type GetColumnCompar erType(Int32 column)
{
return m_comparers[column];
}

/// <summary>
/// Sets the type of the comparer for the given column
/// </summary>
/// <param name="column">C olumn index</param>
/// <param name="comparerT ype">Comparer type</param>
public void SetColumnCompar erType(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 SetComparerType s(Type[] comparers)
{
m_comparers = comparers;
}

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

if(column == m_column)
order = (m_sortOrder == SortOrder.Ascen ding) ? SortOrder.Desce nding :
SortOrder.Ascen ding;

Sort(column, order);
}

/// <summary>
/// Sorts the rows based on the given column and sort order
/// </summary>
/// <param name="column">C olumn to be sorted</param>
/// <param name="order">So rt order</param>
public void Sort(Int32 column, SortOrder order)
{
if(column < 0 || column >= m_comparers.Len gth)
throw new IndexOutOfRange Exception();

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)
{
ListViewTextSor t comp = (ListViewTextSo rt)
Activator.Creat eInstance(m_com parers[m_column], new Object[] { m_column,
order == SortOrder.Ascen ding } );
m_list.ListView ItemSorter = comp;
}
}

/// <summary>
/// ColumnClick event handler
/// </summary>
/// <param name="sender">E vent sender</param>
/// <param name="e">Event arguments</param>
private void ColumnClick(obj ect sender, ColumnClickEven tArgs e)
{
this.Sort(e.Col umn);
}

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
6682
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 Visual Basic .NET version of this article, see 308049. For a Microsoft Visual C++ .NET version of this article, see 310071. For a Microsoft Visual J#...
1
29146
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 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...
1
5195
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 when existing Try
0
2145
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 error: Error Type: Microsoft VBScript runtime (0x800A000D) Type mismatch Code:
0
1629
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 I would like to get the NDS side working during the transition. I know the concept of what required Microsoft's information is very sparse and...
3
4078
by: Ram | last post by:
How to Authenticate NDS server using C#
1
2215
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> <head> <title>New Page 2</title> </head>
6
4066
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, having been advised by several luminaries that that is a "good thing to do"... :-) However, I'm experiencing a problem with the IEnumerable...
0
3205
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 given all the attributes which are needed, for the user, in the code and also the proper path where the user has to be added. Please have a look at my...
0
7465
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7656
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7805
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7416
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7752
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5969
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5325
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
701
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.