common/Utils/UserAccessCtrl/SoftwareUser.cs
2026-04-23 17:50:07 +02:00

115 lines
5.4 KiB
C#

using System;
using System.Collections;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
namespace Xylem.Common.Utils.UserAccessCtrl
{
internal class SoftwareUser
{
public SoftwareUser()
=> InitializeSoftwareUser();
public Int32 EmployeeId { get; private set; }
public String FirstName { get; private set; }
public String LastName { get; private set; }
public String Username { get; private set; }
public String Phone { get; private set; }
public String Email { get; private set; }
private void InitializeSoftwareUser()
{
try
{
var currentUser = UserPrincipal.Current;
using (var directoryEntry = new DirectoryEntry($"LDAP://{currentUser.DistinguishedName}"))
{
using (var directorySearcher = new DirectorySearcher(directoryEntry))
{
var searchResult = directorySearcher.FindOne();
foreach (DictionaryEntry dictionaryEntry in searchResult.Properties)
{
if (dictionaryEntry.Key is String property)
{
if (property.Equals("employeeid", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String value)
{
if (int.TryParse(value, out Int32 employeeId))
{
EmployeeId = employeeId;
}
}
}
}
else if (property.Equals("givenname", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String firstName)
{
FirstName = firstName;
}
}
}
else if (property.Equals("sn", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String lastName)
{
LastName = lastName;
}
}
}
else if (property.Equals("mail", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String email)
{
Email = email;
}
}
}
else if (property.Equals("telephonenumber", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String phone)
{
Phone = phone;
}
}
}
else if (property.Equals("samaccountname", StringComparison.OrdinalIgnoreCase))
{
if (dictionaryEntry.Value is ResultPropertyValueCollection dictionaryEntryValues)
{
if (dictionaryEntryValues.Count > 0 && dictionaryEntryValues[0] is String username)
{
Username = username.ToLower();
}
}
}
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}