🎫 TicketsController.md
Table of Contents 📑
- Overview & Purpose
- Dependencies & Technologies
- Constructor & DI Services
- Routing & Attributes
- Key Functional Areas
- View Models & Data Models
- Helper Methods & Utilities
- Error Handling & Return Types
- Third‑Party Integrations
- Sample Usage & Code Snippets
- UML Diagram
- Conclusion
Overview & Purpose
The TicketsController is the core MVC controller in the IrbyImaging.UI project that manages everything related to IT tickets (incidents & service requests).
It provides:
- 📋 Listing (open/archived, filtered & searched)
- 🆕 Creation (Incident / Request)
- 🔍 Detail views & attachments
- ✏️ Editing & updating (status, fields, “review after”)
- 🎯 Approval workflows
- 🔗 AJAX endpoints (e.g., user lookup, approval state)
Dependencies & Technologies
| Dependency | Purpose |
|---|---|
| Microsoft.AspNetCore.Mvc | MVC controller & routing |
| Microsoft.AspNetCore.Authorization | Securing actions |
EntityFrameworkCore (IrbyContext) |
Database access (Tickets, Updates, Options…) |
| IronPdf & iTextSharp | PDF merging & streaming |
| Newtonsoft.Json / System.Text.Json | JSON (de)serialization |
| AzureADRead (IrbyImaging.Utility) | Azure AD user lookup |
ITicketService & IActiveDirectoryService |
Business logic & AD integration |
Constructor & DI Services 🛠️
public TicketsController(
ITicketService ticketService,
IActiveDirectoryService activeDirectory,
IHttpContextAccessor http,
IrbyContext context,
IWebHostEnvironment environment,
IConfiguration configuration
) : base(context, configuration)
{
_ticketService = ticketService;
_activeDirectory = activeDirectory;
_httpContextAccessor = http;
_context = context;
_hostingEnvironment = environment;
_configuration = configuration;
}
Injected Services
ITicketService: Ticket CRUD & business logicIActiveDirectoryService: Resolve user details from Azure ADIHttpContextAccessor: Access HTTP context (claims, user name)IrbyContext: EF Core DB contextIWebHostEnvironment: Hosting paths & environmentIConfiguration: App settings & connection strings
Routing & Attributes 🚦
| Attribute | Purpose |
|---|---|
[RedirectIfUsingInternetExplorer] |
Block IE, show custom message |
[Route("…")] |
Custom URL segments (e.g. "Tickets/Create/Incident") |
[HttpGet], [HttpPost] |
HTTP verbs |
[ValidateAntiForgeryToken] |
CSRF protection on form POSTs |
Key Functional Areas 🔑
1. Ticket Listing & Filtering 🗂️
Index
[RedirectIfUsingInternetExplorer]
public IActionResult Index(string filter, TicketType type, string search)
- Route:
GET /Tickets - Purpose:
- If user is in IT → admin view: show all tickets, filter by type or status
- Else → user view: show tickets created by them
- ViewBag passes department, role, display name, filters, and splits Request vs Incident for Kendo data sources.
ViewIncidents, ArchivedRequests, ArchivedIncidents, ArchivedTotal
- Very similar to
Index, but scope and source methods change:GetTicketsForAdmin(...)vsGetArchivedTicketsForAdmin(...)- Filters to Incidents or Requests only, or All.
Archive & BigBuckets
| Action | Route | Description |
|---|---|---|
| Archive | /Archive |
List already archived tickets |
| BigBuckets | /BigBuckets |
Returns grouped metrics by selected columns and includeReviewAfter flag |
SearchTickets (GET & POST)
- GET: Renders search form. Populates dropdowns via EF Core: status, type, priority, hardware, software, enterprise, shared access, IrbySystems, employee list.
- POST: Applies filters to up to 100 most recent tickets:
- Deserialize
RequestedJsonintoList<TicketOptions> - Exclude or include completed request items
- Filter by status, type, hardware, software, etc.
- Filter by dates, ticket number, customer, description, last update
- Deserialize
[HttpPost]
public ActionResult SearchTickets(DateTime DatePick, …, bool excludeCompletedItems=false)
{
TempData["ExcludeCompletedItems"] = excludeCompletedItems;
var ticketList = _context.Tickets.Select(x => new TicketViewModel { … }).ToList();
if(excludeCompletedItems) { … }
// filter by status, type, options…
return View(ticketList);
}
2. Ticket Creation 🆕
CreateIncident (GET)
[Route("Tickets/Create/Incident")]
public IActionResult CreateIncident()
{
var vm = _ticketService.CreateIncidentViewModel(User.Identity.Name);
vm.CustomerList = new SelectList(vm.CustomerList, "Value", "Text", fullname);
return View(vm);
}
- Builds
IncidentViewModel, populates customer drop‑down.
CreateIncident (POST)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateIncident(IncidentViewModel incident)
{
if(incident.File!=null) {
using var ms=new MemoryStream();
incident.File.CopyTo(ms);
incident.ImageContents = ms.ToArray();
}
var createdId = await _ticketService.AddTicket(incident, fullName, incident.CustomerUsername);
if(createdId==Guid.Empty) {
ViewBag.SubmissionError="Error…";
return View(incident);
}
return RedirectToAction("Details", new {id=createdId});
}
CreateRequest (GET)
[Route("Tickets/Create/Request")]
public IActionResult CreateRequest()
{
var vm = _ticketService.CreateRequestViewModel(User.Identity.Name);
// Populate job list from _context.Jobs
vm.JobData = jobs.Select(j=>new SelectListItem {Text=$"{j.JdeNumber} - {j.Name}", Value=j.JdeNumber}).ToList();
vm.CustomerList = new SelectList(vm.CustomerList, "Value", "Text", fullname);
return View(vm);
}
CreateRequest (POST)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateRequest(RequestViewModel request)
{
if(request.File!=null) { … /* copy to request.ImageContents */ }
var createdId = await _ticketService.AddTicket(request, fullName, userName);
if(createdId==Guid.Empty) { /* show error */ }
// Send approval emails for each TicketOptions requiring approval
var list = JsonConvert.DeserializeObject<List<TicketOptions>>(request.RequestedJson);
foreach(var item in list.Where(i=>i.ApprovalRequired && !i.IsCompleted && !i.HasApprovalDecision))
{
var sent = await _ticketService.RequestApproval(createdId, item.Item, fullName, item.ApprovalDepartment);
if(sent)
{
var ticket = await _context.Tickets.FindAsync(createdId);
ticket.Status = TicketStatus.WaitingForApproval;
await _context.SaveChangesAsync();
}
}
return RedirectToAction("Details", new {id=createdId});
}
3. Ticket Details & Viewing 🔍
Details
[HttpGet]
public async Task<IActionResult> Details(Guid? id, bool excludeCompletedItems=false)
{
if(id==null) return NotFound();
var ticket = await _ticketService.GetTicketById(id);
if(ticket==null) return NotFound();
var vm = _ticketService.CreateTicketDetailsViewModel(ticket, excludeCompletedItems);
vm.ImageContents = ticket.ImageContents;
vm.ExcludeCompletedItems = excludeCompletedItems;
return View(vm);
}
ViewAttachment
Streams a PDF stored in Ticket.ImageContents:
public ActionResult ViewAttachment(Guid id)
{
var ticket = _context.Tickets.FirstOrDefault(t=>t.Id==id);
using var ms = new MemoryStream();
using var doc = new Document();
using var copy = new PdfSmartCopy(doc, ms) { /* merge if needed */ };
doc.Open();
using var reader = new PdfReader(ticket.ImageContents);
copy.AddDocument(reader);
doc.Close();
return File(ms.ToArray(), "application/pdf");
}
4. Ticket Editing & Updating 📝
EditRequest (GET)
Prepares existing request for editing:
public async Task<IActionResult> EditRequest(Guid? id)
{
// load ticket, build RequestViewModel + options + existing JSON
return View(model);
}
EditIncident (GET)
public async Task<IActionResult> EditIncident(Guid? id)
{
var ticket = await _ticketService.GetTicketById(id);
var vm = _ticketService.CreateTicketUpdateViewModel(ticket);
vm.TicketNumber = ticket.TicketNumber;
vm.ImageContents = ticket.ImageContents;
return View(vm);
}
EditRequest / EditIncident (POST)
- Save updated model via
_ticketService.EditTicket(...)orEditIncident(...) - On success: redirect (to Index or
ViewIncidents)
Update (GET & POST)
Allows updating status, updates JSON, “review after” fields:
public async Task<IActionResult> Update(Guid? id) { … }
[HttpPost]
public async Task<IActionResult> Update(Guid id, TicketUpdateViewModel updateRequest) { … }
UpdateDescription (AJAX)
[HttpPost]
public async Task<IActionResult> UpdateDescription(Guid id, string description,…, string json)
{
var ticket = await _context.Tickets.FindAsync(id);
// Merge new JSON items into ticket.RequestedJson
// Update description & shipping address
// Add one Update record for audit
await _context.SaveChangesAsync();
return Json(new {success=true});
}
5. Approval Workflow ✅
GetApprovalState
[HttpGet]
public IActionResult GetApprovalState(string name)
{
var opt = _context.Options.FirstOrDefault(o=>o.Item==name);
return Json(new {
ApprovalRequired = opt.ApprovalRequired.ToString(),
ApprovalDepartment = opt.ApprovalDepartment
});
}
RequestApproval
[HttpPost]
public async Task<IActionResult> RequestApproval(Guid id)
{
var ticket = await _context.Tickets.FindAsync(id);
var list = JsonConvert.DeserializeObject<List<TicketOptions>>(ticket.RequestedJson);
bool sent = false;
foreach(var item in list.Where(i=>i.ApprovalRequired && !i.IsCompleted && !i.HasApprovalDecision))
{
var didSend = await _ticketService.RequestApproval(id, item.Item, fullName, item.ApprovalDepartment);
if(didSend) {
sent = true;
ticket.Status = TicketStatus.WaitingForApproval;
}
}
var saved = await _context.SaveChangesAsync();
return Json(new { success = sent || saved>0 });
}
View Models & Data Models 📦
| Class | Description |
|---|---|
TicketViewModel |
Summary properties for grids/lists |
IncidentViewModel |
Create/Edit incident form |
RequestViewModel |
Create/Edit request form |
TicketDetailsViewModel |
Detailed view + updates |
TicketUpdateViewModel |
Status, ReviewAfter, New JSON |
EmployeeDetail |
AJAX return of AD/DB user info |
| Inner Classes | Type, Users, TicketOptions for search/filter UI |
TicketOptions Example
public class TicketOptions {
public string Index { get; set; }
public string Type { get; set; }
public string Item { get; set; }
public bool IsCompleted { get; set; }
public bool ApprovalRequired { get; set; }
public string ApprovalDepartment { get; set; }
public bool HasApprovalDecision { get; set; }
public bool IsApproved { get; set; }
public string ApprovalMessage { get; set; }
}
Helper Methods & Utilities 🔧
AzureADRead: Encapsulates Azure AD callsRedirectIfUsingInternetExplorerAttribute: Shows custom “IE not supported” page- JSON handling for
RequestedJson,ShippingAddress,EmployeeAndJobDetails
Error Handling & Return Types ⚠️
NotFound()for missing IDsViewBag.SubmissionErroron service-level failures- AJAX methods return
{ "success": false, "message": "…" }
Third‑Party Integrations 🌐
| Library | Functionality |
|---|---|
| IronPdf | Create/merge PDF streams |
| iTextSharp | Low-level PDF reading & copying |
| Newtonsoft.Json | Serialize / Deserialize RequestedJson & AJAX |
Sample Usage & Code Snippets 💻
Filtering Request items:
if (software.Count()>0 && software[0]!=null) {
var list = new List<TicketViewModel>();
foreach(var rn in ticketList) {
var reqs = JsonConvert.DeserializeObject<List<TicketOptions>>(rn.RequestedJson);
if(reqs.Any(o=>o.Type=="Software" && software.Contains(o.Item)))
list.Add(rn);
}
ticketList = list;
}
AJAX approval call (JavaScript):
$.post('/Tickets/RequestApproval', { id: ticketId })
.done(res=>res.success ? alert('Sent!') : alert('Failed'));
UML Diagram 📊
+-------------------+
| BaseController |
+-------------------+
▲
|
+-------------------------+
| TicketsController |
+-------------------------+
| - _ticketService |
| - _activeDirectory |
| - _httpContextAccessor |
| - _context (DbContext) |
| - _hostingEnvironment |
| - _configuration |
+-------------------------+
| + Index() |
| + ViewIncidents() |
| + Archived…() |
| + CreateIncident() |
| + CreateRequest() |
| + Details() |
| + Edit…() / Update() |
| + RequestApproval() |
| + SearchTickets() |
+-------------------------+
Conclusion 🏁
The TicketsController ties together EF Core, AD lookups, PDF tools, and rich client‑side filtering to deliver a full-featured IT ticketing interface.
By following the patterns here—dependency injection, view models, AJAX helpers, and robust error handling—you can extend or customize ticket flows, add new filters, or integrate additional services with minimal friction. Enjoy building! 🎉