📘 ActiveDirectoryService Documentation

A comprehensive guide to the ActiveDirectoryService.cs file in the IrbyImaging.UI project


Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Architecture & UML Diagram
  4. Key Functional Areas
    4.1. Interface: IActiveDirectoryService
    4.2. Implementation: ActiveDirectoryService
       • User Lookup by Username
       • User Lookup by Employee Number
       • Phone Number Retrieval
       • User List Retrieval
  5. Helper Methods & Utilities
  6. Data Models & View Models
  7. Error Handling & Return Types
  8. Third‑Party Integrations
  9. Usage Examples & Code Snippets
  10. Conclusion

1. Overview & Purpose

ActiveDirectoryService.cs provides a thin wrapper around Microsoft’s Active Directory APIs to fetch user and employee information for the Irby Construction organization. It exposes a simple interface to:

  • Query users by SAM account name (username)
  • Query users by employee number
  • Retrieve phone numbers
  • Build a dropdown list (SelectListItem) of all users

This service abstracts away raw LDAP paths, sorting logic, property checks, and repeated boilerplate.


2. Dependencies & Technologies

Category Technology / Namespace
.NET Core / ASP.NET Microsoft.AspNetCore.Mvc.Rendering
Directory Services System.DirectoryServices
Domain / Models IrbyImaging.DomainClassesIrbyImaging.ModelsIrbyImaging.UI.Models.Employee
C# Language Features Interfaces, Generics, Collection Initializers

3. Architecture & UML Diagram

classDiagram
    class IActiveDirectoryService {
      <<interface>>
      +EmployeeDetail GetUserDetailsFromActiveDirectory(string username)
      +string GetPhoneNumberFromActiveDirectory(string employeeNumber)
      +List<SelectListItem> GetUserList()
    }

    class ActiveDirectoryService {
      +EmployeeDetail GetUserDetailsFromActiveDirectory(string username)
      +EmployeeDetail GetEmployeeFromActiveDirectory(string employeeNumber)
      +string GetPhoneNumberFromActiveDirectory(string employeeNumber)
      +List<SelectListItem> GetUserList()
      -DirectorySearcher PrepareForIrbyActiveDirectorySearch()
      -string GetActiveDirectoryPropertyIfExists(SearchResult result, string property)
    }

    IActiveDirectoryService <|.. ActiveDirectoryService

4. Key Functional Areas

4.1 Interface: IActiveDirectoryService

public interface IActiveDirectoryService
{
    EmployeeDetail GetUserDetailsFromActiveDirectory(string username);
    string GetPhoneNumberFromActiveDirectory(string employeeNumber);
    List<SelectListItem> GetUserList();
}
Method Description
GetUserDetailsFromActiveDirectory(string) Returns full EmployeeDetail using SAM account name.
GetPhoneNumberFromActiveDirectory(string) Returns home phone number by employee number.
GetUserList() Returns a list of <SelectListItem> (Value=SAM, Text=DisplayName)

4.2 Implementation: ActiveDirectoryService

public class ActiveDirectoryService : IActiveDirectoryService
{
    // … methods here …
}

User Lookup by Username

public EmployeeDetail GetUserDetailsFromActiveDirectory(string username)
{
    var userSearcher = PrepareForIrbyActiveDirectorySearch();
    userSearcher.Filter = "(samAccountName=" + username + ")";
    var result = userSearcher.FindOne();

    return new EmployeeDetail
    {
        Username       = username,
        FullName       = GetActiveDirectoryPropertyIfExists(result, "displayName"),
        PhoneNumber    = GetActiveDirectoryPropertyIfExists(result, "mobile"),
        Email          = GetActiveDirectoryPropertyIfExists(result, "mail"),
        Title          = GetActiveDirectoryPropertyIfExists(result, "title"),
        Department     = GetActiveDirectoryPropertyIfExists(result, "department"),
        EmployeeNumber = GetActiveDirectoryPropertyIfExists(result, "employeeNumber")
    };
}

Flow

  1. Prepare a DirectorySearcher scoped to Irby’s LDAP OU
  2. Filter by (samAccountName=… )
  3. Fetch first result (FindOne())
  4. Map properties to EmployeeDetail

User Lookup by Employee Number

public EmployeeDetail GetEmployeeFromActiveDirectory(string employeeNumber)
{
    var searcher = PrepareForIrbyActiveDirectorySearch();
    searcher.Filter = "(employeeNumber=" + employeeNumber + ")";
    var result = searcher.FindOne();

    if (result == null)
        return new EmployeeDetail(); // empty

    return new EmployeeDetail
    {
        FullName       = GetActiveDirectoryPropertyIfExists(result, "displayName"),
        PhoneNumber    = GetActiveDirectoryPropertyIfExists(result, "mobile"),
        Email          = GetActiveDirectoryPropertyIfExists(result, "mail"),
        Title          = GetActiveDirectoryPropertyIfExists(result, "title"),
        Department     = GetActiveDirectoryPropertyIfExists(result, "department"),
        EmployeeNumber = GetActiveDirectoryPropertyIfExists(result, "employeeNumber")
    };
}

Note: This method is not declared in the interface but offers similar functionality to the username lookup.


Phone Number Retrieval

public string GetPhoneNumberFromActiveDirectory(string employeeNumber)
{
    var searcher = PrepareForIrbyActiveDirectorySearch();
    searcher.Filter = "(employeeNumber=" + employeeNumber + ")";
    var result = searcher.FindOne();

    return GetActiveDirectoryPropertyIfExists(result, "homePhone");
}

Retrieves home phone number by employee number.


User List Retrieval

public List<SelectListItem> GetUserList()
{
    var items = new List<SelectListItem>();
    var searcher = PrepareForIrbyActiveDirectorySearch();
    searcher.Filter = "(objectClass=user)";

    foreach (SearchResult result in searcher.FindAll())
    {
        items.Add(new SelectListItem
        {
            Value = GetActiveDirectoryPropertyIfExists(result, "samAccountName"),
            Text  = GetActiveDirectoryPropertyIfExists(result, "displayName")
        });
    }

    return items;
}
  • Filter: All objects of class user
  • Sort: By displayName (configured in the helper)
  • Map: samAccountName → Value, displayName → Text

5. Helper Methods & Utilities

PrepareForIrbyActiveDirectorySearch

private DirectorySearcher PrepareForIrbyActiveDirectorySearch()
{
    const string irbyPath = "LDAP://OU=users,OU=Irby Construction,OU=Quanta Subsidiaries,DC=quantaservices,DC=local";
    var entry = new DirectoryEntry(irbyPath);
    var ds    = new DirectorySearcher(entry)
    {
        SearchScope = SearchScope.Subtree
    };

    // Load only required properties
    var props = new[] { "samAccountName", "displayName", "mobile", "mail", "title", "department", "employeeNumber" };
    foreach (var p in props)
        ds.PropertiesToLoad.Add(p);

    // Sort by display name ascending
    ds.Sort.Direction    = SortDirection.Ascending;
    ds.Sort.PropertyName = "displayName";

    return ds;
}

Pre-configures path, scope, properties and sorting.


GetActiveDirectoryPropertyIfExists

private string GetActiveDirectoryPropertyIfExists(SearchResult result, string property)
{
    return (result?.Properties[property].Count > 0)
        ? result.Properties[property][0].ToString()
        : string.Empty;
}
  • Null-check & zero-count guard
  • Returns empty string when no value exists

6. Data Models & View Models

  • EmployeeDetail (likely in IrbyImaging.UI.Models.Employee)

    Property Type Description
    Username string SAM account name (login)
    FullName string Display name in AD
    PhoneNumber string Mobile number
    Email string Email address
    Title string Job title
    Department string Department name
    EmployeeNumber string Organizational employee ID
  • SelectListItem (ASP.NET MVC)

    Property Type Description
    Value string Underlying option value
    Text string Display text in dropdown

7. Error Handling & Return Types

  • Empty Results:
    • GetUserDetailsFromActiveDirectory will return an EmployeeDetail with empty properties if AD returns nothing.
    • GetEmployeeFromActiveDirectory explicitly returns a new, empty EmployeeDetail.
  • Exceptions:
    • Directory access exceptions (e.g. binding failures) bubble up to caller. Consider wrapping calls in try/catch in production.

8. Third‑Party Integrations

  • Active Directory (LDAP)
  • ASP.NET MVC for SelectListItem

No external NuGet beyond standard .NET and Microsoft packages.


9. Usage Examples & Code Snippets

public class EmployeeController : Controller
{
    private readonly IActiveDirectoryService _adService;

    public EmployeeController(IActiveDirectoryService adService)
    {
        _adService = adService;
    }

    public IActionResult Details(string username)
    {
        // 🔍 Lookup by username
        var employee = _adService.GetUserDetailsFromActiveDirectory(username);
        return View(employee);
    }

    public IActionResult Phone(string empNumber)
    {
        // 📞 Phone retrieval
        var phone = _adService.GetPhoneNumberFromActiveDirectory(empNumber);
        return Content($"Employee Phone: {phone}");
    }

    public IActionResult Dropdown()
    {
        // 📋 Build dropdown
        ViewBag.Users = _adService.GetUserList();
        return View();
    }
}

Razor dropdown example:

<select asp-items="ViewBag.Users" class="form-control"></select>

10. Conclusion

🎯 ActiveDirectoryService streamlines LDAP lookups for the IrbyImaging UI, hiding low‑level DirectoryServices details and exposing simple methods for:

  • Retrieving full user profiles
  • Fetching phone numbers
  • Populating user selection lists

With this service in place, controllers and pages can remain clean, focusing purely on presentation logic. For production, consider caching frequent lookups, error wrapping for Directory unavailability, and configuration of the LDAP path via appsettings.json.


Happy coding! 🚀