📄 ATSHomeController.cs Documentation

Welcome to the comprehensive documentation of ATSHomeController, part of the IrbyImaging.UI project. This controller powers the “All Things Service” (ATS) dashboard, offering asset summaries, search/autocomplete, and Excel/ZIP export capabilities.


📑 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Controller Structure & Key Functional Areas
    3.1. Index Action (Dashboard)
    3.2. Chart Data Endpoints
    3.3. Search & Autocomplete Endpoints
    3.4. Asset Display Actions
    3.5. ZIP Download & Excel Exports
    3.6. Error Handling
  4. View Models & Data Models
  5. Helper Methods & Utilities
  6. API Endpoints Overview
  7. Third‑party Integrations
  8. Sample Code & Usage Examples
  9. UML Class Diagram
  10. Conclusion

1. Overview & Purpose

ATSHomeController serves as the entry point for IrbyImaging’s asset‑management dashboard. It:

  • Displays key metrics (computers, mobile devices, printers, etc.).
  • Exposes AJAX JSON endpoints for charting.
  • Allows search by employee number, phone number, or name autocomplete.
  • Renders asset lists by owner or field office.
  • Provides ZIP/Excel exports for asset review workflows.

This controller inherits from BaseController (common authentication/logging).


2. Dependencies & Technologies

Category Libraries / Frameworks
Web Framework ASP.NET Core MVC
ORM / DB Entity Framework Core, IrbyContext
Authentication Azure.Identity, Microsoft.Graph
Excel Generation Syncfusion.XlsIO, IronXL
Compression / ZIP Syncfusion.Compression.Zip
Data Serialization Newtonsoft.Json
Miscellaneous BouncyCastle, Regex, SMO (SQL Management)

3. Controller Structure & Key Functional Areas

public class ATSHomeController : BaseController
{
    private readonly IrbyContext _context;
    private readonly IWebHostEnvironment _hostingEnvironment;
    private readonly IConfiguration _configuration;

    public ATSHomeController(
        IrbyContext context,
        IWebHostEnvironment environment,
        IConfiguration configuration
    ) : base(context, configuration)
    {
        _context = context;
        _hostingEnvironment = environment;
        _configuration = configuration;
    }
    // ... action methods below ...
}

3.1. Index Action (Dashboard)

Route: GET /ATSHome/Index
Returns: IActionResult (View)

  • Authenticates via Azure AD Graph API to fetch user Department, Role, DisplayName.
  • Aggregates asset counts (computers, mobiles, printers, network equipment, safety equipment).
  • Loads recent asset activities (AssetHistories).
  • Passes metrics via ViewBag to the Razor View.
public async Task<IActionResult> Index()
{
    // 1. Get current user info
    var email = User.Identity.Name; 
    var graphClient = new GraphServiceClient(...);
    var user = await graphClient.Users[email].GetAsync();

    // 2. Set ViewBag for UI
    ViewBag.Department = user.Department ?? "";
    ViewBag.Role       = user.JobTitle   ?? "";
    ViewBag.DisplayName= user.DisplayName?? "";

    // 3. Compute asset tallies
    ViewBag.ActiveComputerCount    =
        _context.Computers.Count(c => c.Status == AssetStatus.Active);
    // ...
    // 4. Query recent activity
    var activity = (from a in _context.AssetHistories
                    join b in _context.Assets on a.AssetId equals b.Id
                    orderby a.Timestamp descending
                    select new { /* ... */ })
                   .Take(8).ToArray();
    // Populate 8 most recent events in ViewBag.Date1, Asset1, Notes1, etc.

    return View();
}

3.2. Chart Data Endpoints

Action HTTP Description Returns
GetChartData POST Overview counts for main categories JsonResult
GetMobileDevicesData POST Breakdown by carrier & Telegis flag JsonResult
GetComputersData POST Computer status pie chart JsonResult
GetNetworkEquipmentData POST Network equipment status pie chart JsonResult
GetOfficePrintersData POST Office printers status pie chart JsonResult

Each method performs LINQ queries on _context to count by status/carrier, then returns JSON with:

{
  "success": true,
  "series": [ /* numeric array */ ],
  "labels": [ /* string array */ ]
}

3.3. Search & Autocomplete Endpoints

  • SearchByEmployeeNumber (GET): Redirects to Employees/Details if JdeNumber found, else shows error on Index.
  • SearchByMobilePhoneNumber (GET): Strips non‑digits, looks up MobileDevices, then redirects or displays error.
  • GetNames (autocomplete) (GET): Accepts term, splits full names, returns JSON array of { label, value }.
// Autocomplete signature
public async Task<IActionResult> GetNames(string term)

3.4. Asset Display Actions

Action Route Description
ShowAssets GET /ShowAssets Asset list grouped by employee
ShowAssetsByField GET /ShowAssetsByField Refactored: group by FieldOffice, populate manager/job
ShowAssetsForITReview GET /ShowAssetsForITReview Assets needing IT review
  • Uses AssetsView and AssetsViewDetail view models.
  • Eager‑loads related Model, Owner, FieldOffice, Job to reduce trips.
  • Ensures no null‑pointer via checks.

3.5. ZIP Download & Excel Exports

  • DownloadZip & DownloadZipForITReview (GET):
    • Collate asset data by field offices.
    • Generate XLSX files per office via IronXL or Syncfusion.XlsIO.
    • Create a ZIP archive in memory using Syncfusion.Compression.
    • Return as File(memStream.ToArray(), "application/zip", "AssetsByFieldOffices.zip").

Snippet:

using (ExcelEngine excelEngine = new ExcelEngine())
{
    // Create Workbook, Worksheet, populate cells 
    var stream = xlsWorkbook.ToStream();
    zipArchive.AddItem(officeName+".xlsx", stream, false, FileAttributes.Normal);
}
MemoryStream memStream = new MemoryStream();
zipArchive.Save(memStream, false);
return File(memStream.ToArray(), "application/zip", "AssetsByFieldOffices.zip");

3.6. Error Handling

  • Error() action decorated with [ResponseCache(...)] to render ErrorViewModel.
  • Search endpoints set ViewBag.EmployeeNumberError / ViewBag.PhoneNumberError and return View("Index") on failure.

4. View Models & Data Models

Model Purpose
AssetsView Container for List<AssetsViewDetail>
AssetsViewDetail Holds per-asset data (serial, model, owner, office, etc.)
ErrorViewModel Standard MVC error model (RequestId)
Employee (DomainClass) Employee entity with properties (FirstName, JdeNumber, etc.)
Asset, Computer, EF Core entities (one-to-one inheritance)
MobileDevice, etc.

5. Helper Methods & Utilities

  • Regex.Replace for phone‑number normalization.
  • LINQ GroupBy + ToDictionary for pre-loading assets by ID (reduces DB round-trips).
  • GraphServiceClient initialization with ClientSecretCredential.
  • CultureInfo for date abbreviations on dashboard events.

6. Error Handling & Return Types

  • IActionResult: Views (Index, ShowAssets*, Error), Redirects, File downloads.
  • JsonResult: AJAX endpoints returning { success, series, labels } or chart data arrays.

7. API Endpoints Overview

Endpoint HTTP Params Returns
/ATSHome/Index GET — HTML View
/ATSHome/GetChartData POST — JSON
/ATSHome/GetMobileDevicesData POST — JSON
/ATSHome/GetComputersData POST — JSON
/ATSHome/SearchByEmployeeNumber GET number (string) Redirect / Index view
/ATSHome/SearchByMobilePhoneNumber GET phoneNumber (string) Redirect / Index view
/ATSHome/GetNames GET term (string) JSON autocomplete
/ATSHome/ShowAssets GET — HTML View
/ATSHome/ShowAssetsByField GET — HTML View
/ATSHome/ShowAssetsForITReview GET — HTML View
/ATSHome/DownloadZip GET — ZIP File
/ATSHome/DownloadZipForITReview GET — ZIP File

8. Third‑party Integrations

  • Microsoft.Graph: Fetches user profile and sign‑in activity.
  • Azure.Identity: Auth with ClientSecretCredential.
  • Syncfusion.XlsIO & IronXL: Excel file creation.
  • Syncfusion.Compression.Zip: In-memory ZIP archiving.
  • Org.BouncyCastle: (Referenced but not actively used in this controller)
  • Microsoft.SqlServer.Management.Smo: (Referenced for DB management utilities)

9. Sample Code & Usage Examples

AJAX Chart Load (jQuery)

$.post('/ATSHome/GetChartData', function(response) {
  if(response.success) {
    var ctx = document.getElementById('myChart').getContext('2d');
    new Chart(ctx, {
      type: 'pie',
      data: {
        labels: response.labels,
        datasets: [{ data: response.series }]
      }
    });
  }
});

Name Autocomplete (jQuery UI)

$("#employeeSearch").autocomplete({
  source: '/ATSHome/GetNames',
  minLength: 2,
  select: function(event, ui) {
    window.location = '/Employees/Details/' + ui.item.value;
  }
});

10. UML Class Diagram

classDiagram
    BaseController <|-- ATSHomeController
    ATSHomeController o-- IrbyContext
    ATSHomeController o-- IWebHostEnvironment
    ATSHomeController o-- IConfiguration
    ATSHomeController ..> GraphServiceClient
    ATSHomeController ..> Syncfusion.Compression.Zip.ZipArchive
    ATSHomeController ..> ExcelEngine
    ATSHomeController ..> AssetsView
    ATSHomeController ..> AssetsViewDetail

11. Conclusion

ATSHomeController centralizes the ATS dashboard, data‑driven charts, search/autocomplete, asset listings, and file exports. While robust, consider future refinements:

  • Use strongly‑typed view models instead of ViewBag.
  • Extract repeated asset‑population logic into services.
  • Modularize Excel/ZIP generation for reuse and testability.

With this documentation, developers and stakeholders can better understand, extend, and maintain the ATS home functionalities. 🚀


End of ATSHomeController.cs Documentation