473,387 Members | 1,705 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,387 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 5023
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...

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.