šŸ“„ 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

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Controller Structure & Design
  4. 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
  5. View Models & Data Models
  6. Helper Methods & Utilities
  7. Error Handling & Return Types
  8. API Endpoints Overview
  9. Third-Party Integrations
  10. Sample Code Blocks & Usage Examples
  11. UML Class Diagram
  12. 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:

  1. Receive file(s) via IFormFile.
  2. Save to temporary stream / disk.
  3. Split multi‐page PDFs into single‐page streams using iTextSharp or IronPdf.
  4. OCR each page with IronOcr → ImageOCRContents, ImageOCRText.
  5. Persist TempDocumentData & BlobData to database.
  6. 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! šŸš€