📄 UAREmail.cs Documentation
Path:
IrbyImaging.BusinessLogic/Jobs/UAREmail.cs
📑 Table of Contents
- Overview & Purpose
- File Structure
- Dependencies & Technologies
- 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 - Process Flow (Mermaid Sequence)
- Configuration
- Usage Examples
- Error Handling & Logging
- Third‑party Integrations
- 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:
.defaultto inherit permissions granted in Azure AD - Credentials:
ClientId,TenantId,ClientSecretloaded fromappsettings.json- Uses
ClientSecretCredentialfor 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
}
}
- Loop: Up to 9 messages
- Filter: Subjects containing
[Approved]or[Denied] - Extract:
- Ticket ID: GUID parsed after
ID: - Item to match: Text between
--delimiters - Approval text: Body content after
"============="
- Ticket ID: GUID parsed after
- Match: Load
Ticketfrom DB by ID - Deserialize:
ticket.RequestedJson→List<TicketOptions> - Update:
- Mark
HasApprovalDecision, setIsApprovedflag - Store
ApprovalMessage - Append an
Updaterecord
- Mark
- 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
IServiceScopeFactoryto obtain a scopedIrbyContext - 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
-
Register Quartz Job (in
Startup.csorProgram.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); -
Running Locally
- Populate
appsettings.Development.jsonwith your testing credentials. - Ensure EF Core migrations are applied.
- Populate
🛡 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! 🚀