📚 AuditRepository Documentation
Welcome to the comprehensive guide on IrbyImaging/UI/Repository/AuditRepository.cs! This document will walk you through the purpose, design, usage, and inner workings of the AuditRepository class, complete with diagrams, code snippets, tables, and practical examples.
📑 Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Data Models & View Models
- Key Functional Areas
- Error Handling & Return Types
- Configuration & Dependency Injection
- UML Class Diagram
- Sample Code Blocks & Usage Examples
- Conclusion
1. Overview & Purpose
The AuditRepository is responsible for capturing and persisting user audit logs—tracking who did what, when, and from where in the application. By centralizing audit log insertion into one repository, you ensure consistent, maintainable, and testable code for all your auditing needs.
- Namespace:
IrbyImaging.UI.Repository - Primary Responsibility: Insert audit details into the database.
- Intended Use: Called whenever you want to record user activity (e.g., login attempts, page visits, actions performed).
2. Dependencies & Technologies
| Component | Purpose |
|---|---|
| Microsoft.EntityFrameworkCore (EF Core) | ORM for database interactions (IrbyContext) |
| IrbyImaging.DomainClasses | Contains the AuditDetail EF entity |
| IrbyImaging.Models | Contains the Employee domain model |
| IrbyImaging.UI.Models | Contains the AuditModel view model |
| System | Base .NET types (e.g., DateTime, Guid) |
| Microsoft.AspNetCore.Http | (Imported but not used directly in this file) |
| Microsoft.Extensions.Configuration | (Imported but not used directly in this file) |
🔧 Note: Some imported namespaces (e.g.,
System.Data,SqlClient) aren’t utilized in the current implementation and can be cleaned up.
3. Data Models & View Models
📋 View Model: AuditModel
Represents the data passed from UI or service layers into the repository.
| Property | Type | Description |
|---|---|---|
| UserEmail | string | Email of the user performing the action |
| SessionId | string | Unique session identifier |
| IpAddress | string | Client IP address |
| PageAccessed | string | URL or name of the page visited |
| LoginStatus | string | e.g., “Success”, “Failed” |
| ControllerName | string | MVC Controller handling the request |
| ActionName | string | MVC Action being executed |
| UrlReferrer | string | Previous page URL |
| Area | string | MVC Area name (if any) |
| LangId | int | Language identifier |
| IsFirstLogin | bool | Flag for first-time login |
| DocumentImageId | Guid? | Reference to a document image (optional) |
| Namespace | string | Code namespace for further context |
⚙️ EF Entity: AuditDetail
Maps directly to the AuditDetails table in SQL via EF Core.
| Column | Type | Description |
|---|---|---|
| AuditDetailId (PK) | Guid | Unique identifier for the audit record |
| UserId | int | Internal user ID |
| EmployeeEmail | string | The user’s email |
| SessionId | string | Session identifier |
| IpAddress | string | Client IP address |
| PageAccessed | string | Page visited |
| ActivityDate | DateTime | Timestamp of the activity |
| LoginStatus | string | “Success” / “Failed” etc. |
| ControllerName | string | MVC Controller |
| ActionName | string | MVC Action |
| UrlReferrer | string | Referring URL |
| Area | string | MVC Area |
| RoleId | int? | User’s role ID (nullable) |
| EmployeeId | int? | Employee table FK (nullable) |
| LangId | int | Language ID |
| IsFirstLogin | bool | First login indicator |
| DocumentImageId | Guid? | FK to document image (nullable) |
| Namespace | string | Contextual code namespace |
| LastSignInDateTime | DateTime? | Last interactive sign-in (nullable) |
| LastNonInteractiveSignInDateTime | DateTime? | Last non-interactive sign-in (nullable) |
👷♂️ DomainEntity: Employee
Used to enrich the AuditDetail with RoleId and EmployeeId.
4. Key Functional Areas
-
Constructor Injection
- Receives an instance of
IrbyContext(EF DbContext). - Secures a single point for DB access.
- Receives an instance of
-
InsertAuditLogs Method
Signature:public void InsertAuditLogs(AuditModel objauditmodel, IrbyImaging.Models.Employee emp)- Gathers both UI-level (
AuditModel) and domain-level (Employee) data. - Maps properties onto a new
AuditDetailentity. - Uses EF Core to add and save the record to the database.
- Gathers both UI-level (
-
Property Mapping
Source (AuditModel) Target (AuditDetail) objauditmodel.UserEmail EmployeeEmail objauditmodel.SessionId SessionId objauditmodel.IpAddress IpAddress objauditmodel.PageAccessed PageAccessed objauditmodel.LoginStatus LoginStatus objauditmodel.ControllerName ControllerName objauditmodel.ActionName ActionName objauditmodel.UrlReferrer UrlReferrer objauditmodel.Area Area objauditmodel.LangId LangId objauditmodel.IsFirstLogin IsFirstLogin objauditmodel.DocumentImageId DocumentImageId objauditmodel.Namespace Namespace DateTime.Now ActivityDate Employee props (if found) RoleId, EmployeeId, LastSignIn..., etc.
5. Error Handling & Return Types
-
Return Type:
void— this method does not return any data.- Any exception bubbles up to the caller.
-
Error Handling:
try { // build & save audit record } catch (Exception) { // Rethrows the original exception throw; }⚠️ Tip: Consider logging the exception or wrapping it in a custom exception for richer context!
6. Configuration & Dependency Injection
To start using AuditRepository, register it in your Startup.cs (or wherever you configure DI):
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<IrbyContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// Register repository
services.AddScoped<AuditRepository>();
}
Then, inject and use in any controller or service:
public class HomeController : Controller
{
private readonly AuditRepository _auditRepo;
public HomeController(AuditRepository auditRepo)
{
_auditRepo = auditRepo;
}
public IActionResult Index()
{
var auditModel = new AuditModel
{
UserEmail = User.Identity.Name,
SessionId = HttpContext.Session.Id,
IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(),
PageAccessed = "Home/Index",
LoginStatus = "Success",
ControllerName = "Home",
ActionName = "Index",
UrlReferrer = Request.Headers["Referer"].ToString(),
Area = "",
LangId = 1,
IsFirstLogin = false,
Namespace = nameof(HomeController)
};
// Suppose 'employee' loaded from context or user store
Employee currentEmp = /* get from DbContext or authentication ticket */;
_auditRepo.InsertAuditLogs(auditModel, currentEmp);
return View();
}
}
7. UML Class Diagram
classDiagram
AuditRepository ..> IrbyContext
AuditRepository ..> AuditModel
AuditRepository ..> Employee
AuditRepository --> AuditDetail
class AuditRepository {
+InsertAuditLogs(AuditModel objauditmodel, Employee emp) : void
}
class IrbyContext {
+DbSet<AuditDetail> AuditDetails
+DbSet<Employee> Employees
+SaveChanges() : int
}
class AuditModel {
+string UserEmail
+string SessionId
+string IpAddress
+string PageAccessed
+string LoginStatus
+string ControllerName
+string ActionName
+string UrlReferrer
+string Area
+int LangId
+bool IsFirstLogin
+Guid? DocumentImageId
+string Namespace
}
class Employee {
+int UserId
+string Email
+DateTime? LastSignInDateTime
+DateTime? LastNonInteractiveSignInDateTime
+int RoleId
+int EmployeeId
}
class AuditDetail {
+Guid AuditDetailId
+int UserId
+string EmployeeEmail
+string SessionId
+string IpAddress
+string PageAccessed
+DateTime ActivityDate
+string LoginStatus
+string ControllerName
+string ActionName
+string UrlReferrer
+string Area
+int? RoleId
+int? EmployeeId
+int LangId
+bool IsFirstLogin
+Guid? DocumentImageId
+string Namespace
+DateTime? LastSignInDateTime
+DateTime? LastNonInteractiveSignInDateTime
}
8. Sample Code Blocks & Usage Examples
Instantiating & Using the Repository
// In Startup.cs
services.AddScoped<AuditRepository>();
// In any controller
public class AccountController : Controller
{
private readonly AuditRepository _auditRepo;
public AccountController(AuditRepository auditRepo)
{
_auditRepo = auditRepo;
}
[HttpPost]
public IActionResult Login(LoginViewModel model)
{
// Authenticate user...
var emp = _context.Employees.FirstOrDefault(e => e.Email == model.Email);
var audit = new AuditModel
{
UserEmail = model.Email,
SessionId = HttpContext.Session.Id,
IpAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
PageAccessed = "Account/Login",
LoginStatus = emp != null ? "Success" : "Failure",
ControllerName = "Account",
ActionName = "Login",
UrlReferrer = Request.Headers["Referer"],
Area = "UI",
LangId = 1,
IsFirstLogin = emp != null && emp.LastSignInDateTime == null,
Namespace = nameof(AccountController)
};
_auditRepo.InsertAuditLogs(audit, emp);
// ...
}
}
Direct EF Context Usage (For Testing)
var options = new DbContextOptionsBuilder<IrbyContext>()
.UseInMemoryDatabase("TestDb")
.Options;
using var context = new IrbyContext(options);
var repo = new AuditRepository(context);
// Prepare a dummy audit
var dummyModel = new AuditModel {
UserEmail = "[email protected]",
SessionId = Guid.NewGuid().ToString(),
IpAddress = "127.0.0.1",
PageAccessed = "Test/Page",
LoginStatus = "Success",
ControllerName = "Test",
ActionName = "Page",
UrlReferrer = "",
Area = "",
LangId = 1,
IsFirstLogin = true,
Namespace = "TestNamespace"
};
var dummyEmp = new Employee { UserId = 1, Email = "[email protected]" };
repo.InsertAuditLogs(dummyModel, dummyEmp);
// Verify record exists
var saved = context.AuditDetails.First();
Console.WriteLine($"Saved AuditId: {saved.AuditDetailId}");
9. Conclusion
🎉 AuditRepository is your go‑to component for persisting audit logs in the IrbyImaging application. By leveraging EF Core and a clear AuditModel → AuditDetail mapping strategy, it ensures that every user action can be tracked reliably.
Next Steps:
- Integrate into your controllers/services wherever auditing is required.
- Enhance error handling by logging exceptions or implementing retry logic.
- Consider an async version (
InsertAuditLogsAsync) for non-blocking I/O operations.
Happy auditing and may your logs be ever‑accurate! 🕵️♂️🛡️