SafetyImagingController.cs Documentation 📄


Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Controller Structure
    3.1 Controller Declaration & Attributes
    3.2 Constructor & Initialization
  4. Key Functional Areas
  5. View Models & Data Models
  6. Helper Methods & Utilities 🔧
  7. Error Handling & Return Types
  8. Third-Party Integrations 🌐
  9. Sample Usage Examples 💡
  10. UML Class Diagram 🧩
  11. Conclusion

1. Overview & Purpose

SafetyImagingController is an ASP.NET Core MVC controller responsible for managing the Safety‑oriented document imaging workflow in the IrbyImaging application. This includes:

  • 📁 Uploading PDFs/images
  • 📝 OCR (Optical Character Recognition) processing
  • 🔍 Indexing and search by safety‑specific metadata
  • 📑 Previewing, merging, deleting documents
  • 👷‍♂️ Managing Document Types, Categories, and Attributes for safety compliance
  • ⚙️ Exposing a lightweight PDF‑Viewer API (via Syncfusion)
  • 📋 Integrating Word & Excel editors (Syncfusion EJ2)

It builds on EF Core (IrbyContext), Azure AD for user identity, and several third‑party libraries (iTextSharp, IronOCR, IronPdf, Syncfusion).


2. Dependencies & Technologies

Dependency Purpose
Microsoft.AspNetCore.Mvc MVC Controller base & routing
Microsoft.EntityFrameworkCore Database context (IrbyContext)
Microsoft.AspNetCore.Http File upload (IFormFile) & context accessor
Microsoft.AspNetCore.Hosting IWebHostEnvironment for file paths
Microsoft.Extensions.Caching.Memory Caching PDF viewer renders
iTextSharp.text.pdf PDF reading & merging
IronOcr OCR processing
IronPdf Splitting and saving PDFs
Syncfusion.EJ2.FileManager Physical file provider for file manager
Syncfusion.XlsIO Excel import/export
Syncfusion.DocIO Word document processing
Syncfusion.EJ2.DocumentEditor Web‑based Word editor
Newtonsoft.Json JSON serialization / deserialization
AzureADRead (custom) Azure AD user lookup

3. Controller Structure

3.1 Controller Declaration & Attributes

[DisableRequestSizeLimit]
public class SafetyImagingController : BaseController
  • [DisableRequestSizeLimit]
    Allows very large uploads (e.g. multi‑MB PDFs).
  • Inherits from BaseController which provides shared context and configuration.

3.2 Constructor & Initialization

public SafetyImagingController(
    IrbyContext context,
    IHttpContextAccessor http,
    IWebHostEnvironment environment,
    IMemoryCache cache,
    IConfiguration configuration)
    : base(context, configuration)
{
    _context = context;
    _httpContextAccessor = http;
    _hostingEnvironment = environment;
    _cache = cache;
    _configuration = configuration;

    basePath = environment.ContentRootPath;
    root = "wwwroot\\IrbySafety";
    operation = new PhysicalFileProvider();
    operation.RootFolder(basePath + "\\" + root);
}
  • _context: EF Core DB context
  • _httpContextAccessor: access to HTTP metadata (user)
  • _hostingEnvironment: get paths (WebRootPath)
  • _cache: memory caching for PDF viewer
  • operation: handles Syncfusion file‑manager actions under wwwroot/IrbySafety

4. Key Functional Areas

File Upload & Processing

  • GET /SafetyImaging/Upload — Show upload view
  • POST /SafetyImaging/UploadDocs
    1. Receive IEnumerable<IFormFile>
    2. Save raw file(s) to wwwroot/irbyuploads
    3. IronPdf splits multi‑page PDFs into one file per page
    4. Build TempDocumentData entries with:
      • ImageContents (byte[])
      • ImageOCRContents & ImageOCRText (via IronTesseract)
      • Metadata: Page, TotalPages, BatchId, ReferenceId, Uploader, ContentType
    5. Save to DB & redirect to DocPreview
[HttpPost]
[RequestSizeLimit(900_000_000)]
public async Task<IActionResult> UploadDocs(IEnumerable<IFormFile> file)
{
    // 1) Save input file to "irbyuploads"
    // 2) Use IronPdf to split pages
    // 3) Build TempDocumentData list
    // 4) Save via _context.TempDocumentData.AddRange(...)
    // 5) RedirectToAction("DocPreview", new { batchId })
}

Document Preview & Rendering

  • DocPreview: selects all TempDocumentData not yet indexed by current user and batch; returns count & list
  • Preview(Guid id): returns a single file (image or PDF) from TempDocumentData
  • RenderImage(Guid id): merges all pages of a saved DocumentImage (finalized) into a single PDF
  • RenderImagePrev(Guid id): preview page from temp data
  • ViewPdf(Guid id): writes and returns a PDF file to browser
  • View(Guid id) & ViewOCR(Guid id): raw byte streams for inline display
public async Task<ActionResult> RenderImage(Guid id, string Preview)
{
    var pdfPages = _context.DocumentImages
                    .Where(d => d.OriginalReferenceId == id && !d.IsDeleted)
                    .OrderBy(d => d.DocumentUploadedDate)
                    .ToList();
    using (MemoryStream ms = new())
    using (Document doc = new Document())
    using (PdfSmartCopy copy = new PdfSmartCopy(doc, ms))
    {
        doc.Open();
        foreach (var p in pdfPages)
        {
            using (PdfReader reader = new(p.ImageOCRContents))
            {
                copy.AddDocument(reader);
            }
        }
        doc.Close();
        return File(ms.ToArray(), pdfPages.First().ContentType);
    }
}
  • GET /SafetyImaging/List
    Builds DocumentImaging view‑model with:
    • Available Document Categories & Types (as grouped <select>)
    • IndexList of all DocumentAttributes (filters)
  • POST /SafetyImaging/List
    Accepts a filled DocumentImaging model + form values:
    1. Filters DocumentImages by selected SafetyDocumentType
    2. Matches each DocumentImagingList with requested IndexOptions
    3. Returns results in ImagingList

Document Indexing & Saving

  • SaveDocument, Search, SaveDoc, Save methods handle:
    1. Collecting selected TempDocumentData IDs
    2. Optionally Delete temp entries if user cancels
    3. Merge PDFs to final path (SaveDocumentAndReturnPath)
    4. Build final DocumentImage with:
      • OCR text & PDF (byte[])
      • JSON‑serialized DocumentIndexes
      • Metadata: FileName, Uploader, Type, BatchId, ReferenceId
    5. Save to _context.DocumentImages
  • myModalDet, myModalPreview, myModalDeletePreview
    Return partial views (_myModalDet, _myModalPreview, deleteModal) for quick client‑side dialogs.

File Manager

  • FileManager view shows recent uploads.
  • FileOperations: implements Syncfusion FileManager actions (read, delete, copy, move, details, create, search, rename).
  • UploadFiles, Download, GetImage: handle physical file operations under wwwroot/IrbySafety.

Document Types / Categories / Attributes Management

Feature Endpoints
Document Types DocumentTypes, CreateType, EditType/{id}, DeleteType/{id}
Document Categories DocumentCategories, CreateCategory, EditCategory/{id}, DeleteCategory/{id}
Attributes DocumentAttributes, CreateAttribute, EditAttribute/{id}, DeleteAttribute/{id}

Supports CRUD + modals (myModal, myModalCategory, myModalAttribute).

PDF Viewer API 🎥

Exposes a lightweight JSON‑based API for Syncfusion PDF Viewer:

  • Load, RenderPdfPages, RenderAnnotationComments, Unload, RenderThumbnailImages, Bookmarks, Download, PrintImages, ExportAnnotations, ImportAnnotations

All under route api/SafetyImaging/{action} and returning JSON or Base64 document streams.

Word & Excel Integration 📊

  • Word: GetDocuments(CustomParams), GetFormatType(string)
  • Excel: GetExcel(CustomParams), OpenExcel(IFormCollection), SaveExcel(SaveSettings)

Uses Syncfusion.DocIO and Syncfusion.XlsIO to load/display and save Office files in‑browser.

Search & Autocomplete 🔍

  • GetNames(string term): returns JSON for employee name‑autocomplete
  • SearchByEmployeeNumber & SearchByJobNumber: redirect to Employee details page

5. View Models & Data Models

Class Description
DocumentImaging ViewModel for document upload, listing, indexing
DocumentImagingList Holds each search result with indexes & metadata
DocumentAttributeViewDetail Holds attribute metadata and selected value
DocumentTypeView / Detail ViewModel for managing document types
DocumentCategoryView / Detail ViewModel for managing categories
DocumentAttributeView ViewModel for managing document attributes
TempDocumentData / DocumentImage (Domain) EF entities for temp & finalized docs
IndexOptions { Id, AttributeName, IndexValue, IsMultiValue, AttributeType }
DocumentCollections Helper for list‑of‑select items: { Type, Category, Id, IsSelected }
jsonObjects DTO for PDF API: { document, password, isFileName, pageNumber, … }
CustomParams DTO for GetDocuments & GetExcel: { FileName, Action }

6. Helper Methods & Utilities 🔧

  • GetUserName(string user)
    Queries Azure AD via AzureADRead to get full display name.

  • OCRResult(...)
    Uses IronTesseract to OCR a file or PDF, populating ImageOCRText, ImageOCRContents, TotalPages.

  • Combine(byte[] first, byte[] second)
    Byte‑array concatenation.

  • JsonConverterstring(jsonObjects results)
    Reflects over jsonObjects to produce Dictionary<string,string> for PDF Viewer API.

  • GetDocumentPath(string document)
    Resolves a physical path under wwwroot/IrbySafety or absolute path.

  • GetFormatType(string format)
    Maps file extension to Syncfusion.EJ2.DocumentEditor.FormatType.


7. Error Handling & Return Types

  • 📦 IActionResult or ActionResult for MVC views
  • 📂 FileContentResult / FileStreamResult for binary streams
  • 🚫 Simple checks + return null or redirections for invalid states (could be improved with explicit 404 or 400).
  • 📶 PDF‑API methods return Content(JsonConvert.SerializeObject(...)) to satisfy Syncfusion viewer.

8. Third-Party Integrations 🌐

  • iTextSharp — low‑level PDF manipulation (merging, extracting text)
  • IronOcr — OCR processing of images & PDFs
  • IronPdf — splitting pages & producing searchable PDFs
  • Syncfusion FileManager — in‑app file browser & operations
  • Syncfusion EJ2 DocumentEditor — Word‑processing in browser
  • Syncfusion XlsIO — Excel read/write
  • AzureADRead — custom library for Azure AD user details

9. Sample Usage Examples 💡

Upload + Preview

// 1) Navigate to /SafetyImaging/Upload (GET) to show file picker
// 2) POST files to /SafetyImaging/UploadDocs
//    var formData = new FormData();
//    formData.append("file", fileInput.files[0]);
//    fetch("/SafetyImaging/UploadDocs", { method:"POST", body: formData })
//      .then(() => window.location.href = "/SafetyImaging/DocPreview");

PDF Viewer API (client‑side JavaScript)

// Pseudocode using Syncfusion PDF Viewer

let viewer = new PdfViewer();
fetch("/api/SafetyImaging/Load", {
  method: "POST",
  body: JSON.stringify({
    document: "safety_inspection.pdf",
    isFileName: true
  })
})
.then(res => res.json())
.then(data => viewer.load(data));

Create a Safety Document Type

// GET /SafetyImaging/CreateType -> form with Name, Category dropdown
// POST /SafetyImaging/CreateDocType
public IActionResult CreateDocType(DocumentTypeView model, List<string> indexType) {
    // Saves new DocumentType and associates selected DocumentAttribute IDs
}

10. UML Class Diagram 🧩

classDiagram
    SafetyImagingController --> IrbyContext
    SafetyImagingController --> IHttpContextAccessor
    SafetyImagingController --> IWebHostEnvironment
    SafetyImagingController --> IMemoryCache
    SafetyImagingController --> IConfiguration

    SafetyImagingController ..> DocumentImaging : uses
    SafetyImagingController ..> TempDocumentData : uses
    SafetyImagingController ..> DocumentImage : uses

    class DocumentImaging {
      +List<SelectListItem> DocumentTypes
      +List<DocumentAttributeViewDetail> IndexList
      +List<DocumentImagingList> ImagingList
      +List<Guid> BatchIds
      +string DocumentType
      +Guid ReferenceId
      +bool DeleteFiles
    }

    class DocumentAttributeViewDetail {
      +Guid Id
      +string AttributeName
      +string IndexValue
      +bool IsMultiValue
      +string[] MultiValues
    }

    class TempDocumentData {
      +Guid TempDocumentDataId
      +Guid BatchId
      +Guid ReferenceId
      +byte[] ImageContents
      +DateTime DocumentUploadedDate
      +bool IsIndexed
    }

    class DocumentImage {
      +Guid DocumentImageId
      +Guid OriginalReferenceId
      +byte[] ImageOCRContents
      +string ImageOCRText
      +string DocumentIndexes
      +bool IsDeleted
    }

11. Conclusion

The SafetyImagingController is a comprehensive hub for uploading, OCR‑processing, indexing, and managing safety‑critical documents in the IrbyImaging solution. By leveraging iTextSharp, IronOCR, IronPdf, and Syncfusion libraries, it provides:

  • Robust file upload and splitting
  • Searchable PDF creation
  • Full metadata indexing and search
  • Browser‑based PDF/Word/Excel viewing & editing
  • A self‑contained file manager

🛠️ Next Steps:

  • Add finer‑grained error handling & user feedback
  • Secure API endpoints with authorization
  • Optimize large file streaming (range requests)
  • Enhance UI for attribute indexing and document previews

Thank you for exploring the SafetyImagingController! 🚀