📍 LocationController API Documentation

Welcome to the LocationController documentation for the IrbyImaging.UI.Controllers namespace. This document provides a comprehensive overview of how geographic locations (properties and field offices) are retrieved, processed, and exposed via HTTP endpoints in the LocationController.cs file.


Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Controller Structure
  4. Models & View Models
  5. Key Functional Areas
  6. Helper Methods & Utilities
  7. Error Handling & Return Types
  8. API Endpoints Overview
  9. Sample Usage & Code Snippets
  10. UML Class Diagram
  11. Conclusion

Overview & Purpose

The LocationController is responsible for:

  • Querying raw SQL from the IrbyContext (Entity Framework Core) to retrieve property and field-office data.
  • Transforming document index metadata into geolocatable addresses.
  • Calling a GeocodingService to convert addresses into latitude/longitude coordinates.
  • Exposing two HTTP GET endpoints for front‑end or external consumers to fetch location datasets.

🏆 Primary Goals

  • Provide a unified API for mapping legal document properties and field offices onto a map.
  • Cache and reuse geocoding results for performance (via IMemoryCache).
  • Leverage configuration settings (IConfiguration) and environment context (IWebHostEnvironment) for flexibility.

Dependencies & Technologies

Technology / Package Purpose
.NET Core / ASP.NET Core Web framework
Entity Framework Core (EF) ORM for database queries (FromSqlInterpolated used heavily)
Microsoft.Extensions.Caching In-memory caching of geocoding results
Microsoft.AspNetCore.Mvc MVC Controller base
IrbyImaging.DomainClasses Domain models (e.g., GeoLocation, JobAndFieldOfficeMapping)
IrbyImaging.UI.Services Custom service for geocoding (GeocodingService)
IrbyImaging.Utility Shared utilities (if any)
BouncyCastle.Ocsp (Imported but not directly used in this file)

Controller Structure

namespace IrbyImaging.UI.Controllers
{
    public class LocationController : BaseController
    {
        private readonly IrbyContext _context;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IMemoryCache _cache;
        private readonly GeocodingService _geocodingService;
        private readonly IConfiguration _configuration;

        // Constructor injection
        public LocationController(
            IrbyContext context,
            IHttpContextAccessor http,
            IWebHostEnvironment environment,
            IMemoryCache cache,
            GeocodingService geocodingService,
            IConfiguration configuration)
            : base(context, configuration)
        { ... }

        // Endpoints
        [HttpGet]
        public ActionResult<IEnumerable<GeoLocation>> GetLocations() { ... }

        [HttpGet]
        public ActionResult<IEnumerable<JobAndFieldOfficeMapping>> GetFieldLocations() { ... }
    }
}
  • Inherits from BaseController (presumably handles common tasks like user context, error logging).
  • Uses constructor injection for DbContext, caching, configuration, hosting environment, and a geocoding helper.

Models & View Models

  1. Location (Inner Class)

    public class Location
    {
      public int Id { get; set; }
      public double Latitude { get; set; }
      public double Longitude { get; set; }
      public string Name { get; set; }
    }
    
    • A lightweight helper inside the controller (not exposed as an endpoint type).
  2. GeoLocation (from IrbyImaging.DomainClasses)

    • Fields like DocumentImageId, Latitude, Longitude, Address, StreetAddress, etc.
    • Populated dynamically via raw SQL pivot operations.
  3. JobAndFieldOfficeMapping

    • Contains properties for field‐office details (MailingAddress, Manager, AssetCount, etc.) plus Latitude/Longitude added at runtime.

Key Functional Areas

GetLocations (Properties) 📌

  • Route: GET /api/Location/GetLocations
  • Purpose: Fetch all active legal-document properties of type 729903C1-2830-40F1-BF23-02829CBAC185, pivot their indexed attributes into columns, build an address, then geocode it.
  • Workflow:
    1. Raw SQL: Uses multiple temp tables (#Documents, #IndexList, #TempIndexList, #FinalList) to:
      • Extract document metadata.
      • Pivot attribute-value pairs into tabular form.
    2. Projection: Selects columns such as StreetAddress, City, State, Zip, Monthly Base Rent, etc.
    3. Address Concatenation:
      rec.Address = $"{rec.StreetAddress},{rec.City},{rec.State.Split('-')[0].Trim()} {rec.Zip}";
      
    4. Geocoding:
      var result = _geocodingService.GetCoordinates(rec.Address);
      rec.Latitude  = (decimal)result.Result.Value.Latitude;
      rec.Longitude = (decimal)result.Result.Value.Longitude;
      
    5. Return: ActionResult<IEnumerable<GeoLocation>> containing enriched location data.

GetFieldLocations (Field Offices) 🏢

  • Route: GET /api/Location/GetFieldLocations
  • Purpose: Retrieve all field offices and their aggregated statistics (jobs, employees, assets, etc.), then geocode their MailingAddress.
  • Workflow:
    1. Raw SQL: Joins FieldOffice, Employee, Job, Asset, Equipment, PurchaseOrder, WorkOrder to compute:
      • Manager, Superintendent, ProjectManager, Lead
      • Counts: jobs, employees, assets, equipment, POs, work orders
    2. Initial Lat/Long set to zeros (00.00000).
    3. Geocoding: Same as above, but uses office.MailingAddress.
    4. Return: ActionResult<IEnumerable<JobAndFieldOfficeMapping>>.

Helper Methods & Utilities

  • GeocodingService
    A custom service (in IrbyImaging.UI.Services) that wraps calls to an external geocoding provider (e.g., Google Maps, Mapbox).

    public Task<GeocodeResult> GetCoordinates(string address) { ... }
    
  • Caching
    Although IMemoryCache _cache is injected, this controller currently does not cache geocoding calls. Consider adding:

    if (!_cache.TryGetValue(address, out Coordinates coords)) { ... }
    
  • Configuration
    Uses IConfiguration for reading keys (e.g., geocoding API key).


Error Handling & Return Types

  • ActionResult
    • Returns 200 OK with payload on success.
    • Unhandled exceptions bubble up to global error handlers (e.g., middleware).
  • Potential Improvements
    • Validate SQL result sets (empty, invalid addresses).
    • Wrap geocoding calls in try/catch and return fallback lat/long.

API Endpoints Overview

Method URL Response Type Description
GET  /api/Location/GetLocations /api/Location/GetLocations IEnumerable<GeoLocation> List of property locations with geo data
GET  /api/Location/GetFieldLocations /api/Location/GetFieldLocations IEnumerable<JobAndFieldOfficeMapping> List of field offices with geo data

Sample Usage & Code Snippets

1. Calling via HttpClient (C#)

using System.Net.Http;
using System.Text.Json;

var client = new HttpClient { BaseAddress = new Uri("https://your-api.com/") };
var response = await client.GetAsync("api/Location/GetLocations");
response.EnsureSuccessStatusCode();

var json = await response.Content.ReadAsStringAsync();
var locations = JsonSerializer.Deserialize<List<GeoLocation>>(json);
Console.WriteLine($"Retrieved {locations.Count} locations.");

2. Example JSON Response (GetLocations)

[
  {
    "DocumentImageId": "a1b2c3d4-...",
    "Latitude": 34.052235,
    "Longitude": -118.243683,
    "Address": "123 Main St,Los Angeles,CA 90012",
    "StreetAddress": "123 Main St",
    "City": "Los Angeles",
    "State": "CA",
    "Zip": "90012",
    "MonthlyBaseRent": "2000",
    // ... other pivoted attributes ...
  },
  // ...
]

UML Class Diagram

classDiagram
    BaseController <|-- LocationController
    LocationController : - IrbyContext _context
    LocationController : - IHttpContextAccessor _httpContextAccessor
    LocationController : - IWebHostEnvironment _hostingEnvironment
    LocationController : - IMemoryCache _cache
    LocationController : - GeocodingService _geocodingService
    LocationController : - IConfiguration _configuration

    LocationController : + GetLocations() : ActionResult<IEnumerable<GeoLocation>>
    LocationController : + GetFieldLocations() : ActionResult<IEnumerable<JobAndFieldOfficeMapping>>
    
    class GeocodingService {
      + GetCoordinates(address:string) : Task<GeocodeResult>
    }

Conclusion

The LocationController bridges the gap between complex, pivoted database queries and easy‑to‑consume JSON endpoints that power mapping features in the UI. By leveraging raw SQL, EF Core, and a geocoding service, it provides a robust solution for displaying:

  • 📌 Legal Property Locations (with contract metadata)
  • 🏢 Field Office Locations (with operational counts)

Feel free to extend this controller by:

  • Adding caching of geocoding results to reduce API calls.
  • Implementing pagination or filtering parameters.
  • Securing endpoints via authorization attributes.

Happy mapping! 🗺️✨