๐Ÿ“‘ OfficePrintersController Documentation


Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Controller Structure
  4. Key Functional Areas
  5. View Models & Data Models
  6. Manager & Mapper Utilization
  7. Error Handling & Return Types
  8. API Endpoints Overview
  9. Security & Authorization
  10. UML Class Diagram
  11. Sample Code Blocks
  12. Usage Examples
  13. Conclusion

Overview & Purpose

The OfficePrintersController โš™๏ธ is an ASP.NET Core MVC controller in the IrbyImaging application. It handles all serverโ€‘side logic for managing office printer assets:

  • List printers
  • View details of a printer
  • Create, Edit, and Track history
  • Integrate with the business layer (IAssetManager) and mapping layer (IOfficePrinterMapper)

This controller inherits from a shared BaseController that provides common functionality (e.g., database context, configuration).


Dependencies & Technologies

Category Items
Framework ASP.NET Core MVC
Data Access Entity Framework Core (IrbyContext)
Business Logic Layer IAssetManager
Mapping Layer IOfficePrinterMapper
Models OfficePrinter, AssetStatus (enum)
View Models OfficePrinterListViewModel, OfficePrinterDetailViewModel, etc.
Utilities Logging, Responses enum
Configuration IConfiguration
Security Microsoft.AspNetCore.Authorization

Controller Structure

namespace IrbyImaging.Controllers
{
  public class OfficePrintersController : BaseController
  {
    private readonly IAssetManager _manager;
    private readonly IOfficePrinterMapper _mapper;
    private readonly IrbyContext _context;
    private readonly IConfiguration _configuration;

    public OfficePrintersController(
        IAssetManager manager,
        IOfficePrinterMapper mapper,
        IrbyContext context,
        IConfiguration configuration)
      : base(context, configuration)
    { ... }

    // GET: Index, Details, Create, Edit, History...
  }
}

3.1 Constructor

  • Parameters

    • IAssetManager manager โ€“ Business logic interface for asset operations
    • IOfficePrinterMapper mapper โ€“ Transforms domain models โ†” view models
    • IrbyContext context โ€“ EF Core database context
    • IConfiguration configuration โ€“ App settings
  • Responsibilities

    • Initialize dependencies
    • Call base constructor (BaseController)

3.2 Index (List View)

public async Task<IActionResult> Index(string search, AssetStatus status)
{
  var officePrinters = await _manager.GetOfficePrinters_Async(search);
  var viewModel = _mapper.GenerateOfficePrinterListViewModel(officePrinters, status);
  return View(viewModel);
}
  • Route: GET /OfficePrinters
  • Function:
    • Fetches filtered list of printers
    • Maps domain list โ†’ OfficePrinterListViewModel
    • Returns Razor view

3.3 Details (Detail View)

public async Task<IActionResult> Details(Guid? id)
{
  if (id == null) return NotFound();
  var officePrinter = await _manager.GetOfficePrinterById_Async(id);
  if (officePrinter == null) return NotFound();

  var viewModel = _mapper.GenerateOfficePrinterDetailViewModel(officePrinter);
  return View(viewModel);
}
  • Route: GET /OfficePrinters/Details/{id}
  • Function:
    • Validates id
    • Retrieves single printer
    • Maps to detail view model
    • Returns detail page

3.4 Create (GET & POST)

GET: Display Form

public IActionResult Create()
{
  var viewModel = _mapper.GenerateOfficePrinterCreateViewModel();
  return View(viewModel);
}
  • Route: GET /OfficePrinters/Create
  • Function: Returns an empty create form.

POST: Process Submission

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(OfficePrinterCreateViewModel viewModel)
{
  if (!ModelState.IsValid)
    return View(viewModel);

  var officePrinter = _mapper.CreateViewModelToOfficePrinter(viewModel);
  (var response, var message) = 
      await _manager.AddNewAssetWithHistory_Async(officePrinter, User.Identity.Name);

  if (response == Responses.Failure)
  {
    var newVM = _mapper.GenerateOfficePrinterCreateViewModel();
    newVM.ErrorMessage = message;
    return View(newVM);
  }

  return RedirectToAction(nameof(Index));
}
  • Validations:
    • ModelState
    • Business response
  • Error Handling:
    • Redisplay form with error message

3.5 Edit (GET & POST)

GET: Load for Edit

public async Task<IActionResult> Edit(Guid? id)
{
  if (id == null) return NotFound();

  var officePrinter = await _manager.GetOfficePrinterById_Async(id);
  if (officePrinter == null) return NotFound();

  var viewModel = _mapper.OfficePrinterToEditViewModel(officePrinter);
  return View(viewModel);
}

POST: Submit Changes

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Guid id, OfficePrinterEditViewModel viewModel)
{
  if (id != viewModel.Id) return NotFound();
  if (!ModelState.IsValid) return View(viewModel);

  var domain = _mapper.EditViewModelToOfficePrinter(viewModel);
  (var response, var message) =
    await _manager.UpdateAssetAndHistory_Async(domain, User.Identity.Name, viewModel.Reason);

  if (response == Responses.Failure)
  {
    var newVM = _mapper.OfficePrinterToEditViewModel(domain);
    newVM.ErrorMessage = message;
    return View(newVM);
  }

  return RedirectToAction(nameof(Index));
}

3.6 History (Audit Trail)

public async Task<IActionResult> History(Guid? id)
{
  if (id == null) return NotFound();

  var histories = await _manager.GetHistoryByAssetId_Async(id);
  if (histories == null) return NotFound();

  var viewModel = _mapper.GenerateOfficePrinterHistoryListViewModel(histories);
  var officePrinter = await _manager.GetOfficePrinterById_Async(id);
  if (officePrinter == null) return NotFound();

  viewModel.OfficePrintersList = 
      _mapper.GenerateOfficePrinterDetailViewModel(officePrinter);

  return View(viewModel);
}
  • Shows the change history + current details side by side

Key Functional Areas

  • CRUD Operations
    • Create โ†” POST
    • Read โ†” Index & Details
    • Update โ†” Edit
  • History Tracking via AddNewAssetWithHistory_Async / UpdateAssetAndHistory_Async
  • Search & Filtering by search string and AssetStatus
  • Model Validation & Error Handling
  • Mapping between domain & view models
  • Authorization stubs (commented) for policies

View Models & Data Models

Category Types
View Models OfficePrinterListViewModel, OfficePrinterDetailViewModel,OfficePrinterCreateViewModel, OfficePrinterEditViewModel, OfficePrinterHistoryListViewModel
Domain Model OfficePrinter (in IrbyImaging.DomainClasses)
Supporting AssetStatus (enum), Response (enum in Utility)

Manager & Mapper Utilization

  • IAssetManager (Business Logic)

    • GetOfficePrinters_Async(string search)
    • GetOfficePrinterById_Async(Guid? id)
    • AddNewAssetWithHistory_Async(OfficePrinter, string user)
    • UpdateAssetAndHistory_Async(OfficePrinter, string user, string reason)
    • GetHistoryByAssetId_Async(Guid? id)
  • IOfficePrinterMapper (Mapping Layer)

    • Domain โ†’ ViewModel
      • GenerateOfficePrinterListViewModel(...)
      • GenerateOfficePrinterDetailViewModel(...)
      • GenerateOfficePrinterHistoryListViewModel(...)
      • OfficePrinterToEditViewModel(...)
    • ViewModel โ†’ Domain
      • CreateViewModelToOfficePrinter(...)
      • EditViewModelToOfficePrinter(...)
      • GenerateOfficePrinterCreateViewModel()

Error Handling & Return Types

  • 404 Not Found: when id is null or entity not found
  • ModelState Invalid: redisplay view with validation messages
  • Business Failure (Responses.Failure):
    • Capture error message
    • Redisplay form with viewModel.ErrorMessage

API Endpoints Overview

HTTP Verb Route Action Description
GET /OfficePrinters Index List & filter printers
GET /OfficePrinters/Details/{id} Details View detailed info
GET /OfficePrinters/Create Create (GET) Display create form
POST /OfficePrinters/Create Create (POST) Submit new printer
GET /OfficePrinters/Edit/{id} Edit (GET) Display edit form
POST /OfficePrinters/Edit/{id} Edit (POST) Save printer updates
GET /OfficePrinters/History/{id} History Show change history & current details

Security & Authorization

Stubs are present but commented out.

  • Class-level: [Authorize(Policy = "ReadOnlyOrAdminPolicy")]
  • Action-level: [Authorize(Policy = "AdminPolicy")] on Create & Edit

๐Ÿ”’ When enabled, only users in the specified policies can mutate data.


UML Class Diagram

classDiagram
    OfficePrintersController --|> BaseController
    OfficePrintersController o-- IAssetManager : _manager
    OfficePrintersController o-- IOfficePrinterMapper : _mapper
    OfficePrintersController o-- IrbyContext : _context
    OfficePrintersController o-- IConfiguration : _configuration

    IAssetManager <|.. AssetManager
    IOfficePrinterMapper <|.. OfficePrinterMapper
    OfficePrinter -- "many" AssetHistory : tracks
    OfficePrinter <|-- OfficePrinterCreateViewModel
    OfficePrinter <|-- OfficePrinterEditViewModel

Sample Code Blocks

Consuming the Manager Directly

// Fetch all printers containing "HP"
var printers = await _manager.GetOfficePrinters_Async("HP");
foreach (var p in printers)
{
  Console.WriteLine($"{p.Name} ({p.SerialNumber})");
}

Mapping a Create ViewModel

var createVM = _mapper.GenerateOfficePrinterCreateViewModel();
createVM.Name = "Canon iR-ADV C5535";
createVM.SerialNumber = "SN12345";
...

Usage Examples

1. List All Printers

GET /OfficePrinters?search=&status=All HTTP/1.1
Host: localhost:5001

Returns an HTML page listing all printers.

2. Create a New Printer (cURL)

curl -X POST https://localhost:5001/OfficePrinters/Create \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "Name=NewPrinter&SerialNumber=ABC123&Location=HQ"

3. View History

GET /OfficePrinters/History/3fa85f64-5717-4562-b3fc-2c963f66afa6

Conclusion

The OfficePrintersController orchestrates all user interactions around printer asset management in the IrbyImaging UI:

  • โœ… Clean separation of concerns via IAssetManager and IOfficePrinterMapper.
  • โœ… CRUD + Audit Trail outโ€‘ofโ€‘theโ€‘box.
  • โœ… Extensible authorization stubs to lock down actions.
  • โœ… Robust error handling with ModelState, HTTP statuses, and businessโ€‘level feedback.

Use this controller as a template for other asset types (e.g., scanners, copiers) by swapping in the appropriate domain classes, mappers, and view models. ๐Ÿš€