📦 AssetManager Service Documentation

IrbyImaging/UI · Services · AssetManager.cs
Author: kvamshi · Created: 05‑17‑2022 · Modified: 06‑24‑2022


📑 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Key Functional Areas
    • Create / Upload
    • Update
    • Read (Asset Queries)
    • History Management
    • Helpers & Utilities
  4. Detailed API Methods
    • AddNewAssetWithHistory_Async
    • Upload
    • UpdateAssetAndHistory_Async
    • Get{Asset}Async / Get{Asset}ByIdAsync
    • GetHistoryByAssetId_Async
    • GenerateAssetHistory (private)
    • GetModelIdByName_Async & GetOperatingSystemIdByName_Async
    • Dropdown Helpers
  5. Error Handling & Return Types
  6. UML Class Diagram
  7. Sample Usage & Code Snippets
  8. Conclusion

🔍 1. Overview & Purpose

AssetManager is the core service responsible for all CRUD operations on various Asset types (Computers, Monitors, Mobile Devices, etc.) and for maintaining an immutable AssetHistory log. It abstracts database interactions through Entity Framework Core and enforces business rules such as:

  • Ownership validation: Every asset must belong to an Employee or Field Office.
  • Status constraints: Assets cannot have a status of All.
  • Audit trail: All creations & updates generate history entries capturing serialized snapshots.

This service powers both bulk uploads and granular queries from the UI layer.


⚙️ 2. Dependencies & Technologies

Technology/Package Purpose
Microsoft.EntityFrameworkCore ORM for database access (IrbyContext)
Newtonsoft.Json Serializes assets into JSON for history logging
IrbyImaging.DomainClasses Defines domain models: Asset, AssetHistory, Computer, etc.
IrbyImaging.Utility Contains Responses enum and other shared utilities

🗝 3. Key Functional Areas

3.1 Create / Upload

  • AddNewAssetWithHistory_Async<T>
    Creates an asset of type T : Asset, validates business rules, logs an initial history entry, and saves to DB.

  • Upload<T>
    Bulk-imports a collection of assets, invoking AddNewAssetWithHistory_Async per row, collecting successes/failures.

3.2 Update

  • UpdateAssetAndHistory_Async<T>
    Updates an existing asset, logs a history entry capturing the edit action and reason.

3.3 Read (Asset Queries)

  • Get{AssetType}_Async / Get{AssetType}ById_Async
    Provides paged or filtered lists of assets for each category (Computer, Monitor, MobileDevice, DeskPhone, etc.), including related Model, Make, Owner, FieldOffice, and OS where applicable.

3.4 History Management

  • GetHistoryByAssetId_Async
    Returns the full audit trail for a given asset ID, ordered by timestamp.

  • GenerateAssetHistory (private)
    Internal helper that builds AssetHistory entries with serialized properties, status, action, and timestamp.

3.5 Helpers & Utilities

  • GetModelIdByName_Async, GetOperatingSystemIdByName_Async
  • GetModelsFor(AssetCategory), GetModelsFor(DeviceType)
  • GetOwners, GetFieldOffices, GetOperatingSystems
    Provide dropdown-friendly lists (dataValue/dataText) for UI consumption.

🔎 4. Detailed API Methods

4.1 AddNewAssetWithHistory_Async<T>

public async Task<(Responses, string)> 
  AddNewAssetWithHistory_Async<T>(T asset, string username)
  where T : Asset
  • Purpose: Creates asset, ensures OwnerId or FieldOfficeId is set, status ≠ All, logs initial history.

  • Returns:

    • (Responses.Success, "Created successfully")
    • (Responses.Failure, "Error message")
  • Business Rules:

    • Throws if no owner or field office.
    • Throws if Status == All.
  • History: Calls GenerateAssetHistory<T>(asset, "Create", username, "Initial creation").


4.2 Upload<T>

public async Task<(Responses, string)> 
  Upload<T>(IEnumerable<T> assets, string username) 
  where T : Asset
  • Purpose: Bulk-add rows of assets.
  • Logic: Loops each asset, tracks successfulAdditions, failedAdditions, aggregates problems in a string.
  • Return Format:
    • "5|2|Row 2: OwnerId and FieldOfficeId cannot both be null..."
    • (Responses.Failure, details) if any failure.
    • (Responses.Success, "X|0") if all succeeded.

4.3 UpdateAssetAndHistory_Async<T>

public async Task<(Responses, string)> 
  UpdateAssetAndHistory_Async<T>(T asset, string username, string reason)
  where T : Asset
  • Purpose: Updates existing asset + logs change.
  • Constraints: Same status validation as create.
  • History: Calls GenerateAssetHistory<T>(asset, "Edit", username, reason).

4.4 Get{AssetType}_Async / Get{AssetType}ById_Async

For each category, e.g.:

public async Task<IEnumerable<Computer>> GetComputers_Async(string searchTerm) { … }
public async Task<Computer> GetComputerById_Async(Guid? id) { … }
  • Includes related navigation props: .Include(c => c.Model).ThenInclude(m => m.Make), .Include(c => c.Owner), .Include(c => c.OperatingSystem).
  • Filtering: Applies Where(...) on multiple fields if searchTerm != null.
  • Sorting: By Owner.LastName, FirstName, MiddleName, then asset number.
  • Special Cases:
    • DeskPhone, Dock, MobileDevice, Monitor, NetworkEquipment, OfficePrinter, Printer all merge results from the main table plus historical matches (search in AssetHistory.Reason).

4.5 GetHistoryByAssetId_Async

public async Task<IEnumerable<AssetHistory>> 
  GetHistoryByAssetId_Async(Guid? assetId)
  • Purpose: Fetch audit records.
  • Ordering: Chronological (Timestamp ascending).

4.6 GenerateAssetHistory (private)

private AssetHistory GenerateAssetHistory<T>(
  object someAsset, string action, string username, string reason)
  where T : Asset
  • Serializes someAsset into JSON (Newtonsoft.Json).
  • Populates AssetHistory:
    • AssetId, Status, Action, ModifiedBy, Reason, Timestamp, SerializedProperties.
    • Resolves OwnerId & Owner name from either Employees or FieldOffices.

4.7 Model & OS Lookup Helpers

public async Task<int> GetModelIdByName_Async(string modelName);
public async Task<int> GetOperatingSystemIdByName_Async(string operatingSystemName);
  • Purpose: Map display names to their numeric IDs.

4.8 Dropdown Data Helpers

public IEnumerable<object> GetModelsFor(AssetCategory category);
public IEnumerable<object> GetModelsFor(DeviceType deviceType);
public IEnumerable<object> GetOwners();
public IEnumerable<object> GetFieldOffices();
public IEnumerable<object> GetOperatingSystems();
  • Returns: Sequences of { dataValue = <id>, dataText = "<Name>" } for populating <select> lists.

⚠️ 5. Error Handling & Return Types

  • Return Type: Task<(Responses, string)>
    • Responses: Enum { Success, Failure }
    • string: Success message or inner exception message on failure.
  • Try/Catch:
    • On Add: Rolls back local context additions via _context.Remove(...).
    • On Update: Returns immediate failure without rollback (context automatically tracks old state).

📈 6. UML Class Diagram

classDiagram
    AssetManager ..|> IAssetManager
    AssetManager o-- IrbyContext : _context
    AssetManager ..> Asset
    AssetManager ..> AssetHistory

    class AssetManager {
      +AddNewAssetWithHistory_Async<T>(T asset, string username)
      +Upload<T>(IEnumerable<T> assets, string username)
      +UpdateAssetAndHistory_Async<T>(T asset, string username, string reason)
      +GetComputers_Async(searchTerm)
      +GetComputerById_Async(id)
      +… // and other Get methods
      +GetHistoryByAssetId_Async(assetId)
      +GenerateAssetHistory<T>(object someAsset, string action, string username, string reason)
      +GetModelIdByName_Async(modelName)
      +GetOperatingSystemIdByName_Async(operatingSystemName)
      +GetModelsFor(category/deviceType)
      +GetOwners()
      +GetFieldOffices()
      +GetOperatingSystems()
    }

    class Asset {
      <<abstract>>
      +Guid Id
      +int AssetNumber
      +AssetStatus Status
      +Guid? OwnerId
      +Guid? FieldOfficeId
      +string Notes
      …
    }

    class AssetHistory {
      +Guid AssetId
      +string Status
      +string Action
      +string ModifiedBy
      +string Reason
      +DateTimeOffset Timestamp
      +string SerializedProperties
      +Guid OwnerId
      +string Owner
    }

    IrbyContext o-- DbSet~Asset~
    IrbyContext o-- DbSet~AssetHistory~
    IrbyContext o-- DbSet~Computer~
    IrbyContext o-- DbSet~Employee~
    IrbyContext o-- DbSet~FieldOffice~
    IrbyContext o-- DbSet~AssetModel~
    IrbyContext o-- DbSet~OperatingSystem~

💻 7. Sample Usage & Code Snippets

7.1 Registering & Injecting in Startup

// In Startup.cs / Program.cs (ASP.NET Core)
services.AddDbContext<IrbyContext>(options => 
    options.UseSqlServer(Configuration["ConnectionStrings:Default"]));
services.AddScoped<IAssetManager, AssetManager>();

7.2 Creating a Computer Asset

var newComputer = new Computer {
  Id = Guid.NewGuid(),
  ModelId = await assetManager.GetModelIdByName_Async("Latitude 7410"),
  OperatingSystemId = await assetManager.GetOperatingSystemIdByName_Async("Windows 10 Pro"),
  OwnerId = employeeId,
  SerialNumber = "SN123456",
  AssetNumber = 1001,
  Status = AssetStatus.Active,
  Notes = "Deployed to field"
};

var (response, message) = 
  await assetManager.AddNewAssetWithHistory_Async(newComputer, "j.doe");
if (response == Responses.Success)
  Console.WriteLine("Computer created!");
else
  Console.Error.WriteLine($"Error: {message}");

7.3 Bulk Upload

var importedAssets = csvParser.Parse<Computer>("computers.csv");
var (bulkResp, details) = await assetManager.Upload(importedAssets, "importUser");
Console.WriteLine(details);

7.4 Fetching & Displaying History

var history = await assetManager.GetHistoryByAssetId_Async(computerId);
foreach (var entry in history) {
  Console.WriteLine($"{entry.Timestamp:u} - {entry.Action} by {entry.ModifiedBy}: {entry.Reason}");
}

🏁 8. Conclusion

The AssetManager service centralizes all asset lifecycle operations—create, update, search, and audit—for a heterogeneous fleet of equipment. Its design:

  • Enforces critical business constraints.
  • Tracks every change via AssetHistory.
  • Optimizes UI integration through tailored dropdown and search methods.

By leveraging EF Core and JSON serialization, it offers a robust, transactional foundation for the IrbyImaging asset management subsystem.

⭐ Happy Coding!