đ 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
- Overview & Purpose
- Dependencies & Technologies
- 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 - View Models & Data Models
- Helper Methods & Utilities
- API Endpoints Overview
- Thirdâparty Integrations
- Sample Code & Usage Examples
- UML Class Diagram
- 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
ViewBagto 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 toEmployees/DetailsifJdeNumberfound, else shows error on Index. - SearchByMobilePhoneNumber (
GET): Strips nonâdigits, looks upMobileDevices, then redirects or displays error. - GetNames (autocomplete) (
GET): Acceptsterm, 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,Jobto 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 renderErrorViewModel. - Search endpoints set
ViewBag.EmployeeNumberError/ViewBag.PhoneNumberErrorand returnView("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