CarrierTypeController Documentation 🚚📦

File: IrbyImaging/UI/Controllers/CarrierTypeController.cs
Assembly: IrbyImaging.UI
Author: kvamshi
Created: 03-31-2022
Last Modified: 05-17-2022


Table of Contents 📑

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Data Models & ViewModels
  4. API Endpoints Overview
  5. Key Functional Areas
  6. Error Handling & Return Types
  7. Third-Party Integrations
  8. UML Class Diagram
  9. Sample Code Blocks & Usage Examples
  10. Conclusion

1. Overview & Purpose 🎯

The CarrierTypeController is an ASP.NET Core MVC controller responsible for managing Carrier Types in the IrbyImaging application. It provides the following functionality:

  • List all Carrier Types
  • Create a new Carrier Type
  • Edit an existing Carrier Type

This controller inherits from a BaseController to reuse common functionality (e.g., authentication, logging). It uses Entity Framework Core (IrbyContext) for data access and the HttpContextAccessor for retrieving user identity.


2. Dependencies & Technologies 🔧

Dependency Purpose
Microsoft.AspNetCore.Mvc MVC Controller base classes & attributes
Microsoft.AspNetCore.Authorization (Optionally) secure endpoints with policies/roles
Microsoft.EntityFrameworkCore Database access via DbContext
Microsoft.AspNetCore.Http Accessing HttpContext for user identity
Microsoft.Extensions.Configuration Reading configuration values (e.g., connection strings)
IrbyImaging.DbContext Contains IrbyContext (EF Core DbContext)
IrbyImaging.DomainClasses Domain entities: CarrierType, CarrierTypeDetail

3. Data Models & ViewModels 📊

3.1 CarrierType (Domain Model)

public class CarrierType
{
    public Guid Id { get; set; }
    public string Carrier { get; set; }
    public bool IsInactive { get; set; }
    public DateTime AddedDate { get; set; }
    public DateTime ModifiedDate { get; set; }
    public string AddedBy { get; set; }
    public string ModifiedBy { get; set; }

    // Used only for Index view to wrap details
    public List<CarrierTypeDetail> CarriersTypeDetail { get; set; }
}

3.2 CarrierTypeDetail (ViewModel)

public class CarrierTypeDetail
{
    public Guid Id { get; set; }
    public string Carrier { get; set; }
    public bool IsInactive { get; set; }
}

Note: The controller uses the CarrierType entity itself to hold a List<CarrierTypeDetail> for the Index view. In a more layered design, a separate view model class would be preferable.


4. API Endpoints Overview 🌐

HTTP Verb Route Action Description
GET /CarrierType Index() List all carrier types
GET /CarrierType/Create Create() Show form to create a new carrier
POST /CarrierType/Create Create(model) Process new carrier creation
GET /CarrierType/Edit/{id} Edit(id) Show form to edit an existing carrier
POST /CarrierType/Edit/{id} Edit(id, model) Process carrier update

5. Key Functional Areas ⚙️

5.1 Index - List Carrier Types

  • Method Signature:

    public async Task<IActionResult> Index()
    
  • Workflow:

    1. Queries all CarrierTypes ordered by Carrier name.
    2. Maps each database entity to a CarrierTypeDetail.
    3. Wraps the collection in a CarrierType view model.
    4. Returns the Index view with populated model.
  • Code Snippet:

    var atsContext = _context.CarrierTypes.OrderBy(a => a.Carrier);
    var carrierDetail = new CarrierType { CarriersTypeDetail = new List<CarrierTypeDetail>() };
    
    foreach (var rec in atsContext)
    {
        carrierDetail.CarriersTypeDetail.Add(new CarrierTypeDetail
        {
            Id = rec.Id,
            Carrier = rec.Carrier,
            IsInactive = rec.IsInactive
        });
    }
    
    return View(carrierDetail);
    

5.2 Create - Add New Carrier Type

5.2.1 GET: Display Create Form

  • Method Signature:

    public IActionResult Create()
    
  • Purpose:
    Prepares a new empty CarrierType and populates view data for any dropdowns (none required but scaffolded).

  • Code Snippet:

    var carrier = new CarrierType();
    ViewData["Carrier"] = new SelectList(_context.CarrierTypes, "Id", "Carrier");
    return View(carrier);
    

5.2.2 POST: Process Create Form

  • Method Signature:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Carrier,IsInactive")] CarrierType carrierType)
    
  • Workflow:

    1. Validate model state.
    2. Retrieve current user identity (defaults to "System" if not authenticated).
    3. Set audit fields:
      • Id = Guid.NewGuid()
      • AddedDate, ModifiedDate = Now
      • AddedBy, ModifiedBy = current user
      • IsInactive = false
    4. Save to database and redirect to Index.
  • Code Snippet:

    if (ModelState.IsValid)
    {
        var identityName = GetCurrentUserName() ?? "System";
        carrierType.Id = Guid.NewGuid();
        carrierType.AddedDate = carrierType.ModifiedDate = DateTime.Now;
        carrierType.AddedBy = carrierType.ModifiedBy = identityName;
        carrierType.IsInactive = false;
    
        _context.Add(carrierType);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    

5.3 Edit - Modify Existing Carrier Type

5.3.1 GET: Display Edit Form

  • Method Signature:
    public async Task<IActionResult> Edit(int? id)
    
  • Workflow:
    1. Check id != null, else return 404 NotFound.
    2. Fetch entity via _context.CarrierTypes.FindAsync(id).
    3. If not found, return 404.
    4. Populate ViewData and return view.

5.3.2 POST: Process Edit Form

  • Method Signature:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(Guid id, [Bind("Id,Carrier,IsInactive")] CarrierType carrierType)
    
  • Workflow:

    1. Validate route id matches carrierType.Id.
    2. If model state is valid:
      • Update ModifiedDate, ModifiedBy.
      • Call _context.Update(...) and _context.SaveChangesAsync().
    3. Handle DbUpdateConcurrencyException in case of concurrent edits.
    4. Redirect to Index.
  • Code Snippet:

    if (id != carrierType.Id) return NotFound();
    
    if (ModelState.IsValid)
    {
        try
        {
            carrierType.ModifiedDate = DateTime.Now;
            carrierType.ModifiedBy = GetCurrentUserName() ?? "System";
    
            _context.Update(carrierType);
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CarrierTypeExists(carrierType.Id))
                return NotFound();
            throw;
        }
        return RedirectToAction(nameof(Index));
    }
    

5.4 Utility Methods

Method Purpose
private bool CarrierTypeExists(Guid id) Checks existence of a CarrierType by Id in the database.
private bool CarrierTypeExists(Guid id)
{
    return _context.CarrierTypes.Any(e => e.Id == id);
}

6. Error Handling & Return Types 🛡️

  • 404 NotFound(): Returned when an expected record is missing.
  • RedirectToAction(nameof(Index)): On successful Create or Edit, redirects back to Index.
  • ModelState Checks: Ensures invalid input returns back to the form view with validation messages.
  • DbUpdateConcurrencyException: Catches EF Core concurrency violations; rethrows if record still exists.

7. Third-Party Integrations 🔌

  • Entity Framework Core: Core ORM for data persistence.
  • Microsoft Identity (via HttpContextAccessor): Retrieves current user claims for audit tracking.

8. UML Class Diagram 🏗️

classDiagram
    class BaseController {
        <<abstract>>
        - IrbyContext _context
        - IConfiguration _configuration
        + BaseController(IrbyContext, IConfiguration)
    }

    class CarrierTypeController {
        - IrbyContext _context
        - IHttpContextAccessor _httpContextAccessor
        - IConfiguration _configuration
        + Index() IActionResult
        + Create() IActionResult
        + Create(CarrierType) IActionResult
        + Edit(int?) IActionResult
        + Edit(Guid, CarrierType) IActionResult
        - CarrierTypeExists(Guid) bool
    }

    class CarrierType {
        + Guid Id
        + string Carrier
        + bool IsInactive
        + DateTime AddedDate
        + DateTime ModifiedDate
        + string AddedBy
        + string ModifiedBy
        + List~CarrierTypeDetail~ CarriersTypeDetail
    }

    class CarrierTypeDetail {
        + Guid Id
        + string Carrier
        + bool IsInactive
    }

    BaseController <|-- CarrierTypeController
    CarrierTypeController --> CarrierType
    CarrierType --> CarrierTypeDetail

9. Sample Code Blocks & Usage Examples 💡

9.1 Navigating the UI

  • List Carrier Types
    Browse to https://<host>/CarrierType to see a table of all carrier types.

  • Add New Carrier Type

    1. Click Create New.
    2. Fill in the Carrier name.
    3. Submit to add.
  • Edit an Existing Carrier Type

    1. From the Index, click Edit next to a carrier.
    2. Modify the name or toggle Inactive.
    3. Submit to save changes.

9.2 AJAX Example (Optional)

// Example: fetch carriers via AJAX (if JSON endpoint existed)
fetch('/CarrierType/GetAll')
  .then(res => res.json())
  .then(data => console.log('Carrier Types:', data));

Note: The current controller serves Razor views. For SPA or API-based use, consider adding JSON-returning endpoints.


10. Conclusion 🏁

The CarrierTypeController is a straightforward ASP.NET Core MVC controller that encapsulates CRUD operations for CarrierType entities. It demonstrates:

  • Use of EF Core for data access
  • Model binding and validation for form posts
  • Audit trail via HttpContextAccessor and timestamp fields
  • Basic error handling with 404 responses and concurrency checks

By following this pattern, you can extend similar controllers for other domain entities (e.g., AssetModels, Departments) with minimal boilerplate. 🎉


End of Documentation