π UploadsController.cs Documentation
π Table of Contents
- Overview & Purpose
- Key Functional Areas
- Dependencies & Technologies
- View Models & Data Models
- Controller Actions
- Helper Methods & Utilities
- Error Handling & Return Types
- Thirdβparty Integrations
- Sample Code Snippets
- Usage Examples
- UML Class Diagram
- Conclusion
π 1. Overview & Purpose
The UploadsController in IrbyImaging.UI is responsible for handling CSV file uploads, delegating import logic to the business layer, and presenting the import results.
- Namespace:
IrbyImaging.Controllers - Assembly:
IrbyImaging.UI - Author: kvamshi
- Created: 03-31-2022
- Last Modified: 05-17-2022
Primary Responsibilities
- Serve the upload page (
Indexview) - Validate and process incoming CSV files
- Display success/failure counts and details
π§© 2. Key Functional Areas
| Area | Responsibility |
|---|---|
| π File Upload Handling | Accepts CSV files via UploadViewModel. |
| π Business Logic Invoke | Calls IUploadService.Import(...) for import operation. |
| π Result Presentation | Parses service response and renders Results view. |
| π Security (optional) | Can be secured via [Authorize(Policy = "AdminPolicy")]. |
ποΈ 3. Dependencies & Technologies
- ASP.NET Core MVC
- Dependency Injection via constructor
- IrbyImaging.BusinessLogic β Business rules and import logic
- IrbyImaging.Services β Service interfaces/implementations
- IrbyImaging.Utility β Shared utilities and enums (e.g.,
Responses) - IrbyImaging.DomainClasses β Entity Framework DbContext (
IrbyContext) - Microsoft.Extensions.Configuration β App settings
π¦ 4. View Models & Data Models
4.1 UploadViewModel
public class UploadViewModel
{
[Required]
public IFormFile UploadedCsv { get; set; }
[Required]
public string Category { get; set; }
}
| Property | Type | Description |
|---|---|---|
UploadedCsv |
IFormFile |
CSV file to import |
Category |
string |
Category/tag for the import batch |
4.2 UploadResultsViewModel
public class UploadResultsViewModel
{
public string SuccessfulCount { get; set; }
public string FailedCount { get; set; }
public List<string> Problems { get; set; } = new List<string>();
}
| Property | Type | Description |
|---|---|---|
SuccessfulCount |
string |
Number of records imported |
FailedCount |
string |
Number of records failed |
Problems |
List<string> |
Detailed error messages per record |
π 5. Controller Actions
The UploadsController inherits from BaseController, which encapsulates common context and configuration logic.
public class UploadsController : BaseController
{
private readonly IUploadService _uploadService;
private readonly IrbyContext _context;
private readonly IConfiguration _configuration;
public UploadsController(
IUploadService uploadService,
IrbyContext context,
IConfiguration configuration
) : base(context, configuration)
{
_uploadService = uploadService;
_context = context;
_configuration = configuration;
}
// GET: /Uploads
public IActionResult Index() => View();
// POST: /Uploads
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(UploadViewModel upload)
{
if (!ModelState.IsValid)
return View();
(var response, var message) =
await _uploadService.Import(upload.UploadedCsv, upload.Category, User.Identity.Name);
if (response == Responses.Error)
{
ViewData["ErrorMessage"] = message;
return View(upload);
}
var results = message.Split('|').ToList();
var vm = new UploadResultsViewModel
{
SuccessfulCount = results[0],
FailedCount = results[1],
Problems = results.Skip(2).ToList()
};
return View("Results", vm);
}
}
5.1 Index (GET)
- Route:
GET /Uploads/Index - Purpose: Display the upload form
- Return:
View()(rendersViews/Uploads/Index.cshtml)
5.2 Index (POST)
- Route:
POST /Uploads/Index - Attributes:
[HttpPost][ValidateAntiForgeryToken]
- Parameters:
UploadViewModel upload
- Workflow:
- Model Validation: If invalid, re-display form.
- Import Execution:
var (response, message) = await _uploadService.Import(...); - Error Handling:
- If
response == Responses.Error, setViewData["ErrorMessage"]and re-display form.
- If
- Success Path:
- Parse
messageby|separator. - Build
UploadResultsViewModel. - Render
Views/Uploads/Results.cshtml.
- Parse
π οΈ 6. Helper Methods & Utilities
Though UploadsController does not define private helpers, it leverages:
BaseController(common logic forUser,Context,Configuration)IUploadService.Import(IFormFile, string, string)Responsesenum (likely:Success,Error, etc.)
π 7. Error Handling & Return Types
| Scenario | Response | View |
|---|---|---|
| ModelState invalid | IActionResult |
Index (form) |
| Service returns Error | (Responses.Error, message) |
Index + ViewData["Error"] |
| Service returns Success | (Responses.Success, formattedText) |
Results |
ViewData["ErrorMessage"]is used to pass error details to the view.
π 8. Thirdβparty Integrations
- None directly within this controller.
- Underlying
IUploadServicemay integrate with:- CSV parsers (e.g., CsvHelper)
- Database (via
IrbyContext) - Logging frameworks
π» 9. Sample Code Snippets
9.1 Dependency Injection Setup
// In Startup.cs or Program.cs
services.AddScoped<IUploadService, UploadService>();
services.AddDbContext<IrbyContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("Default")));
9.2 Razor View: Index.cshtml
@model UploadViewModel
<h2>Upload CSV</h2>
<form asp-action="Index" enctype="multipart/form-data" method="post">
<div asp-validation-summary="ModelOnly"></div>
<input type="file" asp-for="UploadedCsv" />
<input type="text" asp-for="Category" placeholder="Category" />
<button type="submit">π€ Upload</button>
</form>
9.3 Razor View: Results.cshtml
@model UploadResultsViewModel
<h2>Upload Results</h2>
<p>β
Success: @Model.SuccessfulCount</p>
<p>β Failed: @Model.FailedCount</p>
<ul>
@foreach (var problem in Model.Problems)
{
<li>@problem</li>
}
</ul>
π 10. Usage Examples
- Navigate to
/Uploadsin your browser. - Select a CSV file and enter a Category.
- Submit form β Controller invokes
IUploadService.Import. - View results or errors on the subsequent page.
cURL Example (for advanced clients):
curl -X POST https://yourapp.com/Uploads/Index \
-F "UploadedCsv=@/path/to/data.csv" \
-F "Category=Invoices" \
-H "X-CSRF-TOKEN: {token}"
π 11. UML Class Diagram
classDiagram
BaseController <|-- UploadsController
UploadsController : - IUploadService _uploadService
UploadsController : - IrbyContext _context
UploadsController : - IConfiguration _configuration
UploadsController : + IActionResult Index()
UploadsController : + Task<IActionResult> Index(UploadViewModel)
IUploadService <.. UploadService
class UploadViewModel {
+ IFormFile UploadedCsv
+ string Category
}
class UploadResultsViewModel {
+ string SuccessfulCount
+ string FailedCount
+ List<string> Problems
}
π 12. Conclusion
The UploadsController provides a clean, twoβstep workflow for CSV import:
- Display upload UI
- Process file & render results
It delegates import logic to IUploadService, enabling robust separation of concerns and ease of testing. By following this pattern, you can extend or secure the upload process (e.g., adding [Authorize]), swap out CSV parsers, or plug in additional validation layers without changing the controller code. π