πŸ“„ UploadsController.cs Documentation


πŸ“‘ Table of Contents

  1. Overview & Purpose
  2. Key Functional Areas
  3. Dependencies & Technologies
  4. View Models & Data Models
  5. Controller Actions
  6. Helper Methods & Utilities
  7. Error Handling & Return Types
  8. Third‑party Integrations
  9. Sample Code Snippets
  10. Usage Examples
  11. UML Class Diagram
  12. Conclusion

πŸ“– 1. Overview & Purpose

The UploadsController in IrbyImaging.UI is responsible for handling CSV file uploads, delegating import logic to the business layer, and presenting the import results.

  • Namespace: IrbyImaging.Controllers
  • Assembly: IrbyImaging.UI
  • Author: kvamshi
  • Created: 03-31-2022
  • Last Modified: 05-17-2022

Primary Responsibilities

  • Serve the upload page (Index view)
  • Validate and process incoming CSV files
  • Display success/failure counts and details

🧩 2. Key Functional Areas

Area Responsibility
πŸ“ File Upload Handling Accepts CSV files via UploadViewModel.
🏭 Business Logic Invoke Calls IUploadService.Import(...) for import operation.
πŸ“Š Result Presentation Parses service response and renders Results view.
πŸ”’ Security (optional) Can be secured via [Authorize(Policy = "AdminPolicy")].

πŸ—οΈ 3. Dependencies & Technologies

  • ASP.NET Core MVC
  • Dependency Injection via constructor
  • IrbyImaging.BusinessLogic – Business rules and import logic
  • IrbyImaging.Services – Service interfaces/implementations
  • IrbyImaging.Utility – Shared utilities and enums (e.g., Responses)
  • IrbyImaging.DomainClasses – Entity Framework DbContext (IrbyContext)
  • Microsoft.Extensions.Configuration – App settings

πŸ“¦ 4. View Models & Data Models

4.1 UploadViewModel

public class UploadViewModel
{
    [Required]
    public IFormFile UploadedCsv { get; set; }

    [Required]
    public string Category { get; set; }
}
Property Type Description
UploadedCsv IFormFile CSV file to import
Category string Category/tag for the import batch

4.2 UploadResultsViewModel

public class UploadResultsViewModel
{
    public string SuccessfulCount { get; set; }
    public string FailedCount { get; set; }
    public List<string> Problems { get; set; } = new List<string>();
}
Property Type Description
SuccessfulCount string Number of records imported
FailedCount string Number of records failed
Problems List<string> Detailed error messages per record

πŸš€ 5. Controller Actions

The UploadsController inherits from BaseController, which encapsulates common context and configuration logic.

public class UploadsController : BaseController
{
    private readonly IUploadService _uploadService;
    private readonly IrbyContext _context;
    private readonly IConfiguration _configuration;

    public UploadsController(
        IUploadService uploadService,
        IrbyContext context,
        IConfiguration configuration
    ) : base(context, configuration)
    {
        _uploadService = uploadService;
        _context = context;
        _configuration = configuration;
    }

    // GET: /Uploads
    public IActionResult Index() => View();

    // POST: /Uploads
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Index(UploadViewModel upload)
    {
        if (!ModelState.IsValid)
            return View();

        (var response, var message) =
            await _uploadService.Import(upload.UploadedCsv, upload.Category, User.Identity.Name);

        if (response == Responses.Error)
        {
            ViewData["ErrorMessage"] = message;
            return View(upload);
        }

        var results = message.Split('|').ToList();
        var vm = new UploadResultsViewModel
        {
            SuccessfulCount = results[0],
            FailedCount     = results[1],
            Problems        = results.Skip(2).ToList()
        };

        return View("Results", vm);
    }
}

5.1 Index (GET)

  • Route: GET /Uploads/Index
  • Purpose: Display the upload form
  • Return: View() (renders Views/Uploads/Index.cshtml)

5.2 Index (POST)

  • Route: POST /Uploads/Index
  • Attributes:
    • [HttpPost]
    • [ValidateAntiForgeryToken]
  • Parameters:
    • UploadViewModel upload
  • Workflow:
    1. Model Validation: If invalid, re-display form.
    2. Import Execution:
      var (response, message) = await _uploadService.Import(...);
      
    3. Error Handling:
      • If response == Responses.Error, set ViewData["ErrorMessage"] and re-display form.
    4. Success Path:
      • Parse message by | separator.
      • Build UploadResultsViewModel.
      • Render Views/Uploads/Results.cshtml.

πŸ› οΈ 6. Helper Methods & Utilities

Though UploadsController does not define private helpers, it leverages:

  • BaseController (common logic for User, Context, Configuration)
  • IUploadService.Import(IFormFile, string, string)
  • Responses enum (likely: Success, Error, etc.)

🐞 7. Error Handling & Return Types

Scenario Response View
ModelState invalid IActionResult Index (form)
Service returns Error (Responses.Error, message) Index + ViewData["Error"]
Service returns Success (Responses.Success, formattedText) Results
  • ViewData["ErrorMessage"] is used to pass error details to the view.

πŸ”Œ 8. Third‑party Integrations

  • None directly within this controller.
  • Underlying IUploadService may integrate with:
    • CSV parsers (e.g., CsvHelper)
    • Database (via IrbyContext)
    • Logging frameworks

πŸ’» 9. Sample Code Snippets

9.1 Dependency Injection Setup

// In Startup.cs or Program.cs
services.AddScoped<IUploadService, UploadService>();
services.AddDbContext<IrbyContext>(options => 
    options.UseSqlServer(configuration.GetConnectionString("Default")));

9.2 Razor View: Index.cshtml

@model UploadViewModel
<h2>Upload CSV</h2>
<form asp-action="Index" enctype="multipart/form-data" method="post">
  <div asp-validation-summary="ModelOnly"></div>
  <input type="file" asp-for="UploadedCsv" />
  <input type="text" asp-for="Category" placeholder="Category" />
  <button type="submit">πŸ“€ Upload</button>
</form>

9.3 Razor View: Results.cshtml

@model UploadResultsViewModel
<h2>Upload Results</h2>
<p>βœ… Success: @Model.SuccessfulCount</p>
<p>❌ Failed: @Model.FailedCount</p>
<ul>
  @foreach (var problem in Model.Problems)
  {
    <li>@problem</li>
  }
</ul>

πŸ“ 10. Usage Examples

  1. Navigate to /Uploads in your browser.
  2. Select a CSV file and enter a Category.
  3. Submit form β†’ Controller invokes IUploadService.Import.
  4. View results or errors on the subsequent page.

cURL Example (for advanced clients):

curl -X POST https://yourapp.com/Uploads/Index \
  -F "UploadedCsv=@/path/to/data.csv" \
  -F "Category=Invoices" \
  -H "X-CSRF-TOKEN: {token}"

πŸ“Š 11. UML Class Diagram

classDiagram
    BaseController <|-- UploadsController
    UploadsController : - IUploadService _uploadService
    UploadsController : - IrbyContext _context
    UploadsController : - IConfiguration _configuration
    UploadsController : + IActionResult Index()
    UploadsController : + Task<IActionResult> Index(UploadViewModel)
    IUploadService <.. UploadService

    class UploadViewModel {
      + IFormFile UploadedCsv
      + string Category
    }

    class UploadResultsViewModel {
      + string SuccessfulCount
      + string FailedCount
      + List<string> Problems
    }

πŸ”š 12. Conclusion

The UploadsController provides a clean, two‑step workflow for CSV import:

  1. Display upload UI
  2. Process file & render results

It delegates import logic to IUploadService, enabling robust separation of concerns and ease of testing. By following this pattern, you can extend or secure the upload process (e.g., adding [Authorize]), swap out CSV parsers, or plug in additional validation layers without changing the controller code. πŸš€