📄 UploadService Documentation


Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. UML Class Diagram
  4. Key Functional Areas
  5. Data Models & Mappings
  6. Error Handling & Return Types
  7. Third‑party Integrations
  8. Sample Usage & Code Examples
  9. Conclusion

Overview & Purpose

UploadService is a bulk‐import service in the IrbyImaging.UI assembly. It processes uploaded CSV files of various AssetCategory types (computers, phones, printers, etc.), maps each row to a corresponding domain object, and delegates persistence to the IAssetManager.

🎯 Primary Goals

  • Validate incoming file type/extension
  • Parse CSV per asset category
  • Enrich records by fetching related IDs (model, owner, field office)
  • Upload domain objects in bulk via IAssetManager.Upload(...)

Dependencies & Technologies

Technology / Library Purpose
.NET Core / ASP.NET Core Framework
CsvHelper CSV parsing
Microsoft.AspNetCore.Http IFormFile abstraction for file uploads
IrbyImaging.BusinessLogic IAssetManager, IEmployeeAndFieldOfficeManager
IrbyImaging.DomainClasses Domain entities (Computer, Monitor, etc.)
IrbyImaging.Models & Utility Shared enums & helpers (e.g., Responses, AssetStatus)

UML Class Diagram

classDiagram
    IUploadService <|.. UploadService
    UploadService : +Import(IFormFile formFile, AssetCategory category, string username) Task<(Responses,string)>
    UploadService : -GetComputers(...)
    UploadService : -GetSafetyEquipments(...)
    UploadService : -GetDeskPhones(...)
    UploadService : -GetDocks(...)
    UploadService : -GetMobileDevices(...)
    UploadService : -GetMonitors(...)
    UploadService : -GetNetworkEquipments(...)
    UploadService : -GetOfficePrinters(...)
    UploadService : -GetPrinters(...)
    UploadService ..> IAssetManager : uses
    UploadService ..> IEmployeeAndFieldOfficeManager : uses

Key Functional Areas

1. Import Method

public async Task<(Responses, string)> Import(
    IFormFile formFile,
    AssetCategory category,
    string username
)

🔍 Responsibilities

  • Validation: Ensures .csv extension and ContentType of application/vnd.ms-excel or text/csv.
  • Routing: Based on AssetCategory, calls the corresponding private parsing method.
  • Delegation: Invokes _assetManager.Upload(parsedEntities, username).
  • Fallback: Returns (Responses.Error, "Asset Category not found.") if category is unsupported.
Step Description
1. Validate File Checks extension & content type → returns error tuple if invalid.
2. Switch‑Case Matches category (e.g., AssetCategory.Computer) → calls GetComputers(...).
3. Upload Awaits _assetManager.Upload(...) → returns (Responses, message) from manager.
4. Default If no case matches, returns error.

2. CSV Parsing Methods

Each private method:

  • Opens a StreamReader on formFile.OpenReadStream().
  • Creates a CsvReader with CultureInfo.CurrentCulture.
  • Calls .Read() and .ReadHeader() once.
  • Iterates through each record .Read() → maps fields → adds to list.
  • Async calls to managers to fetch foreign keys (modelId, ownerId, etc.).

2.1 GetComputers

  • Domain: Computer
  • Key CSV Headers:
    • "Model Name" → ModelId
    • "Owner's JDE Number" → OwnerId
    • "Operating System" → OperatingSystemId
    • "Purchase Date", "Status", "Serial Number", "Asset Number", "Unit Number", "CPS Number", "Notes"
  • Returns: IEnumerable<Computer>

2.2 GetSafetyEquipments

  • Domain: SafetyEquipment
  • Difference: "Tested Date" column instead of "Purchase Date".

2.3 GetDeskPhones

  • Domain: DeskPhone
  • Extra Fields: "MAC Address", "Phone Number".

2.4 GetDocks

  • Domain: Dock

2.5 GetMobileDevices

  • Domain: MobileDevice
  • Specifics:
    • Fields: "Service Provider" → Carrier, "Device Type" → Type, "IMEI", "SIM", "Phone Number", "Telogis?".
    • Validation: Throws Exception("IMEI cannot be NULL") if IMEI is empty.

2.6 GetMonitors

  • Domain: Monitor

2.7 GetNetworkEquipments

  • Domain: NetworkEquipment
  • Owner: Uses GetFieldOfficeIdByJdeNumber_Async(...).

2.8 GetOfficePrinters

  • Domain: OfficePrinter
  • Extra Fields: "Contracted Company", "Contract End Date".

2.9 GetPrinters

  • Domain: Printer

Data Models & Mappings

Domain Class Key Properties
Computer Id, PurchaseDate, Status, ModelId, OwnerId, SerialNumber, AssetNumber, UnitNumber, CpsNumber, Notes, OperatingSystemId
SafetyEquipment Id, PurchaseDate(TestedDate), Status, ModelId, OwnerId, SerialNumber, CpsNumber, Notes, OperatingSystemId
DeskPhone Id, PurchaseDate, Status, ModelId, OwnerId, SerialNumber, MacAddress, PhoneNumber, Notes
Dock Id, PurchaseDate, Status, ModelId, OwnerId, SerialNumber, Notes
MobileDevice Id, PurchaseDate, Status, ModelId, OwnerId, SerialNumber, Carrier, Type, Imei, Sim, PhoneNumber, IsTelogis, Notes
Monitor Id, PurchaseDate, Status, ModelId, OwnerId, SerialNumber, Notes
NetworkEquipment Id, PurchaseDate, Status, ModelId, FieldOfficeId, SerialNumber, Notes
OfficePrinter Id, PurchaseDate, Status, ModelId, FieldOfficeId, SerialNumber, Company, ContractEndDate, Notes
Printer Id, PurchaseDate, Status, ModelId, OwnerId, SerialNumber, Notes

Error Handling & Return Types

  • File Validation
    • Returns (Responses.Error, "Uploaded file must be a CSV.") if extension or MIME type mismatch.
  • Category Fallback
    • Returns (Responses.Error, "Asset Category not found.").
  • Field Validations
    • Mobile devices throw Exception("IMEI cannot be NULL").
  • Upload Response
    • Delegates return value from _assetManager.Upload(...) (typically a tuple of Responses enum + message string).

Third‑party Integrations

  • CsvHelper
    • Fast, culture-aware CSV parsing.
    • Supports header lookup by column name.

Sample Usage & Code Examples

1. Dependency Injection Setup

services.AddScoped<IAssetManager, AssetManager>();
services.AddScoped<IEmployeeAndFieldOfficeManager, EmployeeAndFieldOfficeManager>();
services.AddScoped<IUploadService, UploadService>();

2. Controller Endpoint

[ApiController]
[Route("api/[controller]")]
public class AssetsController : ControllerBase
{
    private readonly IUploadService _uploadService;
    public AssetsController(IUploadService uploadService)
        => _uploadService = uploadService;

    [HttpPost("bulk-import")]
    public async Task<IActionResult> BulkImport(
        IFormFile file,
        AssetCategory category,
        [FromQuery] string username
    ) {
        var (status, message) = await _uploadService.Import(file, category, username);
        return status == Responses.Success
            ? Ok(new { message })
            : BadRequest(new { message });
    }
}

3. Sample CSV (Computers)

Model Name,Owner's JDE Number,Operating System,Purchase Date,Status,Serial Number,Asset Number,Unit Number,CPS Number,Notes
Dell XPS 13,12345,Windows 10 Pro,2022-01-15,Active,SN12345,A1001,U01,CPS001,New laptop
HP EliteBook,67890,Windows 11 Pro,2022-02-01,Active,SN67890,A1002,U02,CPS002,

Conclusion

The UploadService is a robust, category‑driven CSV importer for asset management. By cleanly separating parsing logic per domain model, leveraging CsvHelper, and asynchronously resolving foreign keys, it streamlines bulk data uploads and integrates seamlessly with the IAssetManager business logic layer.

🎉 Key Takeaways

  • Single entry point with strong validation
  • Extensible switch-case for new AssetCategory
  • Consistent CSV parsing pattern
  • Clear separation of concerns (parsing vs. persistence)

Feel free to extend or customize the parsing methods or add new asset categories as your domain grows!