📄 UAREmail.cs Documentation

Path: IrbyImaging.BusinessLogic/Jobs/UAREmail.cs


📑 Table of Contents

  1. Overview & Purpose
  2. File Structure
  3. Dependencies & Technologies
  4. Key Functional Areas
    4.1. Job Execution (Quartz)
    4.2. ReadEmail Method
       4.2.1. Authentication (Azure AD)
       4.2.2. Graph API Calls
       4.2.3. Email Processing Logic
       4.2.4. Database Interaction
    4.3. TicketOptions Model
  5. Process Flow (Mermaid Sequence)
  6. Configuration
  7. Usage Examples
  8. Error Handling & Logging
  9. Third‑party Integrations
  10. Conclusion

🔍 Overview & Purpose

UAREmail is a Quartz job that periodically connects to a shared “helpdesk” mailbox via Microsoft Graph API, reads the latest emails, and processes approval/denial responses for support tickets stored in an Entity Framework Core database.

  • Use Case: Automate ticket status updates based on customer or stakeholder email replies containing [Approved] or [Denied] tags.
  • Outcome: The job updates each ticket’s JSON‑serialized request details and logs an Update entry reflecting the approval decision.

📂 File Structure

IrbyImaging.BusinessLogic
└── Jobs
    └── UAREmail.cs

Key Types

Class / Interface Description
UAREmail : IJob Quartz job for reading and processing emails
TicketOptions DTO representing items within a ticket’s payload

🛠 Dependencies & Technologies

Category Libraries / Frameworks
Scheduling Quartz.NET
Azure Authentication Azure.Identity (ClientSecretCredential)
Graph API Microsoft.Graph, Microsoft.Kiota.Abstractions
ORM & Data Access Microsoft.EntityFrameworkCore, custom IrbyContext
Configuration Microsoft.Extensions.Configuration
JSON Serialization Newtonsoft.Json
Miscellaneous System.Text.RegularExpressions, System.Net.WebUtility, System.Uri

🔑 Key Functional Areas

4.1 Job Execution (Quartz)

public class UAREmail : IJob
{
    public Task Execute(IJobExecutionContext context)
    {
        ReadEmail();
        return Task.CompletedTask;
    }
}
  • Implements Quartz.IJob
  • Method: Execute
    • Called by Quartz Scheduler
    • Invokes the asynchronous ReadEmail() method

4.2 ReadEmail Method

4.2.1 Authentication (Azure AD)

var scopes = new[] { "https://graph.microsoft.com/.default" };
var options = new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud };

var clientId     = _configuration["IrbySystemsAppId"];
var tenantId     = _configuration["Tenant"];
var clientSecret = _configuration["IrbySystemsGraphSecret"];

var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
  • Scopes: .default to inherit permissions granted in Azure AD
  • Credentials:
    • ClientId, TenantId, ClientSecret loaded from appsettings.json
    • Uses ClientSecretCredential for app‑only (daemon) authentication

4.2.2 Graph API Calls

var result = await graphClient
    .Users["[email protected]"]
    .Messages
    .GetAsync();
  • Endpoint: /users/{email}/messages
  • Retrieves: The first batch of messages (default page size)

4.2.3 Email Processing Logic

for (var i = 0; i < 9; i++)
{
    var res = result.Value[i];

    // Decode & normalize subject
    var decodedSubject = Uri.UnescapeDataString(res.Subject);

    // Only process [Approved] or [Denied]
    if (decodedSubject.ToLower().Contains("[approved]") 
     || decodedSubject.ToLower().Contains("[denied]"))
    {
        // Parse GUID after "ID:"
        var split = decodedSubject.Split("ID:");
        // ...validate and parse `ticketId`
        // Extract decision, item name, and comment from body preview
        // Update matching TicketOptions and persist changes
    }
}
  1. Loop: Up to 9 messages
  2. Filter: Subjects containing [Approved] or [Denied]
  3. Extract:
    • Ticket ID: GUID parsed after ID:
    • Item to match: Text between -- delimiters
    • Approval text: Body content after "============="
  4. Match: Load Ticket from DB by ID
  5. Deserialize: ticket.RequestedJson → List<TicketOptions>
  6. Update:
    • Mark HasApprovalDecision, set IsApproved flag
    • Store ApprovalMessage
    • Append an Update record
  7. Persist: await context.SaveChangesAsync()

4.2.4 Database Interaction

using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<IrbyContext>();
// Query: context.Tickets.FirstOrDefaultAsync(t => t.Id == ticketId)
// Save: await context.SaveChangesAsync();
  • Uses IServiceScopeFactory to obtain a scoped IrbyContext
  • Ensures thread safety and lifetime management

4.3 TicketOptions Model

public class TicketOptions
{
    public string Index { get; set; }
    public string Type { get; set; }
    public string Item { get; set; }
    public bool IsCompleted { get; set; }
    public bool ApprovalRequired { get; set; }
    public string ApprovalDepartment { get; set; }
    public bool HasApprovalDecision { get; set; }
    public bool IsApproved { get; set; }
    public string ApprovalMessage { get; set; }
}
Property Type Description
Index string Order or identifier within the request payload
Type string Category of this item
Item string Human‑readable name
IsCompleted bool If the item has been fulfilled
ApprovalRequired bool If an approval step was requested
ApprovalDepartment string Department responsible for approval
HasApprovalDecision bool If an approval/denial email has been processed
IsApproved bool Final decision
ApprovalMessage string Comments from the approver

🔄 Process Flow (Mermaid Sequence)

sequenceDiagram
    participant Q as Quartz Scheduler
    participant J as UAREmail Job
    participant A as Azure AD
    participant G as Microsoft Graph
    participant DB as IrbyContext (EF Core)

    Q->>J: Trigger Execute()
    J->>A: Authenticate via ClientSecretCredential
    A-->>J: Access Token
    J->>G: GET /users/helpdesk@.../messages
    G-->>J: Message list
    loop For each message
        J->>J: Decode Subject & Check [Approved]/[Denied]
        alt valid format
            J->>DB: SELECT Ticket WHERE Id==GUID
            DB-->>J: Ticket Entity
            J->>J: Deserialize TicketOptions
            J->>J: Update decision & build Update entry
            J->>DB: SaveChangesAsync()
            DB-->>J: Acknowledged
        else invalid / no ticket
            J-->>J: Log issue, continue
        end
    end
    J-->>Q: Job complete

⚙️ Configuration

appsettings.json should contain:

{
  "IrbySystemsAppId": "<Azure AD Application (Client) ID>",
  "Tenant": "<Azure AD Tenant ID>",
  "IrbySystemsGraphSecret": "<Client Secret for Graph API>"
}

Ensure that the Azure AD app has Mail.Read or Mail.ReadWrite application permissions granted.


✨ Usage Examples

  1. Register Quartz Job (in Startup.cs or Program.cs):

    services.AddQuartz(q =>
    {
        q.UseMicrosoftDependencyInjectionJobFactory();
        var jobKey = new JobKey("UAREmailJob");
        q.AddJob<UAREmail>(opts => opts.WithIdentity(jobKey));
        q.AddTrigger(opts => opts
            .ForJob(jobKey)
            .WithIdentity("UAREmailTrigger")
            .WithSimpleSchedule(x => x.WithIntervalInMinutes(5).RepeatForever())
        );
    });
    services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
    
  2. Running Locally

    • Populate appsettings.Development.json with your testing credentials.
    • Ensure EF Core migrations are applied.

🛡 Error Handling & Logging

  • ODataError Catch
    Catches Graph API errors:

    catch (ODataError odataError)
    {
        Console.WriteLine(odataError.Error.Code);
        Console.WriteLine(odataError.Error.Message);
    }
    
  • Validation & Continuation

    • Invalid GUID in subject → logs and skips
    • Missing ticket in database → logs and skips

Note: Consider integrating a structured logger (e.g., Serilog) for production.


🔗 Third‑party Integrations

Integration Purpose
Azure.Identity App‑only authentication to Graph API
Microsoft.Graph Read mailbox messages
Quartz.NET Scheduling the periodic job execution
EntityFrameworkCore CRUD operations on IrbyContext
Newtonsoft.Json JSON (de)serialization of RequestedJson

🏁 Conclusion

The UAREmail job automates the approval workflow by:

  • Periodically querying a dedicated mailbox
  • Parsing structured email replies
  • Updating the ticketing system in a SQL database

🎯 Benefits:

  • Removes manual polling of emails
  • Ensures data consistency via EF Core transactions
  • Extensible: modify regex, mailbox, or parsing logic as needed

Next Steps:

  • Add unit/integration tests for ReadEmail() logic
  • Improve logging and retry mechanisms
  • Support paging to process more than 9 messages per run

Happy Coding! 🚀