SafetyImagingController.cs Documentation 📄
Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Controller Structure
3.1 Controller Declaration & Attributes
3.2 Constructor & Initialization - Key Functional Areas
- View Models & Data Models
- Helper Methods & Utilities 🔧
- Error Handling & Return Types
- Third-Party Integrations 🌐
- Sample Usage Examples 💡
- UML Class Diagram 🧩
- 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
BaseControllerwhich 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 vieweroperation: handles Syncfusion file‑manager actions underwwwroot/IrbySafety
4. Key Functional Areas
File Upload & Processing
- GET
/SafetyImaging/Upload— Show upload view - POST
/SafetyImaging/UploadDocs- Receive
IEnumerable<IFormFile> - Save raw file(s) to
wwwroot/irbyuploads - IronPdf splits multi‑page PDFs into one file per page
- Build
TempDocumentDataentries with:ImageContents(byte[])ImageOCRContents&ImageOCRText(viaIronTesseract)- Metadata:
Page,TotalPages,BatchId,ReferenceId,Uploader,ContentType
- Save to DB & redirect to
DocPreview
- Receive
[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 allTempDocumentDatanot yet indexed by current user and batch; returns count & listPreview(Guid id): returns a single file (image or PDF) fromTempDocumentDataRenderImage(Guid id): merges all pages of a saved DocumentImage (finalized) into a single PDFRenderImagePrev(Guid id): preview page from temp dataViewPdf(Guid id): writes and returns a PDF file to browserView(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);
}
}
Document Listing & Search
- GET
/SafetyImaging/List
BuildsDocumentImagingview‑model with:- Available Document Categories & Types (as grouped
<select>) - IndexList of all
DocumentAttributes(filters)
- Available Document Categories & Types (as grouped
- POST
/SafetyImaging/List
Accepts a filledDocumentImagingmodel + form values:- Filters
DocumentImagesby selectedSafetyDocumentType - Matches each
DocumentImagingListwith requestedIndexOptions - Returns results in
ImagingList
- Filters
Document Indexing & Saving
SaveDocument,Search,SaveDoc,Savemethods handle:- Collecting selected
TempDocumentDataIDs - Optionally Delete temp entries if user cancels
- Merge PDFs to final path (
SaveDocumentAndReturnPath) - Build final
DocumentImagewith:- OCR text & PDF (byte[])
- JSON‑serialized
DocumentIndexes - Metadata:
FileName,Uploader,Type,BatchId,ReferenceId
- Save to
_context.DocumentImages
- Collecting selected
Modal Dialogs & Partial Views
myModalDet,myModalPreview,myModalDeletePreview
Return partial views (_myModalDet,_myModalPreview,deleteModal) for quick client‑side dialogs.
File Manager
FileManagerview shows recent uploads.FileOperations: implements Syncfusion FileManager actions (read,delete,copy,move,details,create,search,rename).UploadFiles,Download,GetImage: handle physical file operations underwwwroot/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‑autocompleteSearchByEmployeeNumber&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 viaAzureADReadto get full display name. -
OCRResult(...)
Uses IronTesseract to OCR a file or PDF, populatingImageOCRText,ImageOCRContents,TotalPages. -
Combine(byte[] first, byte[] second)
Byte‑array concatenation. -
JsonConverterstring(jsonObjects results)
Reflects overjsonObjectsto produceDictionary<string,string>for PDF Viewer API. -
GetDocumentPath(string document)
Resolves a physical path underwwwroot/IrbySafetyor absolute path. -
GetFormatType(string format)
Maps file extension toSyncfusion.EJ2.DocumentEditor.FormatType.
7. Error Handling & Return Types
- 📦
IActionResultorActionResultfor MVC views - 📂
FileContentResult/FileStreamResultfor binary streams - 🚫 Simple checks +
return nullor redirections for invalid states (could be improved with explicit404or400). - 📶 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! 🚀