AzureADRead Service Documentation 🚀

Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Class Diagram (Mermaid UML)
  4. Key Functional Areas
  5. Detailed Method Descriptions
    5.1. GetUserADList
    5.2. GetSignInActivity
    5.3. GetUser
    5.4. GetUserDetails
    5.5. GetAllUserADList
  6. Data Models
  7. Error Handling & Return Types
  8. Third‑party Integrations
  9. Usage Examples
  10. Conclusion

1. Overview & Purpose

AzureADRead is a service in the IrbyImaging.UI project that:

  • Authenticates against Azure AD using client‐credential flow
  • Calls Microsoft Graph to retrieve user profiles & sign‑in activity
  • Augments AD data with internal business data (via IrbyContext)
  • Prepares lists for UI dropdowns (e.g. SelectListItem)

This centralizes all Azure AD reading logic, simplifies controllers, and ensures consistent mapping to an Employee view model.


2. Dependencies & Technologies

Package / Namespace Purpose
Azure.Identity ClientSecretCredential & token acquisition
Microsoft.Graph GraphServiceClient to call Microsoft Graph endpoints
Microsoft.AspNetCore.Mvc.Rendering SelectListItem for ASP.NET Core dropdown bindings
Microsoft.EntityFrameworkCore Local DB context (IrbyContext) queries
Microsoft.Extensions.Configuration Reads ClientId, Tenant, ClientSecret from configuration
Newtonsoft.Json JSON serialization (imported but not used directly)
IrbyImaging.* Internal models, view models & utilities

3. Class Diagram (Mermaid UML)

classDiagram
    AzureADRead --> IrbyContext
    AzureADRead --> IConfiguration
    AzureADRead ..> Employee : returns
    AzureADRead ..> List~SelectListItem~ : returns

    class AzureADRead {
        - IrbyContext _context
        - IConfiguration _configuration
        + AzureADRead(IrbyContext, IConfiguration)
        + Task<Employee> GetUserADList(string email)
        + Task<Employee> GetSignInActivity(string name)
        + Task<Employee> GetUser(string username)
        + Employee GetUserDetails(string email)
        + List<SelectListItem> GetAllUserADList(string email)
    }

    class Employee {
        + Guid UserId
        + string FullName
        + string Title
        + string Department
        + string Email
        + string EmployeeNumber
        + string PhoneNumber
        + DateTime? LastSignInDateTime
        + DateTime? LastNonInteractiveSignInDateTime
        + string JobNumber
    }

4. Key Functional Areas

Functional Area Description
Authentication Builds ClientSecretCredential using values from IConfiguration
Graph Client Initialization Instantiates GraphServiceClient with credential & scopes
User Data Retrieval Queries user profile & sign‑in activity from Microsoft Graph
Business Data Augmentation Joins AD data with local DB (IrbyContext.Employees & Jobs)
UI Dropdown Population Builds List<SelectListItem> for active employees

5. Detailed Method Descriptions

5.1 GetUserADList(string email)

Fetches a user from Azure AD by email, then populates an Employee object with profile & sign‑in data.

public async Task<Employee> GetUserADList(string email)
{
    // 1. Split email to get username
    var username = email.Split('@')[0];

    // 2. Build credential & Graph client
    var graphClient = CreateGraphClient();

    // 3. Primary AD fetch
    var user = await graphClient.Users[email].GetAsync();

    // 4. Secondary fetch (Department + SignInActivity)
    var result = await graphClient.Users.GetAsync(cfg =>
    {
        cfg.QueryParameters.Filter = $"id eq '{user.Id}'";
        cfg.QueryParameters.Select = new[] { "displayName", "signInActivity", "Department" };
    });

    // 5. Map to Employee view model
    var emp = new Employee
    {
        FullName = user.DisplayName,
        Title = user.JobTitle,
        Department = user.Department,
        Email = email,
        EmployeeNumber = user.EmployeeId,
        PhoneNumber = user.MobilePhone,
        UserId = Guid.Parse(user.Id)
    };

    // 6. Map signInActivity if present
    if (result.Value.Any() && result.Value[0].SignInActivity != null)
    {
        var sa = result.Value[0].SignInActivity;
        emp.LastSignInDateTime             = sa.LastSignInDateTime?.DateTime;
        emp.LastNonInteractiveSignInDateTime = sa.LastNonInteractiveSignInDateTime?.DateTime;
        emp.Department                     = result.Value[0].Department ?? emp.Department;
    }

    return emp;
}

5.2 GetSignInActivity(string name)

Searches users whose displayName starts with name and returns sign‑in data.

Note: The returned Employee is currently empty—mapping logic can be added.

public async Task<Employee> GetSignInActivity(string name)
{
    var graphClient = CreateGraphClient();
    var result = await graphClient.Users.GetAsync(cfg =>
    {
        cfg.QueryParameters.Filter = $"startswith(displayName,'{name}')";
        cfg.QueryParameters.Select = new[] { "displayName", "signInActivity" };
    });
    // TODO: Map 'result' to Employee
    return new Employee();
}

5.3 GetUser(string username)

Fetches a user by exact displayName, then enriches with sign‑in data.

public async Task<Employee> GetUser(string username)
{
    var graphClient = CreateGraphClient();

    // 1. Filter by displayName
    var result = await graphClient.Users.GetAsync(cfg =>
    {
        cfg.QueryParameters.Filter = $"displayName eq '{username}'";
        cfg.QueryParameters.Select = new[] { "id", "mail", "displayName", "signInActivity", "Department" };
    });

    // 2. Get the primary user object
    var usr = await graphClient.Users[username].GetAsync();

    // 3. Map to Employee
    var emp = new Employee
    {
        FullName        = usr.DisplayName,
        Title           = usr.JobTitle,
        Department      = usr.Department,
        Email           = usr.Mail,
        EmployeeNumber  = usr.EmployeeId,
        PhoneNumber     = usr.MobilePhone
    };

    // 4. Map signInActivity
    if (result.Value.Any() && result.Value[0].SignInActivity != null)
    {
        var sa = result.Value[0].SignInActivity;
        emp.LastSignInDateTime             = sa.LastSignInDateTime?.DateTime;
        emp.LastNonInteractiveSignInDateTime = sa.LastNonInteractiveSignInDateTime?.DateTime;
        emp.Department                     = result.Value[0].Department ?? emp.Department;
    }

    return emp;
}

5.4 GetUserDetails(string email)

Combines AD info with local DB.

  1. Calls GetUserADList(email)
  2. Attempts to find a matching record in _context.Employees
  3. If found, patches JobNumber via _context.Jobs
  4. Returns a final Employee
public Employee GetUserDetails(string email)
{
    var res      = GetUserADList(email).Result;
    var dbEmp    = _context.Employees
                   .FirstOrDefault(e => e.DisplayName == res.FullName 
                                     || e.WorkEmail   == email);

    var emp = new Employee();
    if (dbEmp == null)
    {
        // AD‐only
        emp = res;
    }
    else
    {
        // Augment with JDE job number
        var job = _context.Jobs.FirstOrDefault(j => j.JobId == dbEmp.JobId);
        emp.JobNumber     = job?.JdeNumber;
        emp.FullName      = dbEmp.DisplayName;
        emp.Email         = res.Email;
        emp.EmployeeNumber= dbEmp.JdeNumber;
        emp.PhoneNumber   = res.PhoneNumber;
        emp.Title         = res.Title;
        emp.Department    = res.Department;
    }

    return emp;
}

5.5 GetAllUserADList(string email)

Produces a list of active employees (SelectListItem) for UI dropdowns:

public List<SelectListItem> GetAllUserADList(string email)
{
    return _context.Employees
        .Where(e => e.Status != EmployeeStatus.Terminated)
        .Select(e => new SelectListItem
        {
            Value = e.JdeNumber,
            Text  = $"{e.LastName}, {e.FirstName}"
        })
        .ToList();
}

6. Data Models

Model Key Properties
Employee (ViewModel) Guid UserIdstring FullNamestring Titlestring Departmentstring Emailstring EmployeeNumberstring PhoneNumberDateTime? LastSignInDateTimeDateTime? LastNonInteractiveSignInDateTimestring JobNumber

Note: The Employee class resides in IrbyImaging.ViewModels and is used to carry user data to the UI.


7. Error Handling & Return Types

  • Return Types:

    • Asynchronous: Task<Employee>
    • Synchronous: Employee, List<SelectListItem>
  • Exceptions:

    • Graph API errors (ODataError) are not explicitly caught—recommend wrapping Graph calls in try/catch for graceful failure.
    • Database lookups may throw if context is misconfigured; ensure migrations & schema are up‑to‑date.

8. Third‑party Integrations

Integration Details
Microsoft Graph Fetch user profiles, sign‑in activity, department, etc.
Azure Identity ClientSecretCredential—enables secure token acquisition
EntityFramework CRUD operations on local SQL DB via IrbyContext

9. Usage Examples

9.1 Registering the Service (Startup.cs)

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<IrbyContext>(options => /* 
 */);
    services.AddScoped<AzureADRead>();
    // 
 other services
}

9.2 Inject & Use in an MVC Controller

public class UserController : Controller
{
    private readonly AzureADRead _azureAdRead;

    public UserController(AzureADRead azureAdRead)
    {
        _azureAdRead = azureAdRead;
    }

    public async Task<IActionResult> Profile(string email)
    {
        var employee = await _azureAdRead.GetUserADList(email);
        return View(employee);
    }
}

9.3 Razor View Snippet

@model Employee

<h2>đŸ‘€ @Model.FullName</h2>
<p>
    <strong>Email:</strong> @Model.Email<br/>
    <strong>Title:</strong> @Model.Title<br/>
    <strong>Department:</strong> @Model.Department<br/>
    <strong>Last Sign‑In:</strong> @Model.LastSignInDateTime?.ToString("g") 
</p>

10. Conclusion ✅

The AzureADRead service encapsulates all interactions with Azure AD and Microsoft Graph, provides a unified Employee view model, and blends AD data with local business rules. By centralizing this logic:

  • 👉 Controllers stay lean and focused on HTTP concerns
  • 👉 Reusability is maximized across pages & features
  • 👉 Maintainability improves through a single source of truth for AD reads

Future enhancements may include caching responses, implementing paging for large user sets, and robust error handling (e.g., retry policies).

Happy coding! 🎉