š ImagingController Documentation
Welcome to the ImagingController documentationāa comprehensive guide to the IrbyImaging/Controllers/ImagingController.cs file. This ASP.NET Core MVC controller orchestrates file uploads, OCR, Azure Blob storage integration, preview/rendering, indexing, editing, deletion, listing, and CSV/XLSX generation.
š Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Controller Structure & Design
- Key Functional Areas
4.1. File Upload & OCR
4.2. Azure Blob Storage Integration
4.3. Preview & Rendering
4.4. Document Management (Save/Edit/Delete)
4.5. Listing & Searching
4.6. Migration & Template Generation
- View Models & Data Models
- Helper Methods & Utilities
- Error Handling & Return Types
- API Endpoints Overview
- Third-Party Integrations
- Sample Code Blocks & Usage Examples
- UML Class Diagram
- Conclusion
1. Overview & Purpose
ImagingController is the central controller for handling document imaging workflows in the IrbyImaging UI. It manages:
- š¤ File uploads (single, bulk, IPM migration)
- šØļø OCR processing via IronOCR/Syncfusion
- āļø Azure Blob Storage integration
- š Previewing and rendering of PDF/image content
- šļø Indexing, editing, deletion, and search/list operations
- š CSV/XLSX generation for Lytx templates
- š Migration of legacy documents
2. Dependencies & Technologies
| Namespace / Package |
Role |
| Microsoft.AspNetCore.Mvc |
MVC Controller, ActionResult, Model Binding |
| Microsoft.AspNetCore.Hosting |
Access to IWebHostEnvironment (web root) |
| Microsoft.AspNetCore.Http |
IFormFile, IHttpContextAccessor |
| IrbyImaging.DomainClasses |
Domain models: DocumentImage, TempDocumentData, etc |
| IrbyImaging.Models |
ViewModels (e.g., DocumentImaging, ShortDocumentImageList) |
| IrbyImaging.Services |
Custom services (e.g., IUploadService) |
| IronOcr |
OCR engine |
| IronXL |
XLSX/CSV generation |
| iTextSharp.text, .pdf |
PDF merging/copying |
| Azure.Storage.Blobs |
BlobServiceClient, BlobContainerClient |
| Syncfusion.EJ2.PdfViewer |
PdfRenderer for text extraction |
| CsvHelper |
CSV parsing/upload (vehicles, Lytx templates) |
| Microsoft.EntityFrameworkCore |
IrbyContext DB access |
| Microsoft.Extensions.Configuration |
App configuration |
3. Controller Structure & Design
public class ImagingController : BaseController
{
// Injected services & context
private readonly IrbyContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IUploadService _uploadService;
private readonly IWebHostEnvironment _hostingEnvironment;
private readonly BlobServiceClient _blobServiceClient;
private readonly IConfiguration _configuration;
public ImagingController(
IrbyContext context,
IHttpContextAccessor http,
IWebHostEnvironment environment,
IUploadService uploadService,
BlobServiceClient blobServiceClient,
IConfiguration configuration
) : base(context, configuration) { /* ... */ }
// Action methods below...
}
- Inherits BaseController (provides common properties & methods).
- Uses Dependency Injection to retrieve DB context, hosting environment, blob client, and configuration.
4. Key Functional Areas
4.1 File Upload & OCR š¤š§
| Action |
HTTP Verb |
Purpose |
Index() |
GET |
Return empty upload form. |
Upload() |
GET |
Singleāfile upload view. |
BulkUpload() |
GET |
Bulk upload view (size limit 900MB). |
UploadNewAsync(IEnumerable<IFormFile>) |
POST |
New async PDF splitter & blob uploads (perāpage). Returns preview. |
Upload(IEnumerable<IFormFile>) |
POST |
Standard upload + OCR using IronOCR & IronPDF. Returns JSON success. |
UploadDocs(IEnumerable<IFormFile>) |
POST |
Similar to Upload, then redirects to preview. |
Workflow:
- Receive file(s) via
IFormFile.
- Save to temporary stream / disk.
- Split multiāpage PDFs into singleāpage streams using iTextSharp or IronPdf.
- OCR each page with IronOcr ā
ImageOCRContents, ImageOCRText.
- Persist
TempDocumentData & BlobData to database.
- Redirect to preview or return success JSON.
[HttpPost]
[RequestSizeLimit(900_000_000)]
public async Task<IActionResult> Upload(IEnumerable<IFormFile> file)
{
_context.SetTimeOut(5600);
var ocr = new IronTesseract();
var batchId = Guid.NewGuid();
// ... process each page, OCR, save TempDocumentData
return Json(new { Message = "Documents Uploaded Successfully" });
}
4.2 Azure Blob Storage Integration āļø
| Method |
Purpose |
UploadFileAsync |
Upload a single file stream to Blob storage |
DownloadFileAsync |
Download blob content as Stream |
DeleteFileAsync |
Delete blob if exists |
GetBlobNamesAsync |
List all blob names in a container |
ViewBlob(Guid id) |
Retrieve PDF blob by DocumentImageId |
DownloadBlob(string) |
Force download blob content as PDF |
private async Task<string> UploadFileAsync(IFormFile file)
{
var containerClient = _blobServiceClient.GetBlobContainerClient("irbyimaging");
var blobClient = containerClient.GetBlobClient("Equipment/Temp/" + Guid.NewGuid() + Path.GetExtension(file.FileName));
using var stream = file.OpenReadStream();
await blobClient.UploadAsync(stream, new BlobHttpHeaders { ContentType = file.ContentType });
return blobClient.Uri.ToString();
}
4.3 Preview & Rendering š
| Action |
Purpose |
DocPreview(string, string) |
Select uploaded temp docs for preview |
Preview(Guid id) |
Merge & return singleāpage PDF preview |
DeletePreview(Guid id) |
Preview before deletion |
RenderImage(Guid id) |
Stream stored blob/image content |
RenderImagePrev(Guid id) |
Render OCRāembedded PDF from temp data |
RenderDeleteImagePrev(Guid id) |
Render before deletion (PDF). |
public async Task<ActionResult> RenderImage(Guid id)
{
var pdf = _context.DocumentImages.First(d => d.DocumentImageId == id);
var blobClient = _blobServiceClient.GetBlobContainerClient("irbyimaging")
.GetBlobClient(pdf.BlobName);
using var ms = new MemoryStream();
await blobClient.DownloadToAsync(ms);
return File(ms.ToArray(), pdf.ContentType);
}
4.4 Document Management (Save/Edit/Delete) šļø
- SaveDocument: Stages selected temp pages, tags for indexing.
- Save: Finalizes indexing ā merges pages into final PDF, uploads to blob, populates
DocumentImage (master record).
- Edit (GET/POST): Modify metadata (JobNumber, DocumentType, etc.) and reāupload merged PDF.
- DeleteUploadedDocument, Delete, DeleteDocument: Remove temp or master pages, update
IsDeleted flags and rebuild parent PDF if needed.
4.5 Listing & Searching š
| Action |
Purpose |
List() (GET) |
Show recent 300 documents (non-legal). |
List(...) (POST) |
Filter by type, category, dates, text. |
FileManager() |
Quick file manager: top 7 documents. |
GetNames(string term) |
Autocomplete for document templates. |
[HttpPost]
public ActionResult List(string DocumentType, string JobNumber, /*...*/)
{
IQueryable<DocumentImage> query = _context.DocumentImages.Where(d => !d.IsDeleted);
if (!string.IsNullOrEmpty(DocumentType))
query = query.Where(d => d.DocumentType.Contains(DocumentType));
// ... other filters ...
var results = query.Select(d => new ShortDocumentImageList { /*...*/ }).ToList();
return View(new DocumentImaging { ImgResults = results });
}
4.6 Migration & Template Generation šš
- IPM Migration (
IpmMigration GET/POST): Bulk-import legacy files from file system, OCR, persist to IPMMigration table.
- Migration(DocumentImaging image): Post-migration cleanup of legal docs (merges, tags, OCR, blobāuploads).
- UploadVehicles, LytxTemplateUpload: CSV import for
Vehicle and LytxTemplate.
- Generate(Guid batchId): Produce a CSV export for Lytx data (driver shifts) using IronXL or manual
StringBuilder.
public Tuple<string, string, byte[]> Generate(Guid batchId)
{
var records = _context.LytxTemplate.Where(l => l.BatchId == batchId).ToList();
// Build CSV rows:
var sb = new StringBuilder();
foreach (var r in records) { sb.AppendLine($"\"{r.DriverId}\",\"{r.LastName}\",..."); }
return Tuple.Create($"LytxTemplate_{DateTime.Today:yyyyMMdd}.csv",
"text/csv",
Encoding.UTF8.GetBytes(sb.ToString()));
}
5. View Models & Data Models
ā ļø Classes below are referenced but defined elsewhere in the solution.
- DocumentImaging (ViewModel)
List<Guid> BatchIds ā selected temp IDs
List<ShortDocumentImageList> ImgResults ā search/list results
- Metadata:
DocumentType, JobNumber, JobName, AssignedToEmployeeId, etc.
- ShortDocumentImageList
- Lightweight projection of
DocumentImage for listing.
- DocumentImage (Domain)
Guid DocumentImageId, byte[] ImageContents, byte[] ImageOCRContents, string ImageOCRText, string BlobName, metadata fields, flags.
- TempDocumentData
- Staging table for split pages.
Guid TempDocumentDataId, byte[] ImageContents, int Page, bool IsDeleted, etc.
- BlobData
- Stores binary
byte[] ImageContents for each TempDocumentDataId.
- IPMMigration, LytxTemplate, Vehicle (Domain): various migration and template entities.
6. Helper Methods & Utilities š§
| Method |
Purpose |
GetBlobNamesAsync() |
Enumerate blob names |
UploadFileAsync(IFormFile) |
Upload to blob |
UploadEachFileAsync |
Variant of above |
DownloadFileAsync(string) |
Download blob stream |
DeleteFileAsync(string) |
Safe delete blob |
AddByteToArray(byte[], byte) |
Prepend a byte to array |
OCRResult(...) |
Wrapper for IronOcr to produce searchable PDF + text |
ModifyAttachedDocs(DocumentImaging) |
Rebuild merged PDF & reupload blob after edits |
7. Error Handling & Return Types šØ
- Size Limits: Many
[RequestSizeLimit(900_000_000)] to allow large uploads.
- Cancellation/Timeout:
_context.SetTimeOut(5600) for longārunning DB ops.
- Return Types:
ActionResult / ViewResult for views
IActionResult / JsonResult for JSON/redirects
FileContentResult for PDF/image streaming
- Validation: Minimal inācontroller; assumes valid
IFormFile inputs, non-null query parameters.
8. API Endpoints Overview š
| Route |
HTTP |
Parameters |
Description |
/Imaging/Index |
GET |
ā |
Display upload index |
/Imaging/Upload |
GET |
ā |
Single upload form |
/Imaging/Upload |
POST |
IFormFile file |
Handle single file upload + OCR |
/Imaging/BulkUpload |
GET |
ā |
Bulk upload form |
/Imaging/BulkUpload |
POST |
List<IFormFile> files |
Bulk upload + OCR |
/Imaging/UploadNewAsync |
POST |
IEnumerable<IFormFile> file |
Async split & blob upload per page |
/Imaging/DocPreview |
GET |
string fileName, string batchId |
Preview staged pages |
/Imaging/SaveDocument |
POST |
DocumentImaging img |
Stage pages for final indexing |
/Imaging/Save |
POST |
DocumentImaging image, string batchId |
Finalize, merge & upload PDF blob |
/Imaging/Edit/{id} |
GET |
Guid id |
Edit metadata form |
/Imaging/Edit |
POST |
DocumentImaging image, string batchId, IEnumerable<IFormFile> file |
Save edits, rebuild blob |
/Imaging/DeleteUploadedDocument/{id} |
GET |
Guid id |
Confirm temp doc deletion |
/Imaging/Delete |
POST |
string[] docIds |
Delete selected temp pages |
/Imaging/List |
GET |
ā |
List recent documents |
/Imaging/List |
POST |
form filters |
Filtered search |
/Imaging/ViewBlob/{id} |
GET |
Guid id |
Stream PDF from Azure blob |
/Imaging/DownloadBlob/{Name} |
GET |
string Name |
Download PDF blob |
/Imaging/UploadVehicles |
GET |
ā |
CSV upload form |
/Imaging/UploadVehicles |
POST |
IFormFile file |
Import Vehicle entities |
/Imaging/LytxTemplateUpload |
GET |
ā |
Lytx CSV import form |
/Imaging/LytxTemplateUpload |
POST |
IFormFile file |
Import & generate Lytx CSV download |
9. Third-Party Integrations š¤
- IronOCR: Optical Character Recognition
- IronPdf: Page splitting & PDF manipulation
- iTextSharp: Low-level PDF merging (
PdfCopy, PdfSmartCopy)
- Syncfusion EJ2 PdfViewer: Text extraction & bounding boxes
- Azure.Storage.Blobs: Cloud blob container operations
- CsvHelper: High-performance CSV parsing
10. Sample Code Blocks & Usage Examples š§āš»
ClientāSide: AJAX File Upload
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" multiple />
<button type="submit">Upload</button>
</form>
<script>
$("#uploadForm").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: '/Imaging/Upload',
method: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(resp) { alert(resp.Message); }
});
});
</script>
Displaying Preview in Razor View
@model IrbyImaging.Models.DocumentImaging
<div>
@foreach(var id in Model.BatchIds) {
<iframe src="@Url.Action("RenderImagePrev", "Imaging", new { id = id })" width="100%" height="600px"></iframe>
}
</div>
11. UML Class Diagram
classDiagram
class ImagingController {
- IrbyContext _context
- IHttpContextAccessor _httpContextAccessor
- IWebHostEnvironment _hostingEnvironment
- IUploadService _uploadService
- BlobServiceClient _blobServiceClient
- IConfiguration _configuration
+ Index()
+ Upload()
+ Upload(IEnumerable<IFormFile>)
+ BulkUpload()
+ UploadNewAsync(IEnumerable<IFormFile>)
+ ViewBlob(Guid)
+ DownloadBlob(string)
+ DocPreview(string,string)
+ SaveDocument(DocumentImaging)
+ Save(DocumentImaging, string)
+ Edit(Guid)
+ Edit(DocumentImaging, string, IEnumerable<IFormFile>)
+ List()
+ List(filters)
+ ... (many more actions)
}
12. Conclusion š
ImagingController is the heart of the IrbyImaging UI, coordinating:
- Complex file workflows (split, OCR, merge)
- Cloud storage (Azure Blobs)
- Dynamic previews and edits
- Batch migrations and template exports
This documentation has walked through major areas, provided code snippets, endpoint overviews, and dependencies. For further customization, follow MVC best practicesāextract repeated logic into services, add robust error handling, and secure largeāfile endpoints. Happy coding! š