Initial import of MaxInventory

This commit is contained in:
dingo
2026-03-19 09:06:14 -04:00
commit b53d3df923
166 changed files with 81410 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**
+13
View File
@@ -0,0 +1,13 @@
.vs/
.vscode/
[Bb]in/
[Oo]bj/
*.user
*.suo
*.userosscache
*.sln.docstates
src/MaxInventory.Web/FutureSecrets.json
src/MaxInventory.Web/appsettings.Development.json
+28
View File
@@ -0,0 +1,28 @@
# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/runtime:10.0 AS base
USER $APP_UID
WORKDIR /app
# This stage is used to build the service project
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["MaxInventory.csproj", "."]
RUN dotnet restore "./MaxInventory.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./MaxInventory.csproj" -c $BUILD_CONFIGURATION -o /app/build
# This stage is used to publish the service project to be copied to the final stage
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./MaxInventory.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MaxInventory.dll"]
@@ -0,0 +1,9 @@
namespace MaxInventory.Authentication.Abstractions
{
public interface IAdminGroupSource
{
Task<IReadOnlyCollection<string>> GetViewGroupsAsync(CancellationToken cancellationToken = default);
Task<IReadOnlyCollection<string>> GetEditGroupsAsync(CancellationToken cancellationToken = default);
Task<IReadOnlyCollection<string>> GetAdminGroupsAsync(CancellationToken cancellationToken = default);
}
}
@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Configuration;
namespace MaxInventory.Authentication.Abstractions
{
public interface IAuthProvider
{
string Mode { get; }
AuthenticationBuilder Configure(
AuthenticationBuilder builder,
IConfiguration configuration
);
}
}
@@ -0,0 +1,10 @@
using MaxInventory.Authentication.Core;
using System.Security.Claims;
namespace MaxInventory.Authentication.Abstractions
{
public interface IIdentityContextFactory
{
IdentityContext Create(ClaimsPrincipal principal);
}
}
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MaxInventory.Authentication.Configuration
{
public static class AdminGroupSources
{
public const string Max = "MAX";
public const string Ad = "AD";
}
}
@@ -0,0 +1,29 @@
namespace MaxInventory.Authentication.Configuration
{
public static class AuthEnvironment
{
public const string AuthMode = "AUTH_MODE";
public const string ViewGroups = "AUTH_VIEW_GROUPS";
public const string EditGroups = "AUTH_EDIT_GROUPS";
public const string AdminGroups = "AUTH_ADMIN_GROUPS";
public const string AdminGroupSource = "AUTH_GROUP_SOURCE";
public const string AdfsMetadataAddress = "ADFS_METADATA_ADDRESS";
public const string AdfsRealm = "ADFS_WTRELM";
public const string AdfsReply = "ADFS_WREPLY";
public const string AdfsCallbackPath = "ADFS_CALLBACK_PATH";
public const string AdfsHomeRealm = "ADFS_WHR";
public const string AdfsAuthType = "ADFS_WAUTH";
public const string AdfsValidIssuers = "ADFS_VALID_ISSUERS";
public const string OidcAuthority = "OIDC_AUTHORITY";
public const string OidcClientId = "OIDC_CLIENT_ID";
public const string OidcClientSecret = "OIDC_CLIENT_SECRET";
public const string OidcCallbackPath = "OIDC_CALLBACK_PATH";
public const string OidcSignedOutCallbackPath = "OIDC_SIGNOUT_CALLBACK_PATH";
public const string OidcScopes = "OIDC_SCOPES";
public const string OidcRoleClaimType = "OIDC_ROLE_CLAIM_TYPE";
public const string OidcNameClaimType = "OIDC_NAME_CLAIM_TYPE";
public const string OidcValidIssuers = "OIDC_VALID_ISSUERS";
}
}
@@ -0,0 +1,8 @@
namespace MaxInventory.Authentication.Configuration
{
public class AuthModes
{
public const string WsFed = "WSFED";
public const string Oidc = "OIDC";
}
}
@@ -0,0 +1,70 @@
using MaxInventory.Authentication.Configuration;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace MaxInventory.Authentication.Core
{
public sealed class AdminCookieValidationEvents : CookieAuthenticationEvents
{
private static readonly string[] GroupClaimTypes =
{
"groups",
"group",
"role",
"roles",
ClaimTypes.GroupSid,
ClaimTypes.Role,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
"http://schemas.xmlsoap.org/claims/Group"
};
private readonly IConfiguration _configuration;
public AdminCookieValidationEvents(IConfiguration configuration)
{
_configuration = configuration;
}
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
if (context.Principal?.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return;
}
var path = context.HttpContext.Request.Path;
if (!path.StartsWithSegments("/Admin", StringComparison.OrdinalIgnoreCase))
{
return;
}
var configuredGroups = (_configuration[AuthEnvironment.AdminGroups] ?? string.Empty)
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var principalGroups = identity.Claims
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
.Select(c => c.Value);
var isAdmin = configuredGroups.Length > 0 &&
principalGroups.Any(group =>
configuredGroups.Contains(group, StringComparer.OrdinalIgnoreCase));
if (!isAdmin)
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}
}
}
@@ -0,0 +1,97 @@
using MaxInventory.Authentication.Abstractions;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
namespace MaxInventory.Authentication.Core
{
public sealed class AdminRoleClaimsTransformation : IClaimsTransformation
{
private static readonly string[] GroupClaimTypes =
{
"groups",
"group",
"role",
"roles",
ClaimTypes.GroupSid,
ClaimTypes.Role,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
"http://schemas.xmlsoap.org/claims/Group"
};
private readonly IAdminGroupSource _adminGroupSource;
public AdminRoleClaimsTransformation(IAdminGroupSource adminGroupSource)
{
_adminGroupSource = adminGroupSource;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
{
return principal;
}
if (HasRole(identity, AuthRoles.Admin) &&
HasRole(identity, AuthRoles.EditAdd) &&
HasRole(identity, AuthRoles.View))
{
return principal;
}
var principalGroups = identity.Claims
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
.Select(c => c.Value);
var groupSet = new HashSet<string>(principalGroups, StringComparer.OrdinalIgnoreCase);
var isViewer = IsInConfiguredGroup(groupSet, await _adminGroupSource.GetViewGroupsAsync());
var isEditor = IsInConfiguredGroup(groupSet, await _adminGroupSource.GetEditGroupsAsync());
var isAdmin = IsInConfiguredGroup(groupSet, await _adminGroupSource.GetAdminGroupsAsync());
if (isAdmin)
{
AddRole(identity, AuthRoles.Admin);
AddRole(identity, AuthRoles.EditAdd);
AddRole(identity, AuthRoles.View);
return principal;
}
if (isEditor)
{
AddRole(identity, AuthRoles.EditAdd);
AddRole(identity, AuthRoles.View);
return principal;
}
if (isViewer)
{
AddRole(identity, AuthRoles.View);
}
return principal;
}
private static bool IsInConfiguredGroup(HashSet<string> principalGroups, IReadOnlyCollection<string> configuredGroups)
{
if (configuredGroups.Count == 0)
return false;
return configuredGroups.Any(principalGroups.Contains);
}
private static bool HasRole(ClaimsIdentity identity, string role)
{
return identity.Claims.Any(c => c.Type == ClaimTypes.Role &&
string.Equals(c.Value, role, StringComparison.OrdinalIgnoreCase));
}
private static void AddRole(ClaimsIdentity identity, string role)
{
if (!HasRole(identity, role))
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
}
}
@@ -0,0 +1,9 @@
namespace MaxInventory.Authentication.Core
{
public static class AuthRoles
{
public const string Admin = "SG-OMB-IT";
public const string EditAdd = "EditAdd";
public const string View = "View";
}
}
@@ -0,0 +1,40 @@
using Microsoft.Extensions.Configuration;
using MaxInventory.Authentication.Abstractions;
using MaxInventory.Authentication.Configuration;
namespace MaxInventory.Authentication.Core
{
public sealed class ConfiguredAdminGroupSource : IAdminGroupSource
{
private readonly IConfiguration _configuration;
public ConfiguredAdminGroupSource(IConfiguration configuration)
{
_configuration = configuration;
}
public Task<IReadOnlyCollection<string>> GetViewGroupsAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult<IReadOnlyCollection<string>>(ReadGroups(AuthEnvironment.ViewGroups));
}
public Task<IReadOnlyCollection<string>> GetEditGroupsAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult<IReadOnlyCollection<string>>(ReadGroups(AuthEnvironment.EditGroups));
}
public Task<IReadOnlyCollection<string>> GetAdminGroupsAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult<IReadOnlyCollection<string>>(ReadGroups(AuthEnvironment.AdminGroups));
}
private string[] ReadGroups(string key)
{
return (_configuration[key] ?? string.Empty)
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
}
}
}
@@ -0,0 +1,10 @@
namespace MaxInventory.Authentication.Core
{
public sealed class IdentityContext
{
public required string UserId { get; init; }
public required string DisplayName { get; init; }
public required IReadOnlyCollection<string> Groups { get; init; }
public required IReadOnlyCollection<string?> Roles { get; init; }
}
}
@@ -0,0 +1,61 @@
using MaxInventory.Authentication.Abstractions;
using System.Security.Claims;
namespace MaxInventory.Authentication.Core
{
public sealed class IdentityContextFactory : IIdentityContextFactory
{
private static readonly string[] GroupClaimTypes =
{
"groups",
"group",
"role",
"roles",
ClaimTypes.GroupSid,
ClaimTypes.Role,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
"http://schemas.xmlsoap.org/claims/Group"
};
private static readonly string[] RoleClaimTypes =
{
"role",
"roles",
ClaimTypes.Role,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
};
public IdentityContext Create(ClaimsPrincipal principal)
{
var groups = principal.Claims
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
.Select(c => c.Value)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
var roles = principal.Claims
.Where(c => RoleClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
.Select(c => c.Value)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
var userId = principal.FindFirstValue(ClaimTypes.NameIdentifier)
?? principal.FindFirstValue("sub")
?? principal.Identity?.Name
?? "unknown";
var displayName = principal.FindFirstValue(ClaimTypes.Name)
?? principal.Identity?.Name
?? userId;
return new IdentityContext
{
UserId = userId,
DisplayName = displayName,
Groups = groups,
Roles = roles
};
}
}
}
@@ -0,0 +1,49 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MaxInventory.Authentication.Core
{
public sealed class MemoryCacheTicketStore : ITicketStore
{
private const string KeyPrefix = "auth-ticket-";
private readonly IMemoryCache _cache;
private readonly TimeSpan _fallbackLifetime = TimeSpan.FromHours(8);
public MemoryCacheTicketStore(IMemoryCache cache)
{
_cache = cache;
}
public async Task<string> StoreAsync(AuthenticationTicket ticket)
{
var key = $"{KeyPrefix}{Guid.NewGuid():N}";
await RenewAsync(key, ticket);
return key;
}
public Task RenewAsync(string key, AuthenticationTicket ticket)
{
var expiration = ticket.Properties.ExpiresUtc?.UtcDateTime ?? DateTime.UtcNow.Add(_fallbackLifetime);
_cache.Set(key, ticket, expiration);
return Task.CompletedTask;
}
public Task<AuthenticationTicket?> RetrieveAsync(string key)
{
_cache.TryGetValue(key, out AuthenticationTicket? ticket);
return Task.FromResult(ticket);
}
public Task RemoveAsync(string key)
{
_cache.Remove(key);
return Task.CompletedTask;
}
}
}
@@ -0,0 +1,80 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using MaxInventory.Authentication.Providers.AdfsWsFed;
using MaxInventory.Authentication.Abstractions;
using MaxInventory.Authentication.Configuration;
using MaxInventory.Authentication.Core;
using MaxInventory.Authentication.Providers.Oidc;
namespace MaxInventory.Authentication.Extensions
{
public static class AuthenticationServiceCollectionExtensions
{
public static IServiceCollection AddAuthentication(
this IServiceCollection services,
IConfiguration configuration,
Action<AuthorizationOptions>? configureAuthorization = null)
{
services.TryAddSingleton<IIdentityContextFactory, IdentityContextFactory>();
services.TryAddSingleton<IAdminGroupSource, ConfiguredAdminGroupSource>();
services.AddScoped<IClaimsTransformation, AdminRoleClaimsTransformation>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<IAuthProvider, AdfsWsFedAuthProvider>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<IAuthProvider, OidcAuthProvider>());
var authMode = configuration[AuthEnvironment.AuthMode] ?? AuthModes.Oidc;
var challengeScheme = authMode.Equals(AuthModes.Oidc, StringComparison.OrdinalIgnoreCase)
? OidcAuthProvider.Scheme
: AdfsWsFedAuthProvider.Scheme;
var authBuilder = services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = challengeScheme;
});
authBuilder.AddCookie(options =>
{
options.Cookie.Name = "secure-network.auth";
options.AccessDeniedPath = "/AccesDenied";
options.EventsType = typeof(AdminCookieValidationEvents);
});
var providers = new IAuthProvider[]
{
new OidcAuthProvider(),
new AdfsWsFedAuthProvider()
};
var provider = providers.FirstOrDefault(p =>
p.Mode.Equals(authMode, StringComparison.OrdinalIgnoreCase));
if (provider is null)
{
throw new InvalidOperationException($"Unsupported AUTH_MODE: {authMode}");
}
provider.Configure(authBuilder, configuration);
services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireRole(AuthRoles.View,AuthRoles.EditAdd, AuthRoles.Admin)
.Build();
options.AddPolicy("ViewOnly", policy => policy.RequireRole(AuthRoles.View, AuthRoles.EditAdd, AuthRoles.Admin));
options.AddPolicy("CanEdit", policy => policy.RequireRole(AuthRoles.EditAdd, AuthRoles.Admin));
options.AddPolicy("AdminOnly", PolicySchemeHandler => PolicySchemeHandler.RequireRole(AuthRoles.Admin));
configureAuthorization?.Invoke(options);
});
return services;
}
}
}
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.WsFederation" Version="8.0.8" />
</ItemGroup>
</Project>
@@ -0,0 +1,122 @@
using MaxInventory.Authentication.Abstractions;
using MaxInventory.Authentication.Configuration;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.WsFederation;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Tokens.Saml;
using Microsoft.IdentityModel.Protocols.WsFederation;
namespace MaxInventory.Authentication.Providers.AdfsWsFed;
public sealed class AdfsWsFedAuthProvider : IAuthProvider
{
public const string Scheme = WsFederationDefaults.AuthenticationScheme;
public string Mode => AuthModes.WsFed;
AuthenticationBuilder IAuthProvider.Configure(
AuthenticationBuilder builder,
IConfiguration configuration)
{
var metadataAddress = configuration[AuthEnvironment.AdfsMetadataAddress];
var realm = configuration[AuthEnvironment.AdfsRealm];
var callbackPath = configuration[AuthEnvironment.AdfsCallbackPath] ?? "/signin-wsfed";
var replyUrl = configuration[AuthEnvironment.AdfsReply];
var homeRealm = configuration[AuthEnvironment.AdfsHomeRealm];
var authType = configuration[AuthEnvironment.AdfsAuthType];
var configuredValidIssuers = configuration[AuthEnvironment.AdfsValidIssuers];
if (string.IsNullOrWhiteSpace(metadataAddress))
{
throw new InvalidOperationException(
$"Missing required configuration: {AuthEnvironment.AdfsMetadataAddress}");
}
if (string.IsNullOrWhiteSpace(realm))
{
throw new InvalidOperationException(
$"Missing required configuration: {AuthEnvironment.AdfsRealm}");
}
var validIssuers = configuredValidIssuers?
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Where(v => !string.IsNullOrWhiteSpace(v))
.ToArray() ?? [];
// Default ADFS issuer pattern when explicit issuer(s) are not configured.
if (validIssuers.Length == 0 && Uri.TryCreate(metadataAddress, UriKind.Absolute, out var metadataUri))
{
validIssuers = [$"{metadataUri.Scheme}://{metadataUri.Authority}/adfs/services/trust"];
}
return builder.AddWsFederation(options =>
{
options.TokenHandlers.Clear();
options.TokenHandlers.Add(new CustomSamlSecurityTokenHandler());
options.Wtrealm = realm;
options.MetadataAddress = metadataAddress;
options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuers = validIssuers
};
options.Events = new WsFederationEvents()
{
OnRedirectToIdentityProvider = context =>
{
context.ProtocolMessage ??= new WsFederationMessage();
if (!string.IsNullOrWhiteSpace(replyUrl))
{
context.ProtocolMessage.Wreply = replyUrl;
}
if (!string.IsNullOrWhiteSpace(homeRealm))
{
context.ProtocolMessage.Whr = homeRealm;
}
if (!string.IsNullOrWhiteSpace(authType))
{
context.ProtocolMessage.Wa = authType;
}
return Task.CompletedTask;
}
};
});
}
public class CustomSamlSecurityTokenHandler : SamlSecurityTokenHandler
{
public override async Task<TokenValidationResult> ValidateTokenAsync(string token, TokenValidationParameters validationParameters)
{
if (validationParameters.ConfigurationManager is not null)
{
var federationConfig = await validationParameters.ConfigurationManager
.GetBaseConfigurationAsync(CancellationToken.None)
.ConfigureAwait(false);
var dynamicIssuers = new[] { federationConfig.Issuer };
validationParameters.ValidIssuers = validationParameters.ValidIssuers is not null
? dynamicIssuers
: validationParameters.ValidIssuers.Concat(dynamicIssuers);
validationParameters.IssuerSigningKeys = validationParameters.IssuerSigningKeys is not null
? federationConfig.SigningKeys
: validationParameters.IssuerSigningKeys.Concat(federationConfig.SigningKeys);
}
return await base.ValidateTokenAsync(token, validationParameters).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,89 @@
using MaxInventory.Authentication.Abstractions;
using MaxInventory.Authentication.Configuration;
using Microsoft.AspNetCore.Authentication;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace MaxInventory.Authentication.Providers.Oidc;
public sealed class OidcAuthProvider : IAuthProvider
{
public const string Scheme = "oidc";
public string Mode => AuthModes.Oidc;
public AuthenticationBuilder Configure(
AuthenticationBuilder builder,
IConfiguration configuration)
{
var authority = configuration[AuthEnvironment.OidcAuthority];
var clientId = configuration[AuthEnvironment.OidcClientId];
var clientSecret = configuration[AuthEnvironment.OidcClientSecret];
var callbackPath = configuration[AuthEnvironment.OidcCallbackPath] ?? "/signin-oidc";
var signedOutCallbackPath = configuration[AuthEnvironment.OidcSignedOutCallbackPath] ?? "/signout-callback-oidc";
var scopes = (configuration[AuthEnvironment.OidcScopes] ?? "openid;profile;email;role")
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var roleClaimType = configuration[AuthEnvironment.OidcRoleClaimType]
?? "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";
var nameClaimType = configuration[AuthEnvironment.OidcNameClaimType]
?? "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
var configuredValidIssuers = configuration[AuthEnvironment.OidcValidIssuers];
if (string.IsNullOrWhiteSpace(authority))
{
throw new InvalidOperationException(
$"Missing required configuration: {AuthEnvironment.OidcAuthority}");
}
if (string.IsNullOrWhiteSpace(clientId))
{
throw new InvalidOperationException(
$"Missing required configuration: {AuthEnvironment.OidcClientId}");
}
return builder.AddOpenIdConnect(Scheme, options =>
{
options.Authority = authority;
options.ClientId = clientId;
options.ClientSecret = clientSecret;
options.CallbackPath = callbackPath;
options.SignedOutCallbackPath = signedOutCallbackPath;
options.ResponseType = "code";
options.SaveTokens = false;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Clear();
foreach (var scope in scopes)
{
options.Scope.Add(scope);
}
var validIssuers = configuredValidIssuers?
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Where(v => !string.IsNullOrWhiteSpace(v))
.ToArray();
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = validIssuers is { Length: > 0 },
ValidIssuers = validIssuers,
NameClaimType = nameClaimType,
RoleClaimType = roleClaimType
};
options.Events = new OpenIdConnectEvents()
{
OnRedirectToIdentityProvider = context =>
{
var builder = new UriBuilder(context.ProtocolMessage.RedirectUri);
builder.Scheme = "https";
builder.Port = 44374;// 1;
context.ProtocolMessage.RedirectUri = builder.ToString();
return Task.FromResult(0);
}
};
});
}
}
+16
View File
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
</ItemGroup>
</Project>
+6
View File
@@ -0,0 +1,6 @@
<Solution>
<Project Path="MaxInventory.Authentication/MaxInventory.Authentication.csproj" Id="c1189b9b-4806-4281-ad95-6c50f1199d25" />
<Project Path="src/MaxInventory.Core/MaxInventory.Core.csproj" Id="811e1f0d-a0d1-449a-8787-6a54c382515c" />
<Project Path="src/MaxInventory.Infrastructure/MaxInventory.Infrastructure.csproj" Id="c97d502d-a07f-41e9-a6c7-a8254d9c3c70" />
<Project Path="src/MaxInventory.Web/MaxInventory.Web.csproj" />
</Solution>
+2
View File
@@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
+10
View File
@@ -0,0 +1,10 @@
{
"profiles": {
"MaxInventory": {
"commandName": "Project"
},
"Container (Dockerfile)": {
"commandName": "Docker"
}
}
}
@@ -0,0 +1,51 @@
using MaxInventory.Core.Enums;
namespace MaxInventory.Core.Configuration
{
/// <summary>
/// Complete definition of a content type, bundling all metadata needed
/// for dynamic UI generation, API routing, and data handling
/// </summary>
public sealed class ContentTypeDefinition
{
///<summary>
///Enum identifier for this content type.
///</summary>
public required ContentTypeName ContentType { get; init; }
///<summary>
///Human-readable display name.
///</summary>
public required string DisplayName { get; init; }
///<summary>API endpoint segment (e.g., "systems", "customer_zones").
///Used to construct the full API URL: {BaseUrl}/{ApiEndpoint}
///</summary>
public required string ApiEndpoint { get; init; }
///<summary>
///URL slug used in the Blazer route
///</summary>
public required string UrlSlug { get; init; }
///<summary>
///The System.Type of the model class (e.g., typeof(SystemRecord)).
/// </summary>
public required Type ModelType { get; init; }
///<summary>
///Ordered field definitions for this content type.
/// </summary>
public required IReadOnlyList<FieldDefinition> Fields { get; init; }
///<summary>
///The property name used as the primary display identifier for this entity
///(e.g., "ShortName" for Systems, "Name" for Devices).
/// </summary>
public required string DisplayPropertyName { get; init; }
///<summary>CSS class for the nav menu icon</summary>
public string IconCssClass { get; init; } = "bi-grid";
}
}
@@ -0,0 +1,18 @@
namespace MaxInventory.Core.Configuration
{
/// <summary>
/// Represetns a single selectable option in a dropdown field.
/// </summary>
public sealed class DropdownOption
{
///<summary>The value stored and sent to the API.</summary>
public required string Value { get; init; }
///<summary>Human-readable lable shown in the UI dropdown.</summary>
public required string DisplayLabel { get; init; }
///<summary>Optional tooltip description shown on hover to explain the option.</summary>
public string? Description { get; init; }
}
}
@@ -0,0 +1,17 @@
using MaxInventory.Core.Enums;
namespace MaxInventory.Core.Configuration
{
/// <summary>
/// A named collection of dropdown options used by one or more fields across content types.
/// All option sets are registered centrally in the DropdownOptionRegistry.
/// </summary>
public sealed class DropdownOptionSet
{
///<summary>Unique name identifying this option set.</summary>
public required string Name { get; init; }
///<summary>The ordered list of available options.</summary>
public required IReadOnlyList<DropdownOption> Options { get; init; }
}
}
@@ -0,0 +1,44 @@
using MaxInventory.Core.Enums;
namespace MaxInventory.Core.Configuration
{
/// <summary>
/// Metadata describing a single field on a content type.
/// Drives the DataGrid columns, EntityForm inputs, sorting, and filtering behavior.
/// </summary>
public sealed class FieldDefinition
{
/// <summary>The C# property name on the model class.</summary>
public required string PropertyName { get; init; }
/// <summary>The JSON property name sent to/from the API.</summary>
public required string JsonPropertyName { get; init; }
/// <summary>Display name shown in column headers and form labels.</summary>
public required string DisplayName { get; init; }
/// <summary>Input Type for form rendering and filter behavior.</summary>
public required InputType InputType { get; init; }
/// <summary>
/// If InputType is Dropdown, the name of the DropdownOptionSet to use.
/// Must match a registered name in the DropdownOptionRegistry.
/// </summary>
public string? DropdownOptionSetName { get; init; }
/// <summary>Whether this field is required for create/edit operations.</summary>
public bool IsRequired { get; init; }
/// <summary>Whether this field is the primary ID (read-only, assigned by API).</summary>
public bool IsId { get; init; }
/// <summary>Display order - lower numbers appear first/leftmost in the grid.</summary>
public int SortOrder { get; init; }
/// <summary>Whether to show this field as a column in the data grid.</summary>
public bool ShowInGrid { get; init; } = true;
/// <summary>Whether this field is editable in forms. ID fields are typically not editable.</summary>
public bool IsEditable { get; init; } = true;
}
}
@@ -0,0 +1,23 @@
using MaxInventory.Core.Enums;
namespace MaxInventory.Core.Configuration
{
/// <summary>
/// Represents a discovered relationship result - a record from another
/// content type that is related to the currently viewed entity.
/// </summary>
public sealed class RelatedRecord
{
/// <summary>Human-readable label for the relationship.</summary>
public required string RelationshipLabel { get; init; }
/// <summary>The content type of the related record.</summary>
public required ContentTypeName ContentType { get; init; }
/// <summary>The ID of the related record (for navigation).</summary>
public required int Id { get; init; }
/// <summary>A display-friendly name for the related record.</summary>
public required string DisplayName { get; init; }
}
}
@@ -0,0 +1,43 @@
namespace MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
/// <summary>
/// Defines how to discover related records between two content types.
/// When viewing a record of the source content type, matching records
/// from the target content type are found by comparing field values.
/// </summary>
public sealed class RelationshipRule
{
/// <summary>The content type this rule applies to (the "source" side being viewed).</summary>
public required ContentTypeName SourceContentType { get; init; }
/// <summary>The property on the source entity whose value to match.</summary>
public required string SourcePropertyName { get; init; }
/// <summary>The content type to search for matches (the "target" side).</summary>
public required ContentTypeName TargetContentType { get; init; }
/// <summary>The property on the target entity to match against.</summary>
public required string TargetPropertyName { get; init; }
/// <summary>Human-readable label for the relationship (e.g., "Hosted VMs", "Host System").</summary>
public required string DisplayLabel { get; init; }
/// <summary>
/// Optional: only apply this rule when a source field has a specific value.
/// For example, only show "Hosted VMs" when System.Func == "HYP".
/// </summary>
public string? SourceFilterPropertyName { get; init; }
/// <summary>The value that the source filter property must match for this rule to apply.</summary>
public string? SourceFilterValue { get; init; }
/// <summary>
/// Optional: only include target records when a target field has a specific value.
/// </summary>
public string? TargetFilterPropertyName { get; init; }
/// <summary>The value that the target filter property must match for a target record to be included.</summary>
public string? TargetFilterValue { get; init; }
}
@@ -0,0 +1,17 @@
namespace MaxInventory.Core.Enums
{
/// <summary>
/// Identifies each content type managed by the inventory system.
/// Add new entries here when adding new content types.
/// </summary>
public enum ContentTypeName
{
Systems,
Devices,
Ips,
Subnets,
Vms,
CustomerZones,
ApplicationZones
}
}
+17
View File
@@ -0,0 +1,17 @@
namespace MaxInventory.Core.Enums
{
/// <summary>
/// Defines the input control type used for a field in forms and filters.
/// </summary>
public enum InputType
{
///<summary>Single-line text input.</summary>
Text,
/// <summary>Numeric integer input.</summary>
Integer,
/// <summary>Dropdown select populated from DropdownOptionSet.</summary>
Dropdown,
/// <summary>Multi-line text area (for Notes and similar fields).</summary>
TextArea
}
}
@@ -0,0 +1,11 @@
namespace MaxInventory.Core.Enums
{
/// <summary>
/// Defines the direction for column sorting in data grids.
/// </summary>
public enum SortDirection
{
Ascending,
Descending
}
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@@ -0,0 +1,14 @@
using System.Text.Json.Serialization;
namespace MaxInventory.Core.Models
{
/// <summary>
/// Response returned by the API when creating a new entity.
/// Contains the server-assigned ID of the newly created record.
/// </summary>
public sealed class ApiCreateResponse
{
[JsonPropertyName("id")]
public int Id { get; set; }
}
}
@@ -0,0 +1,27 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MaxInventory.Core.Models
{
/// <summary>
/// Represents an Application Zone record in the inventory.
/// Zones are identified by a hex ID and name.
/// </summary>
public sealed class ApplicationZoneRecord : IInventoryEntity
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("hex_code")]
public string HexCode { get; set; } = "";
[JsonPropertyName("name")]
public string Name { get; set; } = "";
[JsonPropertyName("notes")]
public string Notes { get; set; } = "";
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
}
}
@@ -0,0 +1,28 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MaxInventory.Core.Models
{
/// <summary>
/// Represents a Customer Zone record in the inventory.
/// Zones are identified by a hex ID and name.
/// </summary>
public sealed class CustomerZoneRecord : IInventoryEntity
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("hex_code")]
public string HexCode { get; set; } = "";
[JsonPropertyName("name")]
public string Name { get; set; } = "";
[JsonPropertyName("notes")]
public string Notes { get; set; } = "";
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
}
}
@@ -0,0 +1,48 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MaxInventory.Core.Models
{
/// <summary>
/// Represents a Device record in the inventory.
/// Devices are physical hardware items tracked by bar code, model, and location.
/// </summary>
public sealed class DeviceRecord : IInventoryEntity
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("status")]
public string Status { get; set; } = "";
[JsonPropertyName("name")]
public string Name { get; set; } = "";
[JsonPropertyName("bar_code")]
public string BarCode { get; set; } = "";
[JsonPropertyName("model")]
public string Model { get; set; } = "";
[JsonPropertyName("serial_number")]
public string SerialNumber { get; set; } = "";
[JsonPropertyName("firmware")]
public string Firmware { get; set; } = "";
[JsonPropertyName("data_center")]
public string DataCenter { get; set; } = "";
[JsonPropertyName("location")]
public string Location { get; set; } = "";
[JsonPropertyName("admin")]
public string Admin { get; set; } = "";
[JsonPropertyName("notes")]
public string Notes { get; set; } = "";
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
}
}
@@ -0,0 +1,15 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MaxInventory.Core.Models
{
/// <summary>
/// Marker interface for all inventory entity types.
/// Every entity returned from the API has an integer ID assigned by the server.
/// </summary>
public interface IInventoryEntity
{
int Id { get; set; }
public Dictionary<string, JsonElement> ExtensionData { get; set; }
}
}
+52
View File
@@ -0,0 +1,52 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MaxInventory.Core.Models
{
/// <summary>
/// Represents an IP address record in the inventory.
/// Tracks IP assignments to host with protocol and purpose classifications.
/// </summary>
public sealed class IpRecord : IInventoryEntity
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("protocol")]
public string Protocol { get; set; } = "";
[JsonPropertyName("ip")]
public string Ip { get; set; } = "";
[JsonPropertyName("mask_bits")]
public string MaskBits { get; set; } = "";
[JsonPropertyName("host_name")]
public string HostName { get; set; } = "";
[JsonPropertyName("purpose")]
public string Purpose { get; set; } = "";
[JsonPropertyName("trust_zone")]
public string TrustZone { get; set; } = "";
[JsonPropertyName("data_center_zone")]
public string DataCenterZone { get; set; } = "";
[JsonPropertyName("vlan")]
public string Vlan { get; set; } = "";
[JsonPropertyName("customer_zone")]
public string CustomerZone { get; set; } = "";
[JsonPropertyName("application_zone")]
public string ApplicationZone { get; set; } = "";
[JsonPropertyName("notes")]
public string Notes { get; set; } = "";
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
}
}
@@ -0,0 +1,53 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MaxInventory.Core.Models
{
/// <summary>
/// Represents a Subnet record in the inventory.
/// Tracks network subnets with prefix, CIDR bits, VLAN, and color coding.
/// NOTE: May have UI/API pissmatch, UI has 'Status' for protocol, but snippit provided says 'protocol'
/// </summary>
public sealed class SubnetRecord : IInventoryEntity
{
[JsonPropertyName("id")]
public int Id { get; set; }
///may need to be changed to status
[JsonPropertyName("protocol")]
public string Protocol { get; set; } = "";
[JsonPropertyName("prefix")]
public string Prefix { get; set; } = "";
[JsonPropertyName("bits")]
public int? Bits { get; set; }
[JsonPropertyName("mask")]
public string Mask { get; set; } = "";
[JsonPropertyName("trust_zone")]
public string TrustZone { get; set; } = "";
[JsonPropertyName("data_center_zone")]
public string DataCenterZone { get; set; } = "";
[JsonPropertyName("vlan")]
public int? Vlan { get; set; }
[JsonPropertyName("customer_zone")]
public string CustomerZone { get; set; } = "";
[JsonPropertyName("application_zone")]
public string ApplicationZone { get; set; } = "";
[JsonPropertyName("color")]
public string Color { get; set; } = "";
[JsonPropertyName("notes")]
public string Notes { get; set; } = "";
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
}
}
@@ -0,0 +1,69 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MaxInventory.Core.Models
{
/// <summary>
/// Represents a System record in the inventory.
/// Systems are physical or logical servers with OS, environment, and function classifications.
/// </summary>
public sealed class SystemRecord : IInventoryEntity
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("status")]
public string Status { get; set; } = "";
[JsonPropertyName("env")]
public string Env { get; set; } = "";
[JsonPropertyName("os")]
public string Os { get; set; } = "";
[JsonPropertyName("uniq")]
public int Uniq { get; set; }
[JsonPropertyName("function")]
public string Function { get; set; } = "";
[JsonPropertyName("description")]
public string Description { get; set; } = "";
[JsonPropertyName("owner")]
public string Owner { get; set; } = "";
[JsonPropertyName("short_name")]
public string ShortName { get; set; } = "";
[JsonPropertyName("long_name")]
public string LongName { get; set; } = "";
[JsonPropertyName("old_name")]
public string OldName { get; set; } = "";
[JsonPropertyName("host_name")]
public string HostName { get; set; } = "";
[JsonPropertyName("vm_console_vnc")]
public string VmConsoleVnc { get; set; } = "";
[JsonPropertyName("os_version")]
public string OsVersion { get; set; } = "";
[JsonPropertyName("admin")]
public string Admin { get; set; } = "";
[JsonPropertyName("kickstart_type")]
public string KickstartType { get; set; } = "";
[JsonPropertyName("zone")]
public string Zone { get; set; } = "";
[JsonPropertyName("notes")]
public string Notes { get; set; } = "";
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
}
}
+65
View File
@@ -0,0 +1,65 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MaxInventory.Core.Models
{
public sealed class VmRecord : IInventoryEntity
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("status")]
public string Status { get; set; } = "";
[JsonPropertyName("env")]
public string Env { get; set; } = "";
[JsonPropertyName("os")]
public string Os { get; set; } = "";
[JsonPropertyName("uniq")]
public int Uniq { get; set; }
[JsonPropertyName("function")]
public string Function { get; set; } = "";
[JsonPropertyName("description")]
public string Description { get; set; } = "";
[JsonPropertyName("owner")]
public string Owner { get; set; } = "";
[JsonPropertyName("short_name")]
public string ShortName { get; set; } = "";
[JsonPropertyName("long_name")]
public string LongName { get; set; } = "";
[JsonPropertyName("old_name")]
public string OldName { get; set; } = "";
[JsonPropertyName("host_name")]
public string HostName { get; set; } = "";
[JsonPropertyName("vm_console_vnc")]
public string VmConsoleVnc { get; set; } = "";
[JsonPropertyName("os_version")]
public string OsVersion { get; set; } = "";
[JsonPropertyName("admin")]
public string Admin { get; set; } = "";
[JsonPropertyName("kickstart_type")]
public string KickstartType { get; set; } = "";
[JsonPropertyName("zone")]
public string Zone { get; set; } = "";
[JsonPropertyName("notes")]
public string Notes { get; set; } = "";
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
}
}
@@ -0,0 +1,132 @@
using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
using MaxInventory.Core.Models;
namespace MaxInventory.Core.Registry
{
/// <summary>
/// Master registry mapping each ContentTypeName to its complete definition.
/// To add a new content type: add enum value, create model, register fields, then add entry here.
/// The NavMenu and ContentTypePage read from this registry to auto-generate UI.
/// </summary>
public sealed class ContentTypeRegistry : IContentTypeRegistry
{
private readonly Dictionary<ContentTypeName, ContentTypeDefinition> _definitions = new();
private readonly Dictionary<string, ContentTypeDefinition> _slugIndex = new(StringComparer.OrdinalIgnoreCase);
private readonly IFieldDefinitionRegistry _fieldRegistry;
public ContentTypeRegistry(IFieldDefinitionRegistry fieldRegistry)
{
_fieldRegistry = fieldRegistry;
RegisterAll();
}
private void RegisterAll()
{
Register(new ContentTypeDefinition
{
ContentType = ContentTypeName.Systems,
DisplayName = "Systems",
ApiEndpoint = "systems",
UrlSlug = "systems",
ModelType = typeof(SystemRecord),
Fields = _fieldRegistry.GetFieldsForContentType(ContentTypeName.Systems),
DisplayPropertyName = "ShortName",
IconCssClass = "bi-server",
});
Register(new ContentTypeDefinition
{
ContentType = ContentTypeName.Devices,
DisplayName = "Devices",
ApiEndpoint = "devices",
UrlSlug = "devices",
ModelType = typeof(DeviceRecord),
Fields = _fieldRegistry.GetFieldsForContentType(ContentTypeName.Devices),
DisplayPropertyName = "Name",
IconCssClass = "bi-hdd",
});
Register(new ContentTypeDefinition
{
ContentType = ContentTypeName.Ips,
DisplayName = "IPs",
ApiEndpoint = "ips",
UrlSlug = "ips",
ModelType = typeof(IpRecord),
Fields = _fieldRegistry.GetFieldsForContentType(ContentTypeName.Ips),
DisplayPropertyName = "Ip",
IconCssClass = "bi-globe",
});
Register(new ContentTypeDefinition
{
ContentType = ContentTypeName.Subnets,
DisplayName = "Subnets",
ApiEndpoint = "subnets",
UrlSlug = "subnets",
ModelType = typeof(SubnetRecord),
Fields = _fieldRegistry.GetFieldsForContentType(ContentTypeName.Subnets),
DisplayPropertyName = "Prefix",
IconCssClass = "bi-diagram-3",
});
Register(new ContentTypeDefinition
{
ContentType = ContentTypeName.Vms,
DisplayName = "VMs",
ApiEndpoint = "systems",
UrlSlug = "vms",
ModelType = typeof(VmRecord),
Fields = _fieldRegistry.GetFieldsForContentType(ContentTypeName.Vms),
DisplayPropertyName = "ShortName",
IconCssClass = "bi-pc-display",
});
Register(new ContentTypeDefinition
{
ContentType = ContentTypeName.CustomerZones,
DisplayName = "Customer Zones",
ApiEndpoint = "customer_zones",
UrlSlug = "customer-zones",
ModelType = typeof(CustomerZoneRecord),
Fields = _fieldRegistry.GetFieldsForContentType(ContentTypeName.CustomerZones),
DisplayPropertyName = "Name",
IconCssClass = "bi-people",
});
Register(new ContentTypeDefinition
{
ContentType = ContentTypeName.ApplicationZones,
DisplayName = "Application Zones",
ApiEndpoint = "application_zones",
UrlSlug = "application-zones",
ModelType = typeof(ApplicationZoneRecord),
Fields = _fieldRegistry.GetFieldsForContentType(ContentTypeName.ApplicationZones),
DisplayPropertyName = "Name",
IconCssClass = "bi-app-indicator",
});
}
private void Register(ContentTypeDefinition definition)
{
_definitions[definition.ContentType] = definition;
_slugIndex[definition.UrlSlug] = definition;
}
///<inheritdoc/>
public ContentTypeDefinition GetDefinition(ContentTypeName contentType)
{
if (_definitions.TryGetValue(contentType, out var definition))
return definition;
throw new KeyNotFoundException($"No definition registered for content tyoe '{contentType}'.");
}
/// <inheritdoc/>
public IReadOnlyList<ContentTypeDefinition> GetAllDefinitions()
{
return _definitions.Values.ToList().AsReadOnly();
}
///<inheritdoc/>
public ContentTypeDefinition? GetByUrlSlug(string slug)
{
_slugIndex.TryGetValue(slug, out var definition);
return definition;
}
}
}
@@ -0,0 +1,326 @@
namespace MaxInventory.Core.Registry;
using MaxInventory.Core.Configuration;
/// <summary>
/// Central registry of all dropdown option sets.
/// To add or modify dropdown options for any field, edit this single file.
/// Each option includes a value, display label, and tooltip description.
/// </summary>
public sealed class DropdownOptionRegistry : IDropdownOptionRegistry
{
private readonly Dictionary<string, DropdownOptionSet> _optionSets = new(StringComparer.OrdinalIgnoreCase);
public DropdownOptionRegistry()
{
RegisterAll();
}
private void RegisterAll()
{
// ── System Status ──────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "SystemStatus",
Options = new List<DropdownOption>
{
new() { Value = "Active", DisplayLabel = "Active", Description = "System is operational and in use" },
new() { Value = "Disabled", DisplayLabel = "Disabled", Description = "System is temporarily disabled" },
new() { Value = "Reserved", DisplayLabel = "Reserved", Description = "System is reserved for future use" },
new() { Value = "Retired", DisplayLabel = "Retired", Description = "System has been decommissioned" },
}
});
// ── Device Status ──────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "DeviceStatus",
Options = new List<DropdownOption>
{
new() { Value = "Active", DisplayLabel = "Active", Description = "Device is operational" },
new() { Value = "Reserved", DisplayLabel = "Reserved", Description = "Device is reserved for future use" },
new() { Value = "Retired", DisplayLabel = "Retired", Description = "Device has been decommissioned" },
new() { Value = "Scrapped", DisplayLabel = "Scrapped", Description = "Device has been destroyed or scrapped" },
}
});
// ── VM Status ──────────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "VmStatus",
Options = new List<DropdownOption>
{
new() { Value = "Active", DisplayLabel = "Active", Description = "VM is operational and in use" },
new() { Value = "Disabled", DisplayLabel = "Disabled", Description = "VM is temporarily disabled" },
new() { Value = "Reserved", DisplayLabel = "Reserved", Description = "VM is reserved for future use" },
new() { Value = "Retired", DisplayLabel = "Retired", Description = "VM has been decommissioned" },
}
});
// ── Environment ────────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "Environment",
Options = new List<DropdownOption>
{
new() { Value = "S", DisplayLabel = "S", Description = "Staging" },
new() { Value = "D", DisplayLabel = "D", Description = "Development" },
new() { Value = "T", DisplayLabel = "T", Description = "Test" },
new() { Value = "G", DisplayLabel = "G", Description = "Government" },
new() { Value = "P", DisplayLabel = "P", Description = "Production" },
new() { Value = "M", DisplayLabel = "M", Description = "Management" },
new() { Value = "C", DisplayLabel = "C", Description = "Continuity" },
new() { Value = "N", DisplayLabel = "N", Description = "None / Not Applicable" },
}
});
// ── Operating System ───────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "OperatingSystem",
Options = new List<DropdownOption>
{
new() { Value = "A", DisplayLabel = "A", Description = "AIX" },
new() { Value = "L", DisplayLabel = "L", Description = "Linux" },
new() { Value = "W", DisplayLabel = "W", Description = "Windows" },
new() { Value = "N", DisplayLabel = "N", Description = "Network (Cisco / Fortinet)" },
new() { Value = "H", DisplayLabel = "H", Description = "Other (PURE / BSD / APC / misc)" },
}
});
// ── System Function ────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "SystemFunction",
Options = new List<DropdownOption>
{
new() { Value = "NET", DisplayLabel = "NET", Description = "Network" },
new() { Value = "APP", DisplayLabel = "APP", Description = "Application" },
new() { Value = "CON", DisplayLabel = "CON", Description = "Console" },
new() { Value = "LMP", DisplayLabel = "LMP", Description = "Lamp" },
new() { Value = "DBS", DisplayLabel = "DBS", Description = "Database" },
new() { Value = "HYP", DisplayLabel = "HYP", Description = "Hypervisor" },
new() { Value = "SYS", DisplayLabel = "SYS", Description = "System" },
new() { Value = "STI", DisplayLabel = "STI", Description = "Storage" },
new() { Value = "SEC", DisplayLabel = "SEC", Description = "Security" },
new() { Value = "HRD", DisplayLabel = "HRD", Description = "Hardware" },
}
});
// ── VM Function ────────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "VmFunction",
Options = new List<DropdownOption>
{
new() { Value = "APP", DisplayLabel = "APP", Description = "Application" },
new() { Value = "CON", DisplayLabel = "CON", Description = "Console" },
new() { Value = "LMP", DisplayLabel = "LMP", Description = "Lamp" },
new() { Value = "DBS", DisplayLabel = "DBS", Description = "Database" },
new() { Value = "HYP", DisplayLabel = "HYP", Description = "Hypervisor" },
new() { Value = "SYS", DisplayLabel = "SYS", Description = "System" },
new() { Value = "STI", DisplayLabel = "STI", Description = "Storage" },
new() { Value = "NET", DisplayLabel = "NET", Description = "Network" },
new() { Value = "SEC", DisplayLabel = "SEC", Description = "Security" },
new() { Value = "HRD", DisplayLabel = "HRD", Description = "Hardware" },
}
});
// ── Data Center ────────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "DataCenter",
Options = new List<DropdownOption>
{
new() { Value = "Mohawk", DisplayLabel = "Mohawk", Description = "Mohawk Data Center" },
new() { Value = "Dakota", DisplayLabel = "Dakota", Description = "Dakota Data Center" },
new() { Value = "NEOB", DisplayLabel = "NEOB", Description = "NEOB Data Center" },
new() { Value = "COOP", DisplayLabel = "COOP", Description = "COOP Data Center" },
}
});
// ── IP Protocol ────────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "IpProtocol",
Options = new List<DropdownOption>
{
new() { Value = "IPv4", DisplayLabel = "IPv4", Description = "Internet Protocol version 4" },
new() { Value = "IPv6", DisplayLabel = "IPv6", Description = "Internet Protocol version 6" },
}
});
// ── Subnet Protocol ────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "SubnetProtocol",
Options = new List<DropdownOption>
{
new() { Value = "IPv4", DisplayLabel = "IPv4", Description = "Internet Protocol version 4" },
new() { Value = "IPv6", DisplayLabel = "IPv6", Description = "Internet Protocol version 6" },
}
});
// ── IP Purpose ─────────────────────────────────────────────────
Register(new DropdownOptionSet
{
Name = "IpPurpose",
Options = new List<DropdownOption>
{
new() { Value = "Management", DisplayLabel = "Management", Description = "Management network traffic" },
new() { Value = "Application", DisplayLabel = "Application", Description = "Application network traffic" },
new() { Value = "OOB", DisplayLabel = "OOB", Description = "Out-of-Band management" },
new() { Value = "Other", DisplayLabel = "Other", Description = "Other / unclassified purpose" },
}
});
Register(new DropdownOptionSet
{
Name = "TrustZone",
Options = new List<DropdownOption>
{
new() { Value = "00: MAX", DisplayLabel = "00: MAX", Description = "MAX trust zone" },
new() { Value = "10: Hosted Partners", DisplayLabel = "10: Hosted Partners", Description = "Hosted partners trust zone" },
new() { Value = "12: Managed Partners", DisplayLabel = "12: Managed Partners", Description = "Managed partners trust zone" },
new() { Value = "14: Trusted Partners DB", DisplayLabel = "14: Trusted Partners DB", Description = "Trusted partners database zone" },
new() { Value = "15: Trusted Partners API", DisplayLabel = "15: Trusted Partners API", Description = "Trusted partners API zone" },
new() { Value = "55: DMZ", DisplayLabel = "55: DMZ", Description = "Demilitarized zone" },
new() { Value = "7f: Untrusted", DisplayLabel = "7f: Untrusted", Description = "Untrusted zone" },
new() { Value = "80: NP MAX", DisplayLabel = "80: NP MAX", Description = "NP MAX trust zone" },
new() { Value = "90: NP Hosted Partners", DisplayLabel = "90: NP Hosted Partners", Description = "NP hosted partners zone" },
new() { Value = "92: NP Managed Partners", DisplayLabel = "92: NP Managed Partners", Description = "NP managed partners zone" },
new() { Value = "aa: MOD", DisplayLabel = "aa: MOD", Description = "MOD trust zone" },
new() { Value = "ab: MOD DMZ", DisplayLabel = "ab: MOD DMZ", Description = "MOD DMZ trust zone" },
new() { Value = "ac: MOD Citrix VDAs", DisplayLabel = "ac: MOD Citrix VDAs", Description = "MOD Citrix VDA zone" },
new() { Value = "bb: NP MOD", DisplayLabel = "bb: NP MOD", Description = "NP MOD trust zone" },
new() { Value = "cc: MOD NAT", DisplayLabel = "cc: MOD NAT", Description = "MOD NAT zone" },
}
});
Register(new DropdownOptionSet
{
Name = "DataCenterZone",
Options = new List<DropdownOption>
{
new() { Value = "00: Prod Mohawk", DisplayLabel = "00: Prod Mohawk", Description = "Production Mohawk zone" },
new() { Value = "01: Prod COOP", DisplayLabel = "01: Prod COOP", Description = "Production COOP zone" },
new() { Value = "02: Prod NEOB", DisplayLabel = "02: Prod NEOB", Description = "Production NEOB zone" },
new() { Value = "50: Test NEOB", DisplayLabel = "50: Test NEOB", Description = "Test NEOB zone" },
new() { Value = "51: Test Mohawk", DisplayLabel = "51: Test Mohawk", Description = "Test Mohawk zone" },
new() { Value = "52: Test COOP", DisplayLabel = "52: Test COOP", Description = "Test COOP zone" },
new() { Value = "70: Devl NEOB", DisplayLabel = "70: Devl NEOB", Description = "Development NEOB zone" },
new() { Value = "71: Devl Mohawk", DisplayLabel = "71: Devl Mohawk", Description = "Development Mohawk zone" },
new() { Value = "72: Devl COOP", DisplayLabel = "72: Devl COOP", Description = "Development COOP zone" },
new() { Value = "f0: AT&T Tunnels", DisplayLabel = "f0: AT&T Tunnels", Description = "AT&T tunnels zone" },
new() { Value = "f1: WHCA Tunnels", DisplayLabel = "f1: WHCA Tunnels", Description = "WHCA tunnels zone" },
new() { Value = "f2: Internet Tunnels", DisplayLabel = "f2: Internet Tunnels", Description = "Internet tunnels zone" },
new() { Value = "ff: Floating", DisplayLabel = "ff: Floating", Description = "Floating zone" },
}
});
Register(new DropdownOptionSet
{
Name = "CustomerZone",
Options = new List<DropdownOption>
{
new() { Value = "0000: Internal Infrastructure", DisplayLabel = "0000: Internal Infrastructure", Description = "Internal infrastructure customer zone" },
new() { Value = "0001: Shared Services", DisplayLabel = "0001: Shared Services", Description = "Shared services customer zone" },
new() { Value = "0002: OFCIO", DisplayLabel = "0002: OFCIO", Description = "OFCIO customer zone" },
new() { Value = "0003: USTR", DisplayLabel = "0003: USTR", Description = "USTR customer zone" },
new() { Value = "0004: USTDA", DisplayLabel = "0004: USTDA", Description = "USTDA customer zone" },
new() { Value = "0005: Budget Systems", DisplayLabel = "0005: Budget Systems", Description = "Budget systems customer zone" },
new() { Value = "0006: BUMED", DisplayLabel = "0006: BUMED", Description = "BUMED customer zone" },
new() { Value = "0007: SEPS", DisplayLabel = "0007: SEPS", Description = "SEPS customer zone" },
new() { Value = "0008: DHA-RPSS", DisplayLabel = "0008: DHA-RPSS", Description = "DHA-RPSS customer zone" },
new() { Value = "0009: DOE", DisplayLabel = "0009: DOE", Description = "DOE customer zone" },
new() { Value = "0010: HUD", DisplayLabel = "0010: HUD", Description = "HUD customer zone" },
new() { Value = "0011: DHA-HAIMS", DisplayLabel = "0011: DHA-HAIMS", Description = "DHA-HAIMS customer zone" },
new() { Value = "0012: DHA-MILSTD", DisplayLabel = "0012: DHA-MILSTD", Description = "DHA-MILSTD customer zone" },
new() { Value = "0013: ONDCP", DisplayLabel = "0013: ONDCP", Description = "ONDCP customer zone" },
new() { Value = "0014: DHA", DisplayLabel = "0014: DHA", Description = "DHA customer zone" },
new() { Value = "0015: GSA", DisplayLabel = "0015: GSA", Description = "GSA customer zone" },
new() { Value = "0016: BFELoB", DisplayLabel = "0016: BFELoB", Description = "BFELoB customer zone" },
new() { Value = "0017: FPI", DisplayLabel = "0017: FPI", Description = "FPI customer zone" },
new() { Value = "0018: OGE", DisplayLabel = "0018: OGE", Description = "OGE customer zone" },
new() { Value = "0019: DCGS-A", DisplayLabel = "0019: DCGS-A", Description = "DCGS-A customer zone" },
new() { Value = "0020: VA CMS", DisplayLabel = "0020: VA CMS", Description = "VA CMS customer zone" },
new() { Value = "1000: MOD", DisplayLabel = "1000: MOD", Description = "MOD customer zone" },
new() { Value = "ffff: Blended", DisplayLabel = "ffff: Blended", Description = "Blended customer zone" },
}
});
Register(new DropdownOptionSet
{
Name = "ApplicationZone",
Options = new List<DropdownOption>
{
new() { Value = "0000: Internal Infrastructure", DisplayLabel = "0000: Internal Infrastructure", Description = "Internal infrastructure application zone" },
new() { Value = "0001: Community", DisplayLabel = "0001: Community", Description = "Community application zone" },
new() { Value = "0002: Collect", DisplayLabel = "0002: Collect", Description = "Collect application zone" },
new() { Value = "0003: Analytics", DisplayLabel = "0003: Analytics", Description = "Analytics application zone" },
new() { Value = "0004: Internal Security", DisplayLabel = "0004: Internal Security", Description = "Internal security application zone" },
new() { Value = "0005: JaaS", DisplayLabel = "0005: JaaS", Description = "JaaS application zone" },
new() { Value = "0006: PAAS", DisplayLabel = "0006: PAAS", Description = "PAAS application zone" },
new() { Value = "0007: Citrix", DisplayLabel = "0007: Citrix", Description = "Citrix application zone" },
new() { Value = "0008: PHP", DisplayLabel = "0008: PHP", Description = "PHP application zone" },
new() { Value = "0009: Budget", DisplayLabel = "0009: Budget", Description = "Budget application zone" },
new() { Value = "000a: Deployment", DisplayLabel = "000a: Deployment", Description = "Deployment application zone" },
new() { Value = "0010: Internal Patching", DisplayLabel = "0010: Internal Patching", Description = "Internal patching application zone" },
new() { Value = "0011: Authentication", DisplayLabel = "0011: Authentication", Description = "Authentication application zone" },
new() { Value = "0012: Document Manipulation", DisplayLabel = "0012: Document Manipulation", Description = "Document manipulation application zone" },
new() { Value = "2001: Internal Management", DisplayLabel = "2001: Internal Management", Description = "Internal management application zone" },
new() { Value = "2002: Internal Services", DisplayLabel = "2002: Internal Services", Description = "Internal services application zone" },
new() { Value = "2010: Mohawk Syslog", DisplayLabel = "2010: Mohawk Syslog", Description = "Mohawk syslog application zone" },
new() { Value = "2011: COOP Syslog", DisplayLabel = "2011: COOP Syslog", Description = "COOP syslog application zone" },
new() { Value = "2012: NEOB Syslog", DisplayLabel = "2012: NEOB Syslog", Description = "NEOB syslog application zone" },
new() { Value = "4200: K8s", DisplayLabel = "4200: K8s", Description = "Kubernetes application zone" },
new() { Value = "4444: MOD Servers", DisplayLabel = "4444: MOD Servers", Description = "MOD servers application zone" },
new() { Value = "4445: MOD Desktops", DisplayLabel = "4445: MOD Desktops", Description = "MOD desktops application zone" },
new() { Value = "4800: Public Facing Sites", DisplayLabel = "4800: Public Facing Sites", Description = "Public-facing sites application zone" },
new() { Value = "5000: Database", DisplayLabel = "5000: Database", Description = "Database application zone" },
new() { Value = "6001: Warp Speed", DisplayLabel = "6001: Warp Speed", Description = "Warp Speed application zone" },
new() { Value = "a000: Development", DisplayLabel = "a000: Development", Description = "Development application zone" },
new() { Value = "b000: Internal Storage", DisplayLabel = "b000: Internal Storage", Description = "Internal storage application zone" },
new() { Value = "c000: VPN Clients", DisplayLabel = "c000: VPN Clients", Description = "VPN clients application zone" },
new() { Value = "f000: Custom", DisplayLabel = "f000: Custom", Description = "Custom application zone" },
new() { Value = "f010: Desktop Sharing", DisplayLabel = "f010: Desktop Sharing", Description = "Desktop sharing application zone" },
new() { Value = "ffff: IaaS", DisplayLabel = "ffff: IaaS", Description = "IaaS application zone" },
}
});
}
private void Register(DropdownOptionSet optionSet)
{
_optionSets[optionSet.Name] = optionSet;
}
/// <inheritdoc />
public IReadOnlyList<DropdownOption> GetOptions(string optionSetName)
{
if (_optionSets.TryGetValue(optionSetName, out var set))
return set.Options;
throw new KeyNotFoundException($"Dropdown option set '{optionSetName}' is not registered.");
}
/// <inheritdoc />
public DropdownOptionSet GetOptionSet(string optionSetName)
{
if (_optionSets.TryGetValue(optionSetName, out var set))
return set;
throw new KeyNotFoundException($"Dropdown option set '{optionSetName}' is not registered.");
}
/// <inheritdoc />
public IReadOnlyList<string> GetOptionSetNames()
{
return _optionSets.Keys.ToList().AsReadOnly();
}
/// <inheritdoc />
public bool HasOptionSet(string optionSetName)
{
return _optionSets.ContainsKey(optionSetName);
}
}
@@ -0,0 +1,184 @@
namespace MaxInventory.Core.Registry;
using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
/// <summary>
/// Registry of field definitions for all content types.
/// Each content type's fields are defined here with metadata for grid columns,
/// form inputs, validation, and sorting behavior.
/// To add fields for a new content type, add a new Register method and call it from the constructor.
/// </summary>
public sealed class FieldDefinitionRegistry : IFieldDefinitionRegistry
{
private readonly Dictionary<ContentTypeName, IReadOnlyList<FieldDefinition>> _registry = new();
public FieldDefinitionRegistry()
{
RegisterSystemFields();
RegisterDeviceFields();
RegisterIpFields();
RegisterSubnetFields();
RegisterVmFields();
RegisterCustomerZoneFields();
RegisterApplicationZoneFields();
}
/// <inheritdoc />
public IReadOnlyList<FieldDefinition> GetFieldsForContentType(ContentTypeName contentType)
{
if (_registry.TryGetValue(contentType, out var fields))
return fields;
throw new KeyNotFoundException($"No field definitions registered for content type '{contentType}'.");
}
/// <inheritdoc />
public FieldDefinition? GetField(ContentTypeName contentType, string propertyName)
{
if (_registry.TryGetValue(contentType, out var fields))
return fields.FirstOrDefault(f => f.PropertyName == propertyName);
return null;
}
// ── Systems ────────────────────────────────────────────────────────
private void RegisterSystemFields()
{
var fields = new List<FieldDefinition>
{
new() { PropertyName = "Id", JsonPropertyName = "id", DisplayName = "ID", InputType = InputType.Integer, IsId = true, IsEditable = false, SortOrder = 0 },
new() { PropertyName = "Status", JsonPropertyName = "status", DisplayName = "Status", InputType = InputType.Dropdown, DropdownOptionSetName = "SystemStatus", IsRequired = true, SortOrder = 1 },
new() { PropertyName = "Env", JsonPropertyName = "env", DisplayName = "Env", InputType = InputType.Dropdown, DropdownOptionSetName = "Environment", SortOrder = 2 },
new() { PropertyName = "Os", JsonPropertyName = "os", DisplayName = "OS", InputType = InputType.Dropdown, DropdownOptionSetName = "OperatingSystem", SortOrder = 3 },
new() { PropertyName = "Uniq", JsonPropertyName = "uniq", DisplayName = "ID", InputType = InputType.Integer, SortOrder = 4 },
new() { PropertyName = "Function", JsonPropertyName = "function", DisplayName = "Function", InputType = InputType.Dropdown, DropdownOptionSetName = "SystemFunction", SortOrder = 5 },
new() { PropertyName = "Description", JsonPropertyName = "description", DisplayName = "Description", InputType = InputType.Text, SortOrder = 6 },
new() { PropertyName = "Owner", JsonPropertyName = "owner", DisplayName = "Owner", InputType = InputType.Text, SortOrder = 7 },
new() { PropertyName = "ShortName", JsonPropertyName = "short_name", DisplayName = "Short Name", InputType = InputType.Text, IsRequired = true, SortOrder = 8 },
new() { PropertyName = "LongName", JsonPropertyName = "long_name", DisplayName = "Long Name", InputType = InputType.Text, SortOrder = 9 },
new() { PropertyName = "HostName", JsonPropertyName = "host_name", DisplayName = "Host", InputType = InputType.Text, SortOrder = 10 },
new() { PropertyName = "VmConsoleVnc",JsonPropertyName = "vm_console_vnc",DisplayName = "VNC", InputType = InputType.Integer, SortOrder = 11 },
new() { PropertyName = "OsVersion", JsonPropertyName = "os_version", DisplayName = "OS Version", InputType = InputType.Text, SortOrder = 12 },
new() { PropertyName = "Admin", JsonPropertyName = "admin", DisplayName = "Admin", InputType = InputType.Text, SortOrder = 13 },
new() { PropertyName = "KickstartType", JsonPropertyName = "kickstart_type", DisplayName = "Kickstart", InputType = InputType.Text, SortOrder = 14 },
new() { PropertyName = "Zone", JsonPropertyName = "zone", DisplayName = "Security Boundary", InputType = InputType.Text, SortOrder = 15 },
new() { PropertyName = "Notes", JsonPropertyName = "notes", DisplayName = "Notes", InputType = InputType.TextArea, SortOrder = 16 },
};
_registry[ContentTypeName.Systems] = fields.AsReadOnly();
}
// ── Devices ────────────────────────────────────────────────────────
private void RegisterDeviceFields()
{
var fields = new List<FieldDefinition>
{
new() { PropertyName = "Id", JsonPropertyName = "id", DisplayName = "ID", InputType = InputType.Integer, IsId = true, IsEditable = false, SortOrder = 0 },
new() { PropertyName = "Status", JsonPropertyName = "status", DisplayName = "Status", InputType = InputType.Dropdown, DropdownOptionSetName = "DeviceStatus", IsRequired = true, SortOrder = 1 },
new() { PropertyName = "Name", JsonPropertyName = "name", DisplayName = "Name", InputType = InputType.Text, IsRequired = true, SortOrder = 2 },
new() { PropertyName = "BarCode", JsonPropertyName = "bar_code", DisplayName = "Bar Code", InputType = InputType.Text, SortOrder = 3 },
new() { PropertyName = "Model", JsonPropertyName = "model", DisplayName = "Model", InputType = InputType.Text, SortOrder = 4 },
new() { PropertyName = "SerialNumber", JsonPropertyName = "serial_number", DisplayName = "Serial Number", InputType = InputType.Text, SortOrder = 5 },
new() { PropertyName = "Firmware", JsonPropertyName = "firmware", DisplayName = "Firmware", InputType = InputType.Text, SortOrder = 6 },
new() { PropertyName = "DataCenter", JsonPropertyName = "data_center", DisplayName = "Data Center", InputType = InputType.Dropdown, DropdownOptionSetName = "DataCenter", SortOrder = 7 },
new() { PropertyName = "Location", JsonPropertyName = "location", DisplayName = "Location", InputType = InputType.Text, SortOrder = 8 },
new() { PropertyName = "Admin", JsonPropertyName = "admin", DisplayName = "Admin", InputType = InputType.Text, SortOrder = 9 },
new() { PropertyName = "Notes", JsonPropertyName = "notes", DisplayName = "Notes", InputType = InputType.TextArea, SortOrder = 10 },
};
_registry[ContentTypeName.Devices] = fields.AsReadOnly();
}
// ── IPs ────────────────────────────────────────────────────────────
private void RegisterIpFields()
{
var fields = new List<FieldDefinition>
{
new() { PropertyName = "Id", JsonPropertyName = "id", DisplayName = "ID", InputType = InputType.Integer, IsId = true, IsEditable = false, SortOrder = 0 },
new() { PropertyName = "Protocol", JsonPropertyName = "protocol", DisplayName = "Proto", InputType = InputType.Dropdown, DropdownOptionSetName = "IpProtocol", IsRequired = true, SortOrder = 1 },
new() { PropertyName = "Ip", JsonPropertyName = "ip", DisplayName = "IP", InputType = InputType.Text, IsRequired = true, SortOrder = 2 },
new() { PropertyName = "MaskBits", JsonPropertyName = "mask_bits", DisplayName = "Mask bits", InputType = InputType.Text, IsEditable = false, SortOrder = 3 },
new() { PropertyName = "HostName", JsonPropertyName = "host_name", DisplayName = "Host", InputType = InputType.Text, SortOrder = 4 },
new() { PropertyName = "Purpose", JsonPropertyName = "purpose", DisplayName = "Purpose", InputType = InputType.Dropdown, DropdownOptionSetName = "IpPurpose", SortOrder = 5 },
new() { PropertyName = "TrustZone", JsonPropertyName = "trust_zone", DisplayName = "Trust Zone", InputType = InputType.Dropdown, DropdownOptionSetName = "TrustZone", SortOrder = 6 },
new() { PropertyName = "DataCenterZone", JsonPropertyName = "data_center_zone", DisplayName = "Data Center Zone", InputType = InputType.Dropdown, DropdownOptionSetName = "DataCenterZone", SortOrder = 7 },
new() { PropertyName = "Vlan", JsonPropertyName = "vlan", DisplayName = "VLAN", InputType = InputType.Text, SortOrder = 8 },
new() { PropertyName = "CustomerZone", JsonPropertyName = "customer_zone", DisplayName = "Customer Zone", InputType = InputType.Dropdown, DropdownOptionSetName = "CustomerZone", SortOrder = 9 },
new() { PropertyName = "ApplicationZone", JsonPropertyName = "application_zone", DisplayName = "Application Zone", InputType = InputType.Dropdown, DropdownOptionSetName = "ApplicationZone", SortOrder = 10 },
new() { PropertyName = "Notes", JsonPropertyName = "notes", DisplayName = "Notes", InputType = InputType.TextArea, SortOrder = 11 },
};
_registry[ContentTypeName.Ips] = fields.AsReadOnly();
}
// ── Subnets ────────────────────────────────────────────────────────
private void RegisterSubnetFields()
{
var fields = new List<FieldDefinition>
{
new() { PropertyName = "Id", JsonPropertyName = "id", DisplayName = "ID", InputType = InputType.Integer, IsId = true, IsEditable = false, SortOrder = 0 },
new() { PropertyName = "Protocol", JsonPropertyName = "protocol", DisplayName = "Proto", InputType = InputType.Dropdown, DropdownOptionSetName = "SubnetProtocol", IsRequired = true, SortOrder = 1 },
new() { PropertyName = "Prefix", JsonPropertyName = "prefix", DisplayName = "Prefix", InputType = InputType.Text, IsRequired = true, SortOrder = 2 },
new() { PropertyName = "Bits", JsonPropertyName = "bits", DisplayName = "Bits", InputType = InputType.Integer, SortOrder = 3 },
new() { PropertyName = "Mask", JsonPropertyName = "mask", DisplayName = "Mask", InputType = InputType.Text, IsEditable = false, SortOrder = 4 },
new() { PropertyName = "TrustZone", JsonPropertyName = "trust_zone", DisplayName = "Trust Zone", InputType = InputType.Dropdown, DropdownOptionSetName = "TrustZone", SortOrder = 5 },
new() { PropertyName = "DataCenterZone", JsonPropertyName = "data_center_zone", DisplayName = "Data Center Zone", InputType = InputType.Dropdown, DropdownOptionSetName = "DataCenterZone", SortOrder = 6 },
new() { PropertyName = "Vlan", JsonPropertyName = "vlan", DisplayName = "VLAN", InputType = InputType.Integer, SortOrder = 7 },
new() { PropertyName = "CustomerZone", JsonPropertyName = "customer_zone", DisplayName = "Customer Zone", InputType = InputType.Dropdown, DropdownOptionSetName = "CustomerZone", SortOrder = 8 },
new() { PropertyName = "ApplicationZone", JsonPropertyName = "application_zone", DisplayName = "Application Zone", InputType = InputType.Dropdown, DropdownOptionSetName = "ApplicationZone", SortOrder = 9 },
new() { PropertyName = "Color", JsonPropertyName = "color", DisplayName = "Color", InputType = InputType.Text, SortOrder = 10 },
new() { PropertyName = "Notes", JsonPropertyName = "notes", DisplayName = "Notes", InputType = InputType.TextArea, SortOrder = 11 },
};
_registry[ContentTypeName.Subnets] = fields.AsReadOnly();
}
// ── VMs ────────────────────────────────────────────────────────────
private void RegisterVmFields()
{
var fields = new List<FieldDefinition>
{
new() { PropertyName = "Id", JsonPropertyName = "id", DisplayName = "ID", InputType = InputType.Integer, IsId = true, IsEditable = false, SortOrder = 0 },
new() { PropertyName = "Status", JsonPropertyName = "status", DisplayName = "Status", InputType = InputType.Dropdown, DropdownOptionSetName = "VmStatus", IsRequired = true, SortOrder = 1 },
new() { PropertyName = "Env", JsonPropertyName = "env", DisplayName = "Env", InputType = InputType.Dropdown, DropdownOptionSetName = "Environment", SortOrder = 2 },
new() { PropertyName = "Os", JsonPropertyName = "os", DisplayName = "OS", InputType = InputType.Dropdown, DropdownOptionSetName = "OperatingSystem", SortOrder = 3 },
new() { PropertyName = "Uniq", JsonPropertyName = "uniq", DisplayName = "ID", InputType = InputType.Integer, SortOrder = 4 },
new() { PropertyName = "Function", JsonPropertyName = "function", DisplayName = "Function", InputType = InputType.Dropdown, DropdownOptionSetName = "VmFunction", SortOrder = 5 },
new() { PropertyName = "Description", JsonPropertyName = "description", DisplayName = "Description", InputType = InputType.Text, SortOrder = 6 },
new() { PropertyName = "Owner", JsonPropertyName = "owner", DisplayName = "Owner", InputType = InputType.Text, SortOrder = 7 },
new() { PropertyName = "ShortName", JsonPropertyName = "short_name", DisplayName = "Short Name", InputType = InputType.Text, IsRequired = true, SortOrder = 8 },
new() { PropertyName = "LongName", JsonPropertyName = "long_name", DisplayName = "Long Name", InputType = InputType.Text, SortOrder = 9 },
new() { PropertyName = "HostName", JsonPropertyName = "host_name", DisplayName = "Host", InputType = InputType.Text, SortOrder = 10 },
new() { PropertyName = "VmConsoleVnc",JsonPropertyName = "vm_console_vnc",DisplayName = "VNC", InputType = InputType.Integer, SortOrder = 11 },
new() { PropertyName = "OsVersion", JsonPropertyName = "os_version", DisplayName = "OS Version", InputType = InputType.Text, SortOrder = 12 },
new() { PropertyName = "Admin", JsonPropertyName = "admin", DisplayName = "Admin", InputType = InputType.Text, SortOrder = 13 },
new() { PropertyName = "KickstartType", JsonPropertyName = "kickstart_type", DisplayName = "Kickstart", InputType = InputType.Text, SortOrder = 14 },
new() { PropertyName = "Zone", JsonPropertyName = "zone", DisplayName = "Security Boundary", InputType = InputType.Text, SortOrder = 15 },
new() { PropertyName = "Notes", JsonPropertyName = "notes", DisplayName = "Notes", InputType = InputType.TextArea, SortOrder = 16 },
};
_registry[ContentTypeName.Vms] = fields.AsReadOnly();
}
// ── Customer Zones ─────────────────────────────────────────────────
private void RegisterCustomerZoneFields()
{
var fields = new List<FieldDefinition>
{
new() { PropertyName = "Id", JsonPropertyName = "id", DisplayName = "ID", InputType = InputType.Integer, IsId = true, IsEditable = false, SortOrder = 0 },
new() { PropertyName = "HexCode", JsonPropertyName = "hex_code", DisplayName = "Hex ID", InputType = InputType.Text, SortOrder = 1 },
new() { PropertyName = "Name", JsonPropertyName = "name", DisplayName = "Name", InputType = InputType.Text, IsRequired = true, SortOrder = 2 },
new() { PropertyName = "Notes", JsonPropertyName = "notes", DisplayName = "Notes", InputType = InputType.TextArea, SortOrder = 3 },
};
_registry[ContentTypeName.CustomerZones] = fields.AsReadOnly();
}
// ── Application Zones ──────────────────────────────────────────────
private void RegisterApplicationZoneFields()
{
var fields = new List<FieldDefinition>
{
new() { PropertyName = "Id", JsonPropertyName = "id", DisplayName = "ID", InputType = InputType.Integer, IsId = true, IsEditable = false, SortOrder = 0 },
new() { PropertyName = "HexCode", JsonPropertyName = "hex_code", DisplayName = "Hex ID", InputType = InputType.Text, SortOrder = 1 },
new() { PropertyName = "Name", JsonPropertyName = "name", DisplayName = "Name", InputType = InputType.Text, IsRequired = true, SortOrder = 2 },
new() { PropertyName = "Notes", JsonPropertyName = "notes", DisplayName = "Notes", InputType = InputType.TextArea, SortOrder = 3 },
};
_registry[ContentTypeName.ApplicationZones] = fields.AsReadOnly();
}
}
@@ -0,0 +1,27 @@
using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
namespace MaxInventory.Core.Registry
{
/// <summary>
/// Master registry mapping ContentTypeName enums to their complete definitions.
/// Used by the NavMenu, ContentTypePage, and CRUD operations.
/// </summary>
public interface IContentTypeRegistry
{
/// <summary>
/// Gets the definition for a specific content type.
/// </summary>
ContentTypeDefinition GetDefinition(ContentTypeName contentType);
/// <summary>
/// Gets all registered content type definitions.
/// </summary>
IReadOnlyList<ContentTypeDefinition> GetAllDefinitions();
/// <summary>
/// Tries to find a content type definition by its URL slug.
/// </summary>
ContentTypeDefinition? GetByUrlSlug(string slug);
}
}
@@ -0,0 +1,23 @@
using MaxInventory.Core.Configuration;
namespace MaxInventory.Core.Registry
{
/// <summary>
/// Central registry for all dropdown option sets used across the application.
/// Provides lookup of option sets by name for populating dropdowns and validating values.
/// </summary>
public interface IDropdownOptionRegistry
{
///<summary>Gets the list of options for a named option set.</summary>
IReadOnlyList<DropdownOption> GetOptions(string optionSetName);
///<summary>Gets the full option set by name.</summary>
DropdownOptionSet GetOptionSet(string optionSetName);
///<summary>Gets all registered option set names.</summary>
IReadOnlyList<string> GetOptionSetNames();
///<summary>Checks if an option set exists.</summary>
bool HasOptionSet(string optionSetName);
}
}
@@ -0,0 +1,18 @@
using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
namespace MaxInventory.Core.Registry
{
/// <summary>
/// Registry of field definitions for each content type.
/// Provides the metadata needed for dynamic grid and form generation.
/// </summary>
public interface IFieldDefinitionRegistry
{
///<summary>Gets all field definitions for a given content type, ordered by SortOrder.</summary>
IReadOnlyList<FieldDefinition> GetFieldsForContentType(ContentTypeName contentType);
///<summary>Gets a specific field definition by content type and property name.</summary>
FieldDefinition? GetField(ContentTypeName contentType, string propertyName);
}
}
@@ -0,0 +1,18 @@
using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
namespace MaxInventory.Core.Registry
{
/// <summary>
/// Registry of cross-entity relationship rules.
/// Used by the RelatedRecordsPanel to discover linked records.
/// </summary>
public interface IRelationshipRegistry
{
///<summary>Gets all relationship rules where the given content type is the source.</summary>
IReadOnlyList<RelationshipRule> GetRulesForContentType(ContentTypeName contentType);
///<summary>Gets all registered relationship rules.</summary>
IReadOnlyList<RelationshipRule> GetAllRules();
}
}
@@ -0,0 +1,217 @@
namespace MaxInventory.Core.Registry;
using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
/// <summary>
/// Registry of cross-entity relationship rules.
/// Defines how records from different content types are linked.
/// </summary>
public sealed class RelationshipRegistry : IRelationshipRegistry
{
private readonly List<RelationshipRule> _allRules = new();
private readonly Dictionary<ContentTypeName, List<RelationshipRule>> _rulesBySource = new();
public RelationshipRegistry()
{
RegisterAll();
}
private void RegisterAll()
{
// Relationships are based on polymorphic host references (host_id + host_type).
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Systems,
SourcePropertyName = "HostId",
TargetContentType = ContentTypeName.Systems,
TargetPropertyName = "Id",
DisplayLabel = "Host System",
SourceFilterPropertyName = "HostType",
SourceFilterValue = "System",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Systems,
SourcePropertyName = "HostId",
TargetContentType = ContentTypeName.Devices,
TargetPropertyName = "Id",
DisplayLabel = "Host Device",
SourceFilterPropertyName = "HostType",
SourceFilterValue = "Device",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Systems,
SourcePropertyName = "Id",
TargetContentType = ContentTypeName.Systems,
TargetPropertyName = "HostId",
DisplayLabel = "Hosted Systems",
TargetFilterPropertyName = "HostType",
TargetFilterValue = "System",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Systems,
SourcePropertyName = "Id",
TargetContentType = ContentTypeName.Vms,
TargetPropertyName = "HostId",
DisplayLabel = "Hosted VMs",
TargetFilterPropertyName = "HostType",
TargetFilterValue = "System",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Systems,
SourcePropertyName = "Id",
TargetContentType = ContentTypeName.Ips,
TargetPropertyName = "HostId",
DisplayLabel = "IP Addresses",
TargetFilterPropertyName = "HostType",
TargetFilterValue = "System",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Devices,
SourcePropertyName = "Id",
TargetContentType = ContentTypeName.Systems,
TargetPropertyName = "HostId",
DisplayLabel = "Hosted Systems",
TargetFilterPropertyName = "HostType",
TargetFilterValue = "Device",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Devices,
SourcePropertyName = "Id",
TargetContentType = ContentTypeName.Vms,
TargetPropertyName = "HostId",
DisplayLabel = "Hosted VMs",
TargetFilterPropertyName = "HostType",
TargetFilterValue = "Device",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Devices,
SourcePropertyName = "Id",
TargetContentType = ContentTypeName.Ips,
TargetPropertyName = "HostId",
DisplayLabel = "IP Addresses",
TargetFilterPropertyName = "HostType",
TargetFilterValue = "Device",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Vms,
SourcePropertyName = "HostId",
TargetContentType = ContentTypeName.Systems,
TargetPropertyName = "Id",
DisplayLabel = "Host System",
SourceFilterPropertyName = "HostType",
SourceFilterValue = "System",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Vms,
SourcePropertyName = "HostId",
TargetContentType = ContentTypeName.Devices,
TargetPropertyName = "Id",
DisplayLabel = "Host Device",
SourceFilterPropertyName = "HostType",
SourceFilterValue = "Device",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Ips,
SourcePropertyName = "HostId",
TargetContentType = ContentTypeName.Systems,
TargetPropertyName = "Id",
DisplayLabel = "System",
SourceFilterPropertyName = "HostType",
SourceFilterValue = "System",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Ips,
SourcePropertyName = "HostId",
TargetContentType = ContentTypeName.Devices,
TargetPropertyName = "Id",
DisplayLabel = "Device",
SourceFilterPropertyName = "HostType",
SourceFilterValue = "Device",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Ips,
SourcePropertyName = "CustomerZone",
TargetContentType = ContentTypeName.CustomerZones,
TargetPropertyName = "HexCode",
DisplayLabel = "Customer Zone",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Ips,
SourcePropertyName = "ApplicationZone",
TargetContentType = ContentTypeName.ApplicationZones,
TargetPropertyName = "HexCode",
DisplayLabel = "Application Zone",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Subnets,
SourcePropertyName = "CustomerZone",
TargetContentType = ContentTypeName.CustomerZones,
TargetPropertyName = "HexCode",
DisplayLabel = "Customer Zone",
});
Register(new RelationshipRule
{
SourceContentType = ContentTypeName.Subnets,
SourcePropertyName = "ApplicationZone",
TargetContentType = ContentTypeName.ApplicationZones,
TargetPropertyName = "HexCode",
DisplayLabel = "Application Zone",
});
}
private void Register(RelationshipRule rule)
{
_allRules.Add(rule);
if (!_rulesBySource.ContainsKey(rule.SourceContentType))
_rulesBySource[rule.SourceContentType] = new List<RelationshipRule>();
_rulesBySource[rule.SourceContentType].Add(rule);
}
/// <inheritdoc />
public IReadOnlyList<RelationshipRule> GetRulesForContentType(ContentTypeName contentType)
{
if (_rulesBySource.TryGetValue(contentType, out var rules))
return rules.AsReadOnly();
return Array.Empty<RelationshipRule>();
}
/// <inheritdoc />
public IReadOnlyList<RelationshipRule> GetAllRules()
{
return _allRules.AsReadOnly();
}
}
@@ -0,0 +1,43 @@
using System.Text.Json;
namespace MaxInventory.Core.Services
{
/// <summary>
/// Default implementation of IEntitySerializer using System.Text.Json.
/// Configured to respsect [JsonPropertyName] attribute on model classes.
/// </summary>
public sealed class EntitySerializer : IEntitySerializer
{
private readonly JsonSerializerOptions _options;
public EntitySerializer()
{
_options = new JsonSerializerOptions
{
//Do not apply naming policy
PropertyNamingPolicy = null,
//Allow case-insensitive matching
PropertyNameCaseInsensitive = true,
WriteIndented = false,
};
}
///<inheritdoc/>
public string Serialize<T>(T entity)
{
return JsonSerializer.Serialize(entity, _options);
}
///<inheritdoc/>
public T? Deserialize<T>(string json)
{
return JsonSerializer.Deserialize<T>(json, _options);
}
///<inheritdoc/>
public List<T> DeserializeList<T>(string json)
{
return JsonSerializer.Deserialize<List<T>>(json, _options) ?? new List<T>();
}
}
}
@@ -0,0 +1,302 @@
namespace MaxInventory.Core.Services;
using System.Net;
using System.Text;
using System.Text.Json;
using MaxInventory.Core.Models;
/// <summary>
/// Resolves values from inventory entities using both concrete model properties
/// and virtual/derived values that may arrive in JSON extension data.
/// </summary>
public static class EntityValueResolver
{
private static readonly string[] AssociationContainers = ["association_values", "associationValues", "associations"];
public static string GetValue(IInventoryEntity entity, string propertyName, string? jsonPropertyName = null)
{
var direct = GetPropertyValue(entity, propertyName);
if (!string.IsNullOrWhiteSpace(direct))
return direct;
var jsonKey = string.IsNullOrWhiteSpace(jsonPropertyName)
? ToSnakeCase(propertyName)
: jsonPropertyName;
if (TryGetDerivedValue(entity, propertyName, jsonKey, out var derived))
return derived;
var extensionData = entity.ExtensionData;
if (extensionData is null || extensionData.Count == 0)
return string.Empty;
foreach (var candidate in GetCandidates(propertyName, jsonKey))
{
if (TryGetElementValue(extensionData, candidate, out var value))
return value;
}
// Legacy API often exposes derived values under association_values.
foreach (var container in AssociationContainers)
{
if (!TryGetElement(extensionData, container, out var associations))
continue;
if (associations.ValueKind == JsonValueKind.String)
{
var raw = associations.GetString();
if (!string.IsNullOrWhiteSpace(raw))
{
try
{
using var doc = JsonDocument.Parse(raw);
associations = doc.RootElement.Clone();
}
catch (JsonException)
{
continue;
}
}
}
if (associations.ValueKind != JsonValueKind.Object)
continue;
foreach (var candidate in GetCandidates(propertyName, jsonKey))
{
if (TryGetNestedElementValue(associations, candidate, out var value))
return value;
}
}
return string.Empty;
}
private static bool TryGetDerivedValue(IInventoryEntity entity, string propertyName, string jsonKey, out string value)
{
value = string.Empty;
if (entity is IpRecord ipRecord && TryGetIpv6Segments(ipRecord.Ip, out var ipSegments))
return TryGetDerivedZoneValue(propertyName, jsonKey, ipSegments, out value);
if (entity is SubnetRecord subnetRecord)
{
if (string.Equals(propertyName, "MaskBits", StringComparison.OrdinalIgnoreCase) &&
subnetRecord.Bits is not null)
{
value = subnetRecord.Bits.Value.ToString();
return true;
}
if (TryGetIpv6Segments(subnetRecord.Prefix, out var subnetSegments))
return TryGetDerivedZoneValue(propertyName, jsonKey, subnetSegments, out value);
}
return false;
}
private static bool TryGetDerivedZoneValue(string propertyName, string jsonKey, IReadOnlyList<string> segments, out string value)
{
value = string.Empty;
if (segments.Count < 8)
return false;
var zoneSegment = segments[3];
if (string.Equals(propertyName, "TrustZone", StringComparison.OrdinalIgnoreCase) ||
string.Equals(jsonKey, "trust_zone", StringComparison.OrdinalIgnoreCase))
{
value = zoneSegment[..2];
return true;
}
if (string.Equals(propertyName, "DataCenterZone", StringComparison.OrdinalIgnoreCase) ||
string.Equals(jsonKey, "data_center_zone", StringComparison.OrdinalIgnoreCase))
{
value = zoneSegment[2..4];
return true;
}
if (string.Equals(propertyName, "Vlan", StringComparison.OrdinalIgnoreCase) ||
string.Equals(jsonKey, "vlan", StringComparison.OrdinalIgnoreCase))
{
value = Convert.ToInt32(segments[4], 16).ToString();
return true;
}
if (string.Equals(propertyName, "CustomerZone", StringComparison.OrdinalIgnoreCase) ||
string.Equals(jsonKey, "customer_zone", StringComparison.OrdinalIgnoreCase))
{
value = segments[5];
return true;
}
if (string.Equals(propertyName, "ApplicationZone", StringComparison.OrdinalIgnoreCase) ||
string.Equals(jsonKey, "application_zone", StringComparison.OrdinalIgnoreCase))
{
value = segments[6];
return true;
}
return false;
}
private static string GetPropertyValue(IInventoryEntity entity, string propertyName)
{
var prop = entity.GetType().GetProperty(propertyName);
return prop?.GetValue(entity)?.ToString() ?? string.Empty;
}
private static bool TryGetElementValue(
IReadOnlyDictionary<string, JsonElement> extensionData,
string key,
out string value)
{
value = string.Empty;
if (!TryGetElement(extensionData, key, out var element))
return false;
value = JsonElementToString(element);
return !string.IsNullOrWhiteSpace(value);
}
private static bool TryGetNestedElementValue(JsonElement parent, string key, out string value)
{
value = string.Empty;
if (parent.ValueKind != JsonValueKind.Object || !TryGetProperty(parent, key, out var element))
return false;
value = JsonElementToString(element);
return !string.IsNullOrWhiteSpace(value);
}
private static string JsonElementToString(JsonElement element)
{
return element.ValueKind switch
{
JsonValueKind.String => element.GetString() ?? string.Empty,
JsonValueKind.Number => element.ToString(),
JsonValueKind.True => bool.TrueString,
JsonValueKind.False => bool.FalseString,
JsonValueKind.Null => string.Empty,
_ => element.ToString(),
};
}
private static IEnumerable<string> GetCandidates(string propertyName, string jsonKey)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
void Add(string? key)
{
if (!string.IsNullOrWhiteSpace(key))
seen.Add(key);
}
Add(jsonKey);
Add(propertyName);
Add(ToSnakeCase(propertyName));
Add(propertyName.ToLowerInvariant());
if (string.Equals(jsonKey, "host_name", StringComparison.OrdinalIgnoreCase))
{
Add("host");
Add("hostname");
Add("host_id");
}
if (string.Equals(jsonKey, "data_center_zone", StringComparison.OrdinalIgnoreCase))
Add("datacenter_zone");
if (string.Equals(jsonKey, "mask_bits", StringComparison.OrdinalIgnoreCase))
Add("maskbits");
return seen;
}
private static bool TryGetElement(IReadOnlyDictionary<string, JsonElement> extensionData, string key, out JsonElement element)
{
if (extensionData.TryGetValue(key, out element))
return true;
foreach (var pair in extensionData)
{
if (string.Equals(pair.Key, key, StringComparison.OrdinalIgnoreCase))
{
element = pair.Value;
return true;
}
}
element = default;
return false;
}
private static bool TryGetProperty(JsonElement parent, string key, out JsonElement element)
{
if (parent.TryGetProperty(key, out element))
return true;
foreach (var property in parent.EnumerateObject())
{
if (string.Equals(property.Name, key, StringComparison.OrdinalIgnoreCase))
{
element = property.Value;
return true;
}
}
element = default;
return false;
}
private static bool TryGetIpv6Segments(string? input, out string[] segments)
{
segments = [];
if (string.IsNullOrWhiteSpace(input) || !IPAddress.TryParse(input, out var address))
return false;
if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
return false;
var bytes = address.GetAddressBytes();
segments = new string[8];
for (var i = 0; i < 8; i++)
{
var offset = i * 2;
segments[i] = $"{bytes[offset]:x2}{bytes[offset + 1]:x2}";
}
return true;
}
private static string ToSnakeCase(string value)
{
if (string.IsNullOrWhiteSpace(value))
return string.Empty;
var builder = new StringBuilder(value.Length + 8);
for (var i = 0; i < value.Length; i++)
{
var c = value[i];
if (char.IsUpper(c))
{
if (i > 0)
builder.Append('_');
builder.Append(char.ToLowerInvariant(c));
}
else
{
builder.Append(c);
}
}
return builder.ToString();
}
}
@@ -0,0 +1,16 @@
using System.Security.Cryptography.X509Certificates;
namespace MaxInventory.Core.Services
{
/// <summary>
/// Provides the x509 client certificate for API authentication.
/// Implementations can load from Windows cert store, PFX file, or other sources.
/// </summary>
public interface ICertificateProvider
{
///<summary>Retrieves the client certificate used for mutual TLS Authentication.</summary>
///<returns>The X509 certficiate</returns>
///<exception cref="InvalidOperationException">Thrown when the certficiate cannot be found or loaded.</exception>
X509Certificate2 GetClientCertificate();
}
}
@@ -0,0 +1,18 @@
namespace MaxInventory.Core.Services
{
/// <summary>
/// Handles JSON serialization and deserialization for inventory entities.
/// Wraps System.Text.Json with consistent configuration.
/// </summary>
public interface IEntitySerializer
{
/// <summary>Serializes an entity to a JSON string.</summary>
string Serialize<T>(T entity);
///<summary>Deserializes a JSON string to an entity.</summary>
T? Deserialize<T>(string json);
///<summary>Deserializes a JSON array string to a list of entities.</summary>
List<T> DeserializeList<T>(string json);
}
}
@@ -0,0 +1,47 @@
using MaxInventory.Core.Models;
namespace MaxInventory.Core.Services
{
/// <summary>
/// Provides CRUD operations against the inventory API for any entity type.
/// All operations use the generic IInventoryEntity constraint to work with any content type.
/// </summary>
public interface IInventoryApiClient
{
/// <summary>
/// Retrieves all records of the specified type from the given endpoint.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="ct"></param>
/// <returns></returns>
Task<List<T>> GetAllAsync<T>(string endpoint, CancellationToken ct = default) where T : class, IInventoryEntity;
/// <summary>
/// Creates new record at the given endpoint. Returns the server-assigned ID.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="entity"></param>
/// <param name="ct"></param>
/// <returns></returns>
Task<ApiCreateResponse> CreateAsync<T>(string endpoint, T entity, CancellationToken ct = default) where T : class, IInventoryEntity;
/// <summary>
/// Updates an existing record by ID at the given endpoint (HTTP PUT).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint"></param>
/// <param name="id"></param>
/// <param name="entity"></param>
/// <param name="ct"></param>
/// <returns></returns>
Task UpdateAsync<T>(string endpoint, int id, T entity, CancellationToken ct = default) where T : class, IInventoryEntity;
/// <summary>
/// Deletes a record by ID at the given endpoint.
/// </summary>
/// <param name="endpoint"></param>
/// <param name="id"></param>
/// <param name="ct"></param>
/// <returns></returns>
Task DeleteAsync(string endpoint, int id, CancellationToken ct = default);
}
}
@@ -0,0 +1,19 @@
namespace MaxInventory.Core.Settings
{
/// <summary>
/// Configuration settings for the inventory API connection.
/// Bound from the "Api" section of appsettings.json.
/// </summary>
public sealed class ApiSettings
{
/// <summary>
/// Base URL for the inventory API.
/// </summary>
public string BaseUrl { get; set; } = "https://directauth.max.gov/inventory";
/// <summary>
/// HTTP request timeout in seconds. Default is 30.
/// </summary>
public int TimeoutSeconds { get; set; } = 30;
}
}
@@ -0,0 +1,38 @@
namespace MaxInventory.Core.Settings
{
/// <summary>
/// Configuration settings for client certificate authentication.
/// Bound from the "Certificate" section of appsettings.json.
/// Supports two modes: Windows certificate store lookup (by friendly name)
/// or file-based PFX loading (for Docket/Linux environments).
/// </summary>
public sealed class CertificateSettings
{
/// <summary>
/// When true, loads certificate from a PFX file (FilePath + Password).
/// When false, searches the Windows machine certificate store by FriendlyName.
/// </summary>
public bool UseFile { get; set; } = false;
///<summary>Friendly name of the certificate in the Windows machine store.
///Used when UseFile is false.
/// </summary>
public string? FriendlyName { get; set; } = "alleman_j inventory.max.gov client";
///<summary>
///Certificate thumbprint in the windows machine store.
///Used as a fallback when UseFile is false and FriendlyName lookup does not find a certificate.
/// </summary>
public string? Thumbprint { get; set; }
/// <summary>
/// Path to the PFX certificate file. Used when UseFile is true.
/// </summary>
public string? FilePath { get; set; }
/// <summary>
/// Password for the PFC certificate file. Used when UseFile is true.
/// </summary>
public string? Password { get; set; }
}
}
@@ -0,0 +1,15 @@
namespace MaxInventory.Core.Settings
{
/// <summary>
/// Configuration settings for HTTP proxy.
/// Bound from the "Proxy" section of appsettings.json.
/// </summary>
public sealed class ProxySettings
{
///<summary>Whether to use a proxy for API requests.</summary>
public bool Enabled { get; set; } = true;
///<summary>Proxy URL</summary>
public string? Address { get; set; } = "http://proxy.omb.gov:8080";
}
}
@@ -0,0 +1,39 @@
using System.Security.Cryptography.X509Certificates;
using MaxInventory.Core.Services;
namespace MaxInventory.Infrastructure.Certificates
{
/// <summary>
/// Loads the client certificate from a PFX file on disk.
/// Used in Docker/Linux environments where the Windows cert store is unavailable.
/// The PFX file and password are configured via environment variables or appsettings.
/// </summary>
public sealed class FileCertificateProvider : ICertificateProvider
{
private readonly string _filePath;
private readonly string _password;
public FileCertificateProvider(string filePath, string password)
{
_filePath = filePath ?? throw new ArgumentNullException(nameof(filePath));
_password = password ?? throw new ArgumentNullException(nameof(password));
}
///<inheritdoc/>
public X509Certificate2 GetClientCertificate()
{
if (!File.Exists(_filePath))
{
throw new FileNotFoundException(
$"Certificate file not found at '{_filePath}'. Ensure the PFX file" +
$"is mounted or copied to the expected location.", _filePath);
}
return new X509Certificate2(
_filePath,
_password,
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
);
}
}
}
@@ -0,0 +1,72 @@
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using MaxInventory.Core.Services;
namespace MaxInventory.Infrastructure.Certificates
{
/// <summary>
/// Loads the client certificate from the Windows machine certificate store
/// by searching for a certificate with the configured friendly name
/// and falling back to the thumbprint when friendly name is not found.
/// Used in non-Docker deployments where the cert is in the Windows store.
/// </summary>
public sealed class WindowsCertificateProvider : ICertificateProvider
{
private readonly string? _friendlyName;
private readonly string? _thumbprint;
public WindowsCertificateProvider(string? friendlyName, string? thumbprint = null)
{
_friendlyName = friendlyName;
_thumbprint = thumbprint;
}
///<inheritdoc/>
public X509Certificate2 GetClientCertificate()
{
using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2? cert = null;
if (!string.IsNullOrWhiteSpace(_friendlyName))
{
cert = store.Certificates
.OfType<X509Certificate2>()
.FirstOrDefault(c => string.Equals(
c.FriendlyName, _friendlyName, StringComparison.OrdinalIgnoreCase));
}
if (cert is null && !string.IsNullOrEmpty(_thumbprint))
{
cert = store.Certificates
.OfType<X509Certificate2>()
.FirstOrDefault(c => string.Equals(
NormalizeThumbprint(c.Thumbprint), NormalizeThumbprint(_thumbprint), StringComparison.OrdinalIgnoreCase));
}
if (cert is null)
{
var hasFriendlyName = !string.IsNullOrWhiteSpace( _friendlyName );
var hasThumbprint = !string.IsNullOrWhiteSpace ( _thumbprint );
var criteria = hasFriendlyName && hasThumbprint
? $"friendly name '{_friendlyName}' or thumbprint '{_thumbprint}'"
: hasFriendlyName
? $"friendly name '{_friendlyName}'"
: $"thumbprint '{_thumbprint}'";
throw new InvalidOperationException(
$"Certificate with {criteria} not found in " +
$"LocalMachine/My store. Ensure the certificate is installed and the " +
$"application has permission to access the machine certificate store."
);
}
return cert;
}
private static string? NormalizeThumbprint(string? thumbprint)
=> thumbprint?.Replace(" ", string.Empty, StringComparison.OrdinalIgnoreCase);
}
}
@@ -0,0 +1,87 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MaxInventory.Core.Registry;
using MaxInventory.Core.Services;
using MaxInventory.Core.Settings;
using MaxInventory.Infrastructure.Certificates;
using MaxInventory.Infrastructure.Http;
using System.Runtime.CompilerServices;
namespace MaxInventory.Infrastructure.Extensions
{
/// <summary>
/// Extension methods for registering all inventory services with the DI container.
/// Call AddInventoryServices() in Program.cs to wire up everything.
/// </summary>
public static class ServiceCollectionExtensions
{
///<summary>
/// Registers all inventory services: settings, certificate provider, HTTP client,
/// API client, registeries, and serializer.
/// </summary>
public static IServiceCollection AddInventoryServices(
this IServiceCollection services,
IConfiguration configuration)
{
// Bind settings from configuration
var apiSettings = new ApiSettings();
configuration.GetSection("Api").Bind(apiSettings);
services.AddSingleton(apiSettings);
var certSettings = new CertificateSettings();
configuration.GetSection("Certificate").Bind(certSettings);
services.AddSingleton(certSettings);
var proxySettings = new ProxySettings();
configuration.GetSection("Proxy").Bind(proxySettings);
services.AddSingleton(proxySettings);
// Cert provider
if (certSettings.UseFile)
{
services.AddSingleton<ICertificateProvider>(
new FileCertificateProvider(
certSettings.FilePath ?? throw new InvalidOperationException(
"Certificate.FilePath must be set when Certificate.UseFile is true."),
certSettings.Password ?? throw new InvalidOperationException(
"Certificate.Password must be set when Certificate.UseFile is true."))
);
}
else
{
if (string.IsNullOrWhiteSpace(certSettings.FriendlyName) &&
string.IsNullOrWhiteSpace(certSettings.Thumbprint))
{
throw new InvalidOperationException(
"When Certificate.UseFile is false, set at least one of Certificate.FriendlyName or Certificate.Thumbprint.");
}
services.AddSingleton<ICertificateProvider>(
new WindowsCertificateProvider(
certSettings.FriendlyName,
certSettings.Thumbprint));
}
//Http Client
services.AddSingleton<HttpClient>(sp =>
{
var certProvider = sp.GetRequiredService<ICertificateProvider>();
return InventoryHttpClientFactory.Create(certProvider, apiSettings, proxySettings);
});
// API Client
services.AddSingleton<IInventoryApiClient, InventoryApiClient>();
// Serializer
services.AddSingleton<IEntitySerializer, EntitySerializer>();
// Registries
services.AddSingleton<IDropdownOptionRegistry, DropdownOptionRegistry>();
services.AddSingleton<IFieldDefinitionRegistry, FieldDefinitionRegistry>();
services.AddSingleton<IContentTypeRegistry, ContentTypeRegistry>();
services.AddSingleton<IRelationshipRegistry, RelationshipRegistry>();
return services;
}
}
}
@@ -0,0 +1,23 @@
namespace MaxInventory.Infrastructure.Http
{
/// <summary>
/// Constructs API endpoint URLS from base URL and endpoint segments.
/// Ensures consistent URL formatting.
/// </summary>
public static class ApiEndpointResolver
{
///<summary>
///Buildds the full endpoint path for a content type.
/// </summary>
public static string Resolve(string endpoint)
{
return endpoint.TrimStart('/');
}
///<summary>Builds the full endpoint path for a specific record by ID.</summary>
public static string ResolveWithId(string endpoint, int id)
{
return $"{endpoint.TrimStart('/')}/{id}";
}
}
}
@@ -0,0 +1,293 @@
namespace MaxInventory.Infrastructure.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using MaxInventory.Core.Models;
using MaxInventory.Core.Services;
/// <summary>
/// Implementation of IInventoryApiClient that communicates with the
/// inventory REST API using HttpClient with certificate authentication.
/// All CRUD operations go through this single class.
/// </summary>
public sealed class InventoryApiClient : IInventoryApiClient
{
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _jsonOptions;
public InventoryApiClient(HttpClient httpClient)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_jsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = null, // We use explicit [JsonPropertyName] attributes
            PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
WriteIndented = false,
};
_jsonOptions.Converters.Add(new FlexibleStringJsonConverter());
}
    /// <inheritdoc />
    public async Task<List<T>> GetAllAsync<T>(string endpoint, CancellationToken ct = default)
where T : class, IInventoryEntity
{
var endpointsToTry = GetFallbackEndpoints(endpoint);
HttpRequestException? lastNotFound = null;
for (var i = 0; i < endpointsToTry.Count; i++)
{
var candidate = endpointsToTry[i];
var url = ApiEndpointResolver.Resolve(candidate);
var response = await _httpClient.GetAsync(url, ct);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync(ct);
var parsed = JsonSerializer.Deserialize<List<T>>(json, _jsonOptions) ?? new List<T>();
                // Some inventory APIs return 200 with empty arrays for one alias
                // while another alias (usually singular/plural) contains the data.
                // If this candidate is empty and we still have fallbacks, try them.
                if (parsed.Count == 0 && i < endpointsToTry.Count - 1)
continue;
return parsed;
}
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
var body = await response.Content.ReadAsStringAsync(ct);
lastNotFound = new HttpRequestException(
$"Request to '{response.RequestMessage?.RequestUri}' failed with " +
$"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {TrimBody(body)}");
continue;
}
await EnsureSuccessStatusCodeWithDetailsAsync(response, ct);
}
throw lastNotFound ?? new HttpRequestException(
$"Request to endpoint '{endpoint}' failed after trying fallbacks: {string.Join(", ", endpointsToTry)}");
}
    /// <inheritdoc />
    public async Task<ApiCreateResponse> CreateAsync<T>(string endpoint, T entity, CancellationToken ct = default)
where T : class, IInventoryEntity
{
var url = ApiEndpointResolver.Resolve(endpoint);
var json = JsonSerializer.Serialize(entity, _jsonOptions);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(url, content, ct);
await EnsureSuccessStatusCodeWithDetailsAsync(response, ct);
var responseJson = await response.Content.ReadAsStringAsync(ct);
return JsonSerializer.Deserialize<ApiCreateResponse>(responseJson, _jsonOptions)
?? throw new InvalidOperationException("API returned null response on create.");
}
    /// <inheritdoc />
    public async Task UpdateAsync<T>(string endpoint, int id, T entity, CancellationToken ct = default)
where T : class, IInventoryEntity
{
var url = ApiEndpointResolver.ResolveWithId(endpoint, id);
var json = JsonSerializer.Serialize(entity, _jsonOptions);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync(url, content, ct);
await EnsureSuccessStatusCodeWithDetailsAsync(response, ct);
}
    /// <inheritdoc />
    public async Task DeleteAsync(string endpoint, int id, CancellationToken ct = default)
{
var url = ApiEndpointResolver.ResolveWithId(endpoint, id);
var response = await _httpClient.DeleteAsync(url, ct);
await EnsureSuccessStatusCodeWithDetailsAsync(response, ct);
}
private static async Task EnsureSuccessStatusCodeWithDetailsAsync(
HttpResponseMessage response,
CancellationToken ct)
{
if (response.IsSuccessStatusCode) return;
var body = TrimBody(await response.Content.ReadAsStringAsync(ct));
throw new HttpRequestException(
$"Request to '{response.RequestMessage?.RequestUri}' failed with " +
$"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {body}");
}
private static IReadOnlyList<string> GetFallbackEndpoints(string endpoint)
{
if (string.Equals(endpoint, "systems", StringComparison.OrdinalIgnoreCase))
return new[] { "systems", "system" };
if (string.Equals(endpoint, "devices", StringComparison.OrdinalIgnoreCase))
return new[] { "devices", "device" };
if (string.Equals(endpoint, "ips", StringComparison.OrdinalIgnoreCase))
return new[] { "ips", "ip" };
if (string.Equals(endpoint, "subnets", StringComparison.OrdinalIgnoreCase))
return new[] { "subnets", "subnet" };
if (string.Equals(endpoint, "customer_zones", StringComparison.OrdinalIgnoreCase))
return new[] { "customer_zones", "customer_zone" };
if (string.Equals(endpoint, "application_zones", StringComparison.OrdinalIgnoreCase))
return new[] { "application_zones", "application_zone" };
if (string.Equals(endpoint, "vms", StringComparison.OrdinalIgnoreCase))
return new[] { "vms", "vm", "virtual_machines", "systems", "system" };
return new[] { endpoint };
}
private static string TrimBody(string body)
{
if (body.Length > 400)
return body[..400] + "...";
return body;
}
private sealed class FlexibleStringJsonConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
return reader.GetString() ?? string.Empty;
if (reader.TokenType == JsonTokenType.Number)
return reader.GetDouble().ToString(System.Globalization.CultureInfo.InvariantCulture);
if (reader.TokenType == JsonTokenType.True)
return bool.TrueString;
if (reader.TokenType == JsonTokenType.False)
return bool.FalseString;
if (reader.TokenType == JsonTokenType.Null)
return string.Empty;
using var doc = JsonDocument.ParseValue(ref reader);
return doc.RootElement.ToString();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
=> writer.WriteStringValue(value);
}
}
@@ -0,0 +1,50 @@
using System.Net;
using MaxInventory.Core.Services;
using MaxInventory.Core.Settings;
namespace MaxInventory.Infrastructure.Http
{
/// <summary>
/// Factory for creating an HttpClient configured with certificate authentication,
/// proxy settings, and the correct base URL for the inventory API.
/// </summary>
public static class InventoryHttpClientFactory
{
///<summary> Creates a fully configured HttpClient for the inventory API.</summary>
public static HttpClient Create(
ICertificateProvider certificateProvider,
ApiSettings apiSettings,
ProxySettings proxySettings)
{
var handler = new HttpClientHandler();
//Attach client certificate for mutual TLS
var cert = certificateProvider.GetClientCertificate();
handler.ClientCertificates.Add(cert);
//Configure proxy if enabled
if (proxySettings.Enabled && !string.IsNullOrEmpty(proxySettings.Address))
{
handler.Proxy = new WebProxy(proxySettings.Address);
handler.UseProxy = true;
}
else
{
handler.UseProxy = false;
}
//Ensure the base URL ends with a trailing slash for proper relative URL resolution
var baseUrl = apiSettings.BaseUrl.TrimEnd('/') + "/";
var client = new HttpClient(handler)
{
BaseAddress = new Uri(baseUrl),
Timeout = TimeSpan.FromSeconds(apiSettings.TimeoutSeconds),
};
client.DefaultRequestHeaders.Add("Accept", "application/json");
return client;
}
}
}
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MaxInventory.Core\MaxInventory.Core.csproj" />
</ItemGroup>
</Project>
+33
View File
@@ -0,0 +1,33 @@
@using static Microsoft.AspNetCore.Components.Web.RenderMode
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width", initial-scale="1.0" />
<base href="/" />
<link rel="icon" type="image/png" href="favicon.ico" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" />
<link rel="stylesheet" href="css/themes/variables-light.css" />
<link rel="stylesheet" href="css/themes/variables-dark.css" />
<link rel="stylesheet" href="css/app.css" />
<link rel="stylesheet" href="MaxInventory.Web.styles.css" />
<HeadOutlet @rendermode="InteractiveServer" />
</head>
<body>
<Routes @rendermode="InteractiveServer" />
<script>
// Apply saved theme immediately to prevent flash of wrong theme
(function() {
var theme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', theme);
})();
</script>
<script src="_framework/blazor.web.js"></script>
</body>
</html>
@@ -0,0 +1,56 @@
@inherits LayoutComponentBase
@inject IThemeService ThemeService
@inject IToastService ToastService
@implements IDisposable
<div class="app-container">
<header class="app-header">
<div class="d-flex align-center gap-1">
<button class="btn-icon theme-toggle" @onclick="ToggleSidebar" title="Toggle sidebar">
<i class="bg-info bi-list"></i>
</button>
<h1>Max Technical Services Inventory</h1>
</div>
<div class="flex-1 align-center gap-1">
<ThemeToggle />
</div>
</header>
<div class="app-body">
<nav class="app-sidebar @(_sidebarCollapsed ? "collapsed" : "")">
<NavMenu />
</nav>
<main class="app-content">
@Body
</main>
</div>
</div>
<MaxInventory.Web.Components.Shared.ToastNotification />
@code {
private bool _sidebarCollapsed;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await ThemeService.InitializeAsync();
ToastService.OnToastsChanged += HandleToastsChanged;
StateHasChanged();
}
}
private void HandleToastsChanged() => _ = InvokeAsync(StateHasChanged);
private void ToggleSidebar()
{
_sidebarCollapsed = !_sidebarCollapsed;
}
public void Dispose()
{
ToastService.OnToastsChanged -= HandleToastsChanged;
}
}
@@ -0,0 +1 @@
/* Scoped styles for MainLayout - keep minimal since app.css handles most layout */
@@ -0,0 +1,21 @@
@using MaxInventory.Core.Registry
@inject IContentTypeRegistry ContentTypeRegistry
<ul class="nav-menu">
<li class="nav-menu-item">
<NavLink class="nav-menu-link" href="" Match="NavLinkMatch.All">
<i class="bg-info bi-house-door"></i>
<span>Home</span>
</NavLink>
</li>
@foreach (var def in ContentTypeRegistry.GetAllDefinitions())
{
<li class="nav-menu-item">
<NavLink class="nav-menu-link" href="@($"content/{def.UrlSlug}")">
<i class="bi @def.IconCssClass"></i>
<span>@def.DisplayName</span>
</NavLink>
</li>
}
</ul>
@@ -0,0 +1 @@
/* Scoped styles for NavMenu - most styling handled in app.css */
@@ -0,0 +1,6 @@
@inject IThemeService ThemeService
<button class="theme-toggle" @onclick="ThemeService.ToggleThemeAsync"
title="@(ThemeService.IsDarkMode ? "Switch to Light mode" : "Switch to dar mode")">
<i class="bi @(ThemeService.IsDarkMode ? "bi-sun" : "bi-moon-stars")"></i>
</button>"
@@ -0,0 +1,66 @@
@page "/content/{ContentTypeSlug}"
@attribute [Authorize(Policy = "ViewOnly")]
@using Microsoft.AspNetCore.Authorization
@using MaxInventory.Core.Configuration
@using MaxInventory.Core.Enums
@using MaxInventory.Core.Models
@using MaxInventory.Core.Registry
@using MaxInventory.Web.Components.Shared
@* Generic page for all 7 content types. Route /content/{slug}.
All behavior driven by ContentTypeRegistry metadata — no type-specific code. *@
@if (_definition == null)
{
<ErrorDisplay Message="@($"Content type '{ContentTypeSlug}' not found.")" />
}
else if (_isLoading)
{
<LoadingSpinner Message="@($"Loading {_definition.DisplayName}...")" />
}
else if (!string.IsNullOrEmpty(_errorMessage))
{
<ErrorDisplay Message="@_errorMessage" OnRetry="LoadDataAsync" />
}
else
{
<div style="margin-bottom: 1rem;">
<h2 style="margin: 0;">@_definition.DisplayName</h2>
<span class="text-muted">@_items.Count total records</span>
</div>
<MaxInventory.Web.Components.Shared.InventoryDataGrid Items="@_items"
Fields="@_definition.Fields"
SelectedItem="@_selectedItem"
OnRowSelect="SelectItem"
OnEdit="ShowEditForm"
OnDelete="ShowDeleteConfirm"
OnAdd="ShowAddForm"
CanAdd="@_canEdit"
CanEdit="@_canEdit"
CanDelete="@_canDelete" />
@if (_selectedItem != null)
{
<RelatedRecordsPanel Entity="@_selectedItem"
ContentType="@_definition.ContentType"
IsVisible="@_showRelationships"
AllData="@_dataCache"
CanEdit="@_canEdit"
OnEditRequested="OpenEditFromRelatedAsync"
OnClose="CloseRelationships" />
}
}
<EntityForm IsVisible="@_showForm"
Entity="@_formEntity"
Fields="@(_formDefinition?.Fields ?? _definition?.Fields ?? Array.Empty<FieldDefinition>())"
ModelType="@(_formDefinition?.ModelType ?? _definition?.ModelType ?? typeof(object))"
ContentTypeName="@(_formDefinition?.DisplayName ?? _definition?.DisplayName ?? "")"
OnSave="SaveEntityAsync"
OnCancel="CloseForm" />
<DeleteConfirmation IsVisible="@_showDeleteConfirm"
ItemDisplayName="@_deleteDisplayName"
OnConfirm="ConfirmDeleteAsync"
OnCancel="() => _showDeleteConfirm = false" />
@@ -0,0 +1,390 @@
namespace MaxInventory.Web.Components.Pages;
using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
using MaxInventory.Core.Models;
using MaxInventory.Core.Registry;
using MaxInventory.Core.Services;
using MaxInventory.Web.Components.Shared;
using MaxInventory.Web.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
/// <summary>
/// Code-behind for the generic ContentTypePage.
/// Handles loading, CRUD, selection, and relationship cache population.
/// Adding a new content type requires NO changes to this file.
/// </summary>
public partial class ContentTypePage : ComponentBase
{
[Parameter] public string ContentTypeSlug { get; set; } = "";
[SupplyParameterFromQuery(Name = "highlight")]
public int? HighlightId { get; set; }
[SupplyParameterFromQuery(Name = "edit")]
public int? EditId { get; set; }
[Inject] public required IContentTypeRegistry ContentTypeRegistry { get; set; }
[Inject] public required IInventoryApiClient ApiClient { get; set; }
[Inject] public required IRelationshipRegistry RelationshipRegistry { get; set; }
[Inject] public required IToastService ToastService { get; set; }
[Inject] public required AuthenticationStateProvider AuthenticationStateProvider { get; set; }
// ── Page State ───────────────────────────────────────────────────
private ContentTypeDefinition? _definition;
private ContentTypeDefinition? _formDefinition;
private List<IInventoryEntity> _items = new();
private IInventoryEntity? _selectedItem;
private IInventoryEntity? _formEntity; // non-null = edit; null + _showForm = add
private bool _showForm;
private bool _showDeleteConfirm;
private bool _showRelationships;
private string _deleteDisplayName = "";
private IInventoryEntity? _pendingDeleteItem;
private bool _isLoading;
private string? _errorMessage;
private bool _canView;
private bool _canEdit;
private bool _canDelete;
/// <summary>
/// Cache of all entities per content type used by RelatedRecordsPanel for matching.
/// Populated on demand as relationships are requested.
/// </summary>
private readonly Dictionary<ContentTypeName, IReadOnlyList<IInventoryEntity>> _dataCache = new();
// ── Lifecycle ────────────────────────────────────────────────────
protected override async Task OnParametersSetAsync()
{
await ResolvePermissionsAsync();
_definition = ContentTypeRegistry.GetByUrlSlug(ContentTypeSlug);
if (_definition == null) return;
_formDefinition = _definition;
// Reset state when navigating to a different content type
_selectedItem = null;
_formEntity = null;
_showForm = false;
_showDeleteConfirm = false;
_showRelationships = false;
_errorMessage = null;
_items.Clear();
if (!_canView)
{
_items.Clear();
_errorMessage = "You are not authorized to view this content.";
return;
}
await LoadDataAsync();
// Auto-highlight record when navigated from relationship panel
if (HighlightId.HasValue)
{
_selectedItem = _items.FirstOrDefault(i => i.Id == HighlightId.Value);
}
if (EditId.HasValue)
{
var editItem = _items.FirstOrDefault(i => i.Id == HighlightId.Value);
if (editItem != null && _canEdit)
ShowEditForm(editItem);
}
}
// ── Data Loading ─────────────────────────────────────────────────
private async Task LoadDataAsync()
{
if (_definition == null) return;
_isLoading = true;
_errorMessage = null;
StateHasChanged();
try
{
_items = await LoadEntitiesAsync(_definition);
_dataCache[_definition.ContentType] = _items.AsReadOnly();
}
catch (Exception ex)
{
_errorMessage = $"Failed to load {_definition.DisplayName}(API endpoint '{_definition.ApiEndpoint}'): {ex.Message}";
}
finally
{
_isLoading = false;
StateHasChanged();
}
}
private async Task EnsureCachedAsync(ContentTypeName contentType)
{
if (_dataCache.ContainsKey(contentType)) return;
var def = ContentTypeRegistry.GetDefinition(contentType);
var items = await LoadEntitiesAsync(def);
_dataCache[contentType] = items.AsReadOnly();
StateHasChanged();
}
/// <summary>
/// Loads entities for a content type using reflection to call the generic API method.
/// </summary>
private async Task<List<IInventoryEntity>> LoadEntitiesAsync(ContentTypeDefinition def)
{
var method = typeof(IInventoryApiClient)
.GetMethod(nameof(IInventoryApiClient.GetAllAsync))!
.MakeGenericMethod(def.ModelType);
var task = (System.Threading.Tasks.Task)method.Invoke(
ApiClient, new object[] { def.ApiEndpoint, CancellationToken.None })!;
await task;
var result = task.GetType().GetProperty("Result")!.GetValue(task);
return ((System.Collections.IEnumerable)result!)
.Cast<IInventoryEntity>()
.ToList();
}
private static string GetPropertyValue(IInventoryEntity entity, string propertyName)
{
var prop = entity.GetType().GetProperty(propertyName);
return prop?.GetValue(entity)?.ToString() ?? "";
}
// ── Row Selection ─────────────────────────────────────────────────
private void SelectItem(IInventoryEntity item)
{
// Toggle off if clicking already-selected row
if (_selectedItem?.Id == item.Id)
{
_selectedItem = null;
_showRelationships = false;
StateHasChanged();
return;
}
_selectedItem = item;
_showRelationships = true;
StateHasChanged();
// Pre-load related content types into cache in the background.
// InvokeAsync keeps work on the circuit synchronization context so StateHasChanged() is safe.
if (_definition != null)
{
_ = InvokeAsync(async () =>
{
var rules = RelationshipRegistry.GetRulesForContentType(_definition.ContentType);
foreach (var rule in rules)
{
await EnsureCachedAsync(rule.TargetContentType);
}
if (_definition.ContentType == ContentTypeName.Ips)
await EnsureCachedAsync(ContentTypeName.Subnets);
if (_definition.ContentType == ContentTypeName.Subnets)
await EnsureCachedAsync(ContentTypeName.Ips);
if (_definition.ContentType == ContentTypeName.Systems ||
_definition.ContentType == ContentTypeName.Devices)
{
await EnsureCachedAsync(ContentTypeName.Ips);
await EnsureCachedAsync(ContentTypeName.Subnets);
}
});
}
}
// ── CRUD ─────────────────────────────────────────────────────────
private void ShowAddForm()
{
if (!_canEdit)
{
ToastService.ShowError("You do not have permission to add records.");
return;
}
_formDefinition = _definition;
_formEntity = null;
_showForm = true;
StateHasChanged();
}
private void ShowEditForm(IInventoryEntity entity)
{
if (!_canEdit)
{
ToastService.ShowError("You do not have permission to edit records.");
return;
}
_formDefinition = _definition;
_formEntity = entity;
_showForm = true;
StateHasChanged();
}
private void ShowDeleteConfirm(IInventoryEntity entity)
{
if (!_canDelete)
{
ToastService.ShowError("You do not have permission to delete records.");
return;
}
_pendingDeleteItem = entity;
_deleteDisplayName = GetDisplayName(entity);
_showDeleteConfirm = true;
StateHasChanged();
}
private void CloseForm()
{
_showForm = false;
_formEntity = null;
_formDefinition = _definition;
StateHasChanged();
}
private void CloseRelationships()
{
_showRelationships = false;
StateHasChanged();
}
private async Task SaveEntityAsync(IInventoryEntity entity)
{
if (!_canEdit)
{
ToastService.ShowError("You do not have permission to save records.");
return;
}
var activeDefinition = _formDefinition ?? _definition;
if (activeDefinition == null) return;
try
{
if (entity.Id == 0)
{
// Create
var createMethod = typeof(IInventoryApiClient)
.GetMethod(nameof(IInventoryApiClient.CreateAsync))!
.MakeGenericMethod(activeDefinition.ModelType);
var task = (System.Threading.Tasks.Task)createMethod.Invoke(
ApiClient, new object[] { activeDefinition.ApiEndpoint, entity, CancellationToken.None })!;
await task;
ToastService.ShowSuccess($"{activeDefinition.DisplayName} created successfully.");
}
else
{
// Update
var updateMethod = typeof(IInventoryApiClient)
.GetMethod(nameof(IInventoryApiClient.UpdateAsync))!
.MakeGenericMethod(activeDefinition.ModelType);
var task = (System.Threading.Tasks.Task)updateMethod.Invoke(
ApiClient, new object[] { activeDefinition.ApiEndpoint, entity.Id, entity, CancellationToken.None })!;
await task;
ToastService.ShowSuccess($"{activeDefinition.DisplayName} updated successfully.");
}
CloseForm();
await LoadDataAsync();
if (_definition != null && activeDefinition.ContentType != _definition.ContentType)
{
_dataCache.Remove(activeDefinition.ContentType);
await EnsureCachedAsync(activeDefinition.ContentType);
}
}
catch (Exception ex)
{
ToastService.ShowError($"Save failed: {ex.Message}");
}
}
private async Task ConfirmDeleteAsync()
{
if (!_canDelete)
{
ToastService.ShowError("You do not have permission to delete records.");
return;
}
if (_definition == null || _pendingDeleteItem == null) return;
var idToDelete = _pendingDeleteItem.Id;
_showDeleteConfirm = false;
try
{
await ApiClient.DeleteAsync(_definition.ApiEndpoint, idToDelete);
ToastService.ShowSuccess($"{_definition.DisplayName} deleted.");
if (_selectedItem?.Id == idToDelete) _selectedItem = null;
_pendingDeleteItem = null;
await LoadDataAsync();
}
catch (Exception ex)
{
ToastService.ShowError($"Delete failed: {ex.Message}");
}
}
// ── Helpers ──────────────────────────────────────────────────────
private string GetDisplayName(IInventoryEntity entity)
{
if (_definition == null) return $"ID {entity.Id}";
var field = _definition.Fields.FirstOrDefault(f => f.PropertyName == _definition.DisplayPropertyName);
var value = EntityValueResolver.GetValue(entity, _definition.DisplayPropertyName, field?.JsonPropertyName);
return string.IsNullOrEmpty(value) ? $"ID {entity.Id}" : value;
}
private async Task OpenEditFromRelatedAsync(RelatedEditRequest request)
{
if (!_canEdit)
{
ToastService.ShowError("You do not have permission to edit records.");
return;
}
if (!_dataCache.TryGetValue(request.ContentType, out var entities))
{
await EnsureCachedAsync(request.ContentType);
_dataCache.TryGetValue(request.ContentType, out entities);
}
var target = entities?.FirstOrDefault(e => e.Id == request.EntityId);
if (target is null)
{
ToastService.ShowError("Unable to locate related record for editing.");
return;
}
_formDefinition = ContentTypeRegistry.GetDefinition(request.ContentType);
_formEntity = target;
_showForm = true;
StateHasChanged();
}
private async Task ResolvePermissionsAsync()
{
var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = state.User;
_canView = user.Identity?.IsAuthenticated == true &&
(user.IsInRole("View") || user.IsInRole("EditAdd") || user.IsInRole("Admin"));
_canEdit = user.Identity?.IsAuthenticated == true &&
(user.IsInRole("EditAdd") || user.IsInRole("Admin"));
_canDelete = user.Identity?.IsAuthenticated == true && user.IsInRole("Admin");
}
}
@@ -0,0 +1,19 @@
@page "/"
@attribute [Authorize(Policy = "ViewOnly")]
@using Microsoft.AspNetCore.Authorization
@using MaxInventory.Core.Registry
@inject IContentTypeRegistry ContentTypeRegistry
<h2 style="margin-bottom 0.5rem;">Dashboard</h2>
<p class="text-muted" style="margin-bottom 1.5rem;">Select a content type to view and manage inventory records.</p>
<div class="dashboard-grid">
@foreach (var def in ContentTypeRegistry.GetAllDefinitions())
{
<a class="dashboard-card" href="@($"content/{def.UrlSlug}")">
<i class="bi @def.IconCssClass"></i>
<h3>@def.DisplayName</h3>
<div class="count">View records</div>
</a>
}
</div>
@@ -0,0 +1,28 @@
@using MaxInventory.Web.Components.Layout
@using Microsoft.AspNetCore.Components.Authorization
<CascadingAuthenticationState>
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)">
<NotAuthorized>
<LayoutView Layout="typeof(MainLayout)">
<div class="error-container">
<i class="bi bi-shield-lock"></i>
<span style="margin-left: 0.5rem;">Access denied.</span>
</div>
</LayoutView>
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
<NotFound>
<LayoutView Layout="typeof(MainLayout)">
<div class="error-container">
<i class="bi bi-exclamation-triangle"></i>
<span style="margin-left: 0.5rem;">Page not found.</span>
</div>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
@@ -0,0 +1,33 @@
@using MaxInventory.Core.Configuration
@* Per-column filter input in the filter row *@
<th>
<input type="text"
class="form-control"
placeholder="Filter..."
value="@FilterValue"
@oninput="OnInput" />
</th>
@code {
[Parameter] public required FieldDefinition Field { get; set; }
[Parameter] public string FilterValue { get; set; } = "";
[Parameter] public EventCallback<string> OnFilterChanged { get; set; }
private Timer? _debounceTimer;
private void OnInput(ChangeEventArgs e)
{
var value = e.Value?.ToString() ?? "";
_debounceTimer?.Dispose();
_debounceTimer = new Timer(async _ =>
{
await InvokeAsync(async () =>
{
await OnFilterChanged.InvokeAsync(value);
});
}, null, 300, Timeout.Infinite);
}
}
@@ -0,0 +1,48 @@
@using MaxInventory.Core.Configuration
@using MaxInventory.Core.Enums
@* Sortable column header — click to sort, shows direction indicator *@
<th class="@(IsSorted ? "sorted" : "")" @onclick="HandleClick"
title="@(Field.DisplayName)">
@Field.DisplayName
@if (IsSorted)
{
<span class="sort-indicator">
<i class="bi @(CurrentSortDirection == SortDirection.Ascending ? "bi-sort-up" : "bi-sort-down")"></i>
</span>
}
else
{
<span class="sort-indicator">
<i class="bi bi-arrow-down-up"></i>
</span>
}
</th>
@code {
[Parameter] public required FieldDefinition Field { get; set; }
[Parameter] public string CurrentSortColumn { get; set; } = "";
[Parameter] public SortDirection CurrentSortDirection { get; set; }
[Parameter] public EventCallback<(string column, SortDirection direction)> OnSortChanged { get; set; }
private bool IsSorted => CurrentSortColumn == Field.PropertyName;
private async Task HandleClick()
{
SortDirection newDirection;
if (IsSorted)
{
// Toggle direction
newDirection = CurrentSortDirection == SortDirection.Ascending
? SortDirection.Descending
: SortDirection.Ascending;
}
else
{
newDirection = SortDirection.Ascending;
}
await OnSortChanged.InvokeAsync((Field.PropertyName, newDirection));
}
}
@@ -0,0 +1,35 @@
@* Modal confirmation dialog for delete operations *@
@if (IsVisible)
{
<div class="modal-backdrop" @onclick="Cancel">
<div class="modal-dialog" @onclick:stopPropagation>
<div class="modal-header">
<h3>Confirm Delete</h3>
<button class="btn-icon" @onclick="Cancel">
<i class="bi bi-x-lg"></i>
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete <strong>@ItemDisplayName</strong>?</p>
<p class="text-muted">This action cannot be undone.</p>
</div>
<div class="modal-footer">
<button class="btn btn-outline-secondary" @onclick="Cancel">Cancel</button>
<button class="btn btn-danger" @onclick="Confirm">
<i class="bi bi-trash"></i> Delete
</button>
</div>
</div>
</div>
}
@code {
[Parameter] public bool IsVisible { get; set; }
[Parameter] public string ItemDisplayName { get; set; } = "";
[Parameter] public EventCallback OnConfirm { get; set; }
[Parameter] public EventCallback OnCancel { get; set; }
private async Task Confirm() => await OnConfirm.InvokeAsync();
private async Task Cancel() => await OnCancel.InvokeAsync();
}
@@ -0,0 +1,33 @@
@using MaxInventory.Core.Configuration
@using MaxInventory.Core.Registry
@* Dropdown select populated from the DropdownOptionRegistry with tooltip descriptions *@
@inject IDropdownOptionRegistry DropdownRegistry
<select class="form-select" value="@Value" @onchange="OnChange" disabled="@Disabled">
<option value="">-- Select --</option>
@if (!string.IsNullOrEmpty(OptionSetName) && DropdownRegistry.HasOptionSet(OptionSetName))
{
@foreach (var option in DropdownRegistry.GetOptions(OptionSetName))
{
<option value="@option.Value" title="@option.Description">
@option.DisplayLabel
</option>
}
}
</select>
@code {
[Parameter] public string Value { get; set; } = "";
[Parameter] public EventCallback<string> ValueChanged { get; set; }
[Parameter] public string? OptionSetName { get; set; }
[Parameter] public bool Disabled { get; set; }
private async Task OnChange(ChangeEventArgs e)
{
var newValue = e.Value?.ToString() ?? "";
Value = newValue;
await ValueChanged.InvokeAsync(newValue);
}
}
@@ -0,0 +1,113 @@
namespace MaxInventory.Web.Components.Shared;
using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
using MaxInventory.Core.Models;
using MaxInventory.Core.Services;
using Microsoft.AspNetCore.Components;
/// <summary>
/// Non-generic add/edit form that works with any IInventoryEntity via reflection.
/// Stores field values in a string dictionary for binding, writes back to entity on save.
/// ModelType parameter is used to instantiate the correct model class for new entities.
/// </summary>
public partial class EntityForm : ComponentBase
{
[Parameter] public bool IsVisible { get; set; }
[Parameter] public IInventoryEntity? Entity { get; set; }
[Parameter] public required IReadOnlyList<FieldDefinition> Fields { get; set; }
[Parameter] public required Type ModelType { get; set; }
[Parameter] public string ContentTypeName { get; set; } = "";
[Parameter] public EventCallback<IInventoryEntity> OnSave { get; set; }
[Parameter] public EventCallback OnCancel { get; set; }
private Dictionary<string, string>? _editValues;
private readonly Dictionary<string, string> _validationErrors = new();
private bool _isEditMode;
private IEnumerable<FieldDefinition> EditableFields =>
Fields.Where(f => f.IsEditable).OrderBy(f => f.SortOrder);
protected override void OnParametersSet()
{
if (!IsVisible) return;
_isEditMode = Entity is not null;
_validationErrors.Clear();
_editValues = new Dictionary<string, string>();
foreach (var field in Fields)
{
if (_isEditMode && Entity != null)
{
_editValues[field.PropertyName] = EntityValueResolver.GetValue(Entity, field.PropertyName, field.JsonPropertyName);
}
else
{
_editValues[field.PropertyName] = "";
}
}
}
// ── Field binding ───────────────────────────────────────────────
private void SetFieldValue(string propertyName, string value)
{
if (_editValues != null)
_editValues[propertyName] = value;
_validationErrors.Remove(propertyName);
}
// ── Validation ──────────────────────────────────────────────────
private bool Validate()
{
_validationErrors.Clear();
if (_editValues == null) return false;
foreach (var field in EditableFields.Where(f => f.IsRequired))
{
var value = _editValues.GetValueOrDefault(field.PropertyName, "");
if (string.IsNullOrWhiteSpace(value))
{
_validationErrors[field.PropertyName] = $"{field.DisplayName} is required.";
}
}
return _validationErrors.Count == 0;
}
// ── Save: rebuild entity from string dictionary via reflection ───
private async Task HandleSave()
{
if (!Validate() || _editValues == null) return;
var entity = (IInventoryEntity)Activator.CreateInstance(ModelType)!;
// Preserve original ID in edit mode
if (_isEditMode && Entity != null)
entity.Id = Entity.Id;
foreach (var field in Fields)
{
var prop = ModelType.GetProperty(field.PropertyName);
if (prop == null || !prop.CanWrite) continue;
var rawValue = _editValues.GetValueOrDefault(field.PropertyName, "");
if (prop.PropertyType == typeof(int))
prop.SetValue(entity, int.TryParse(rawValue, out var i) ? i : 0);
else
prop.SetValue(entity, rawValue);
}
await OnSave.InvokeAsync(entity);
}
private async Task HandleCancel()
{
_validationErrors.Clear();
await OnCancel.InvokeAsync();
}
}
@@ -0,0 +1,76 @@
@using MaxInventory.Core.Configuration
@using MaxInventory.Core.Enums
@using MaxInventory.Core.Models
@* Non-generic add/edit form modal. Works with any IInventoryEntity via reflection.
Fields rendered from FieldDefinition metadata. Required field validation on save. *@
@if (IsVisible)
{
<div class="modal-backdrop" @onclick="HandleCancel">
<div class="modal-dialog" @onclick:stopPropagation>
<div class="modal-header">
<h3>@(_isEditMode ? "Edit" : "Add") @ContentTypeName</h3>
<button class="btn-icon" @onclick="HandleCancel"
style="color: var(--text-secondary);">
<i class="bi bi-x-lg"></i>
</button>
</div>
<div class="modal-body">
@if (_editValues != null)
{
@foreach (var field in EditableFields)
{
<div class="form-group">
<label class="form-label">
@field.DisplayName
@if (field.IsRequired)
{
<span class="required">*</span>
}
</label>
@if (field.InputType == InputType.Dropdown)
{
<DropdownField OptionSetName="@field.DropdownOptionSetName"
Value="@_editValues.GetValueOrDefault(field.PropertyName, "")"
ValueChanged="(v) => SetFieldValue(field.PropertyName, v)" />
}
else if (field.InputType == InputType.TextArea)
{
<textarea class="form-control" rows="3"
@onchange="@(e => SetFieldValue(field.PropertyName, e.Value?.ToString() ?? string.Empty))"
placeholder="@field.DisplayName">@(_editValues.GetValueOrDefault(field.PropertyName, string.Empty))</textarea>
}
else if (field.InputType == InputType.Integer)
{
<input type="number" class="form-control"
value="@(_editValues.GetValueOrDefault(field.PropertyName, "0"))"
@onchange="@(e => SetFieldValue(field.PropertyName, e.Value?.ToString() ?? "0"))"
placeholder="@field.DisplayName" />
}
else
{
<input type="text" class="form-control"
value="@(_editValues.GetValueOrDefault(field.PropertyName, string.Empty))"
@onchange="@(e => SetFieldValue(field.PropertyName, e.Value?.ToString() ?? string.Empty))"
placeholder="@field.DisplayName" />
}
@if (_validationErrors.TryGetValue(field.PropertyName, out var error))
{
<div class="form-error">@error</div>
}
</div>
}
}
</div>
<div class="modal-footer">
<button class="btn btn-outline-secondary" @onclick="HandleCancel">Cancel</button>
<button class="btn btn-primary" @onclick="HandleSave">
<i class="bi bi-check-lg"></i> Save
</button>
</div>
</div>
</div>
}
@@ -0,0 +1,27 @@
@* Displays an error message with optional retry button *@
@if (!string.IsNullOrEmpty(Message))
{
<div class="error-container">
<div class="d-flex align-center justify-between">
<div>
<i class="bi bi-exclamation-triangle"></i>
<span style="margin-left: 0.5rem;">@Message</span>
</div>
@if (OnRetry.HasDelegate)
{
<button class="btn btn-outline-danger btn-sm" @onclick="OnRetry">
<i class="bi bi-arrow-clockwise"></i> Retry
</button>
}
</div>
</div>
}
@code {
[Parameter]
public string? Message { get; set; }
[Parameter]
public EventCallback OnRetry { get; set; }
}
@@ -0,0 +1,40 @@
@* Global search input with search icon and debounce *@
<div class="global-search">
<i class="bi bi-search"></i>
<input type="text"
class="form-control"
placeholder="Search all fields..."
value="@SearchText"
@oninput="OnInput" />
</div>
@code {
[Parameter]
public string SearchText { get; set; } = "";
[Parameter]
public EventCallback<string> SearchTextChanged { get; set; }
[Parameter]
public EventCallback<string> OnSearchChanged { get; set; }
private Timer? _debounceTimer;
private void OnInput(ChangeEventArgs e)
{
var value = e.Value?.ToString() ?? "";
SearchText = value;
// Debounce: wait 300ms after user stops typing
_debounceTimer?.Dispose();
_debounceTimer = new Timer(async _ =>
{
await InvokeAsync(async () =>
{
await SearchTextChanged.InvokeAsync(value);
await OnSearchChanged.InvokeAsync(value);
});
}, null, 300, Timeout.Infinite);
}
}
@@ -0,0 +1,104 @@
@using MaxInventory.Core.Configuration
@using MaxInventory.Core.Enums
@using MaxInventory.Core.Models
@* Generic data grid — renders any IInventoryEntity using reflection + FieldDefinition metadata.
Supports: sort by any column, per-column filter, global search, pagination, row selection. *@
<div class="data-grid-container">
<div class="data-grid-toolbar">
<GlobalSearch @bind-SearchText="_globalSearchText"
OnSearchChanged="HandleGlobalSearchChanged" />
<div class="d-flex gap-1 align-center">
<span class="text-muted">@FilteredAndSortedItems.Count items</span>
@if (CanAdd)
{
<button class="btn btn-primary btn-sm" @onclick="OnAdd">
<i class="bi bi-plus-lg"></i> Add New
</button>
}
</div>
</div>
<div class="data-grid-table-wrapper">
<table class="data-grid-table">
<thead>
<tr>
@foreach (var field in VisibleFields)
{
<ColumnHeader Field="field"
CurrentSortColumn="@_sortColumn"
CurrentSortDirection="@_sortDirection"
OnSortChanged="HandleSortChanged" />
}
<th class="actions-column">
@if (CanEdit || CanDelete)
{
<span>Actions</span>
}
</th>
</tr>
<tr class="filter-row">
@foreach (var field in VisibleFields)
{
<ColumnFilter Field="field"
FilterValue="@GetColumnFilter(field.PropertyName)"
OnFilterChanged="(value) => HandleColumnFilterChanged(field.PropertyName, value)" />
}
<th></th>
</tr>
</thead>
<tbody>
@if (!PagedItems.Any())
{
<tr>
<td colspan="@(VisibleFields.Count() + 1)"
class="text-center text-muted"
style="padding: 2rem;">
No records found.
</td>
</tr>
}
else
{
@foreach (var item in PagedItems)
{
<tr class="@(SelectedItem?.Id == item.Id ? "selected" : "")"
@onclick="() => HandleRowClick(item)">
@foreach (var field in VisibleFields)
{
<td title="@GetPropertyValueString(item, field.PropertyName)">
@GetDisplayValue(item, field)
</td>
}
<td class="actions-cell">
@if (CanEdit)
{
<button class="btn btn-sm btn-outline-primary"
@onclick:stopPropagation
@onclick="() => OnEdit.InvokeAsync(item)">
<i class="bi bi-pencil"></i>
</button>
}
@if (CanDelete)
{
<button class="btn btn-sm btn-outline-danger"
@onclick:stopPropagation
@onclick="() => OnDelete.InvokeAsync(item)">
<i class="bi bi-trash"></i>
</button>
}
</td>
</tr>
}
}
</tbody>
</table>
</div>
<Pagination CurrentPage="_currentPage"
TotalPages="TotalPages"
TotalItems="FilteredAndSortedItems.Count"
PageSize="PageSize"
OnPageChanged="HandlePageChanged" />
</div>
@@ -0,0 +1,163 @@
namespace MaxInventory.Web.Components.Shared;
using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums;
using MaxInventory.Core.Models;
using MaxInventory.Core.Registry;
using MaxInventory.Core.Services;
using Microsoft.AspNetCore.Components;
/// <summary>
/// Non-generic data grid that renders any IInventoryEntity using reflection.
/// All column, filter, sort, and display behavior is driven by FieldDefinition metadata.
/// </summary>
public partial class InventoryDataGrid : ComponentBase
{
[Parameter] public required IReadOnlyList<IInventoryEntity> Items { get; set; }
[Parameter] public required IReadOnlyList<FieldDefinition> Fields { get; set; }
[Parameter] public EventCallback<IInventoryEntity> OnEdit { get; set; }
[Parameter] public EventCallback<IInventoryEntity> OnDelete { get; set; }
[Parameter] public EventCallback OnAdd { get; set; }
[Parameter] public EventCallback<IInventoryEntity> OnRowSelect { get; set; }
[Parameter] public IInventoryEntity? SelectedItem { get; set; }
[Parameter] public int PageSize { get; set; } = 25;
[Parameter] public bool CanAdd { get; set; } = false;
[Parameter] public bool CanEdit { get; set; } = false;
[Parameter] public bool CanDelete { get; set; } = false;
[Inject] public required IDropdownOptionRegistry DropdownRegistry { get; set; }
// ── Internal State ──────────────────────────────────────────────
private string _globalSearchText = "";
private string _sortColumn = "";
private SortDirection _sortDirection = SortDirection.Ascending;
private readonly Dictionary<string, string> _columnFilters = new();
private int _currentPage = 1;
// ── Computed Properties ─────────────────────────────────────────
private IEnumerable<FieldDefinition> VisibleFields =>
Fields.Where(f => f.ShowInGrid).OrderBy(f => f.SortOrder);
private IReadOnlyList<IInventoryEntity> FilteredAndSortedItems => ApplyPipeline();
private int TotalPages => Math.Max(1,
(int)Math.Ceiling((double)FilteredAndSortedItems.Count / PageSize));
private IReadOnlyList<IInventoryEntity> PagedItems => FilteredAndSortedItems
.Skip((_currentPage - 1) * PageSize)
.Take(PageSize)
.ToList()
.AsReadOnly();
// ── Pipeline ────────────────────────────────────────────────────
private IReadOnlyList<IInventoryEntity> ApplyPipeline()
{
var items = Items.AsEnumerable();
// 1. Global search — match any visible field
if (!string.IsNullOrWhiteSpace(_globalSearchText))
{
var search = _globalSearchText;
items = items.Where(item => VisibleFields.Any(f =>
GetPropertyValueString(item, f.PropertyName, f.JsonPropertyName)
.Contains(search, StringComparison.OrdinalIgnoreCase)));
}
// 2. Per-column filters
foreach (var (propertyName, filterText) in _columnFilters)
{
if (!string.IsNullOrWhiteSpace(filterText))
{
var filter = filterText;
var prop = propertyName;
var field = Fields.FirstOrDefault(f => f.PropertyName == prop);
items = items.Where(item =>
GetPropertyValueString(item, prop, field?.JsonPropertyName)
.Contains(filter, StringComparison.OrdinalIgnoreCase));
}
}
// 3. Sorting
if (!string.IsNullOrEmpty(_sortColumn))
{
var col = _sortColumn;
var field = Fields.FirstOrDefault(f => f.PropertyName == col);
items = _sortDirection == SortDirection.Ascending
? items.OrderBy(item => GetPropertyValueString(item, col, field?.JsonPropertyName), StringComparer.OrdinalIgnoreCase)
: items.OrderByDescending(item => GetPropertyValueString(item, col, field?.JsonPropertyName), StringComparer.OrdinalIgnoreCase);
}
return items.ToList().AsReadOnly();
}
// ── Property Access ─────────────────────────────────────────────
private static string GetPropertyValueString(IInventoryEntity item, string propertyName, string? jsonPropertyName = null)
{
return EntityValueResolver.GetValue(item, propertyName, jsonPropertyName);
}
/// <summary>
/// Gets the display value for a field, resolving dropdown labels when applicable.
/// </summary>
private string GetDisplayValue(IInventoryEntity item, FieldDefinition field)
{
var rawValue = GetPropertyValueString(item, field.PropertyName, field.JsonPropertyName);
// For dropdown fields, show the display label if available
if (field.InputType == InputType.Dropdown &&
!string.IsNullOrEmpty(field.DropdownOptionSetName) &&
!string.IsNullOrEmpty(rawValue) &&
DropdownRegistry.HasOptionSet(field.DropdownOptionSetName))
{
var options = DropdownRegistry.GetOptions(field.DropdownOptionSetName);
var option = options.FirstOrDefault(o =>
string.Equals(o.Value, rawValue, StringComparison.OrdinalIgnoreCase));
option ??= options.FirstOrDefault(o =>
o.Value.StartsWith(rawValue + ":", StringComparison.OrdinalIgnoreCase));
return option?.DisplayLabel ?? rawValue;
}
return rawValue;
}
// ── Event Handlers ──────────────────────────────────────────────
private string GetColumnFilter(string propertyName)
{
return _columnFilters.TryGetValue(propertyName, out var value) ? value : "";
}
private void HandleGlobalSearchChanged(string value)
{
_globalSearchText = value;
_currentPage = 1;
StateHasChanged();
}
private void HandleSortChanged((string column, SortDirection direction) sort)
{
_sortColumn = sort.column;
_sortDirection = sort.direction;
StateHasChanged();
}
private void HandleColumnFilterChanged(string propertyName, string value)
{
_columnFilters[propertyName] = value;
_currentPage = 1;
StateHasChanged();
}
private void HandlePageChanged(int page)
{
_currentPage = page;
StateHasChanged();
}
private async Task HandleRowClick(IInventoryEntity item)
{
await OnRowSelect.InvokeAsync(item);
}
}
@@ -0,0 +1 @@
/* Scoped styles for DataGrid - most styling is in app.css data-grid classes */
@@ -0,0 +1,14 @@
@* Simple loading indicator *@
<div class="loading-container">
<div class="spinner"></div>
@if (!string.IsNullOrEmpty(Message))
{
<span class="text-muted" style="margin-left: 0.75rem;">@Message</span>
}
</div>
@code {
[Parameter]
public string? Message { get; set; } = "Loading...";
}
@@ -0,0 +1,80 @@
@* Pagination control with page buttons and item count info *@
<div class="pagination-container">
<div class="pagination-info">
@if (TotalItems > 0)
{
var start = (CurrentPage - 1) * PageSize + 1;
var end = Math.Min(CurrentPage * PageSize, TotalItems);
<span>Showing @start - @end of @TotalItems items</span>
}
else
{
<span>No items</span>
}
</div>
@if (TotalPages > 1)
{
<div class="pagination-buttons">
<button class="btn btn-outline-secondary btn-sm"
disabled="@(CurrentPage <= 1)"
@onclick="() => GoToPage(1)">
<i class="bi bi-chevron-double-left"></i>
</button>
<button class="btn btn-outline-secondary btn-sm"
disabled="@(CurrentPage <= 1)"
@onclick="() => GoToPage(CurrentPage - 1)">
<i class="bi bi-chevron-left"></i>
</button>
@foreach (var pageNumber in GetVisiblePages())
{
<button class="btn btn-sm @(pageNumber == CurrentPage ? "active btn-primary" : "btn-outline-secondary")"
@onclick="() => GoToPage(pageNumber)">
@pageNumber
</button>
}
<button class="btn btn-outline-secondary btn-sm"
disabled="@(CurrentPage >= TotalPages)"
@onclick="() => GoToPage(CurrentPage + 1)">
<i class="bi bi-chevron-right"></i>
</button>
<button class="btn btn-outline-secondary btn-sm"
disabled="@(CurrentPage >= TotalPages)"
@onclick="() => GoToPage(TotalPages)">
<i class="bi bi-chevron-double-right"></i>
</button>
</div>
}
</div>
@code {
[Parameter] public int CurrentPage { get; set; } = 1;
[Parameter] public int TotalPages { get; set; } = 1;
[Parameter] public int TotalItems { get; set; }
[Parameter] public int PageSize { get; set; } = 25;
[Parameter] public EventCallback<int> OnPageChanged { get; set; }
private async Task GoToPage(int page)
{
if (page >= 1 && page <= TotalPages && page != CurrentPage)
{
await OnPageChanged.InvokeAsync(page);
}
}
private IEnumerable<int> GetVisiblePages()
{
const int maxVisible = 5;
var start = Math.Max(1, CurrentPage - maxVisible / 2);
var end = Math.Min(TotalPages, start + maxVisible - 1);
if (end - start + 1 < maxVisible)
start = Math.Max(1, end - maxVisible + 1);
for (var i = start; i <= end; i++)
yield return i;
}
}
@@ -0,0 +1,10 @@
using MaxInventory.Core.Enums;
namespace MaxInventory.Web.Components.Shared
{
public sealed class RelatedEditRequest
{
public required ContentTypeName ContentType { get; init; }
public required int EntityId { get; init; }
}
}
@@ -0,0 +1,654 @@
@using MaxInventory.Core.Configuration
@using MaxInventory.Core.Enums
@using MaxInventory.Core.Models
@using MaxInventory.Core.Registry
@using MaxInventory.Core.Services
@using Microsoft.AspNetCore.Components.Web
@using System.Net
@inject IRelationshipRegistry RelationshipRegistry
@inject IContentTypeRegistry ContentTypeRegistry
@inject IDropdownOptionRegistry DropdownRegistry
@if (IsVisible && _stack.Any())
{
<div class="modal-backdrop" @onclick="CloseAll" @onkeydown="HandleKeyDown" tabindex="0">
@for (var index = 0; index < _stack.Count; index++)
{
var context = _stack[index];
var stackIndex = index;
<div class="modal-dialog"
style="@GetDialogStyle(stackIndex)"
@onclick:stopPropagation>
<div class="modal-header">
<h3>
<i class="bi bi-diagram-3"></i>
@context.Definition.DisplayName: @GetEntityTitle(context)
</h3>
<button class="btn-icon"
@onclick="() => CloseAt(stackIndex)"
style="color: var(--text-secondary);">
<i class="bi bi-x-lg"></i>
</button>
</div>
<div class="modal-body" style="display: grid; gap: 1rem;">
<section>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
<div class="text-muted">Item Details</div>
@if (CanEdit)
{
<button class="btn btn-sm btn-outline-primary"
@onclick="() => RequestEdit(context.ContentType, context.Entity.Id)">
<i class="bi bi-pencil"></i> Edit This @context.Definition.DisplayName
</button>
}
</div>
<div style="display: grid; gap: 0.35rem;">
@foreach (var row in context.Details)
{
<div style="display: grid; grid-template-columns: minmax(180px, 220px) 1fr; gap: 0.75rem; border-top: 1px solid var(--border-color); padding-top: 0.35rem;">
<div style="font-weight: 600;">@row.Label</div>
<div class="text-muted" style="word-break: break-word;">@row.Value</div>
</div>
}
</div>
</section>
<section>
<div class="text-muted" style="margin-bottom: 0.5rem;">Related Records</div>
@if (!context.RelatedGroups.Any())
{
<div class="text-muted">No related records found for this item.</div>
}
else
{
@foreach (var group in context.RelatedGroups)
{
var groupKey = BuildGroupKey(context, group);
var visibleItems = GetVisibleGroupItems(context, group);
<div class="related-group" style="margin-bottom: 1rem;">
<div class="related-group-label" style="margin-bottom: 0.5rem;">
@group.Label (@visibleItems.Count)
</div>
<div style="margin-bottom: 0.5rem;">
<input class="form-control form-control-sm"
style="max-width: 320px;"
placeholder="Filter related records..."
value="@GetGroupFilter(groupKey)"
@oninput="(e) => SetGroupFilter(groupKey, e.Value?.ToString() ?? string.Empty)" />
</div>
<div style="overflow-x: auto;">
<table class="data-grid-table">
<thead>
<tr>
@foreach (var field in group.Fields)
{
<th style="cursor: pointer;"
@onclick="() => ToggleGroupSort(groupKey, field.PropertyName)">
@field.DisplayName @GetSortIndicator(groupKey, field.PropertyName)
</th>
}
@if (CanEdit)
{
<th>Actions</th>
}
</tr>
</thead>
<tbody>
@foreach (var item in visibleItems)
{
<tr style="cursor: pointer;" @onclick="() => OpenEntity(item, group.ContentType)">
@foreach (var field in group.Fields)
{
<td>@GetDisplayValue(item, field)</td>
}
@if (CanEdit)
{
<td>
<button class="btn btn-sm btn-outline-primary"
@onclick:stopPropagation
@onclick="() => RequestEdit(group.ContentType, item.Id)">
<i class="bi bi-pencil"></i> Edit
</button>
</td>
}
</tr>
}
</tbody>
</table>
</div>
</div>
}
}
</section>
<!--<details>
<summary>Raw JSON</summary>
<pre style="max-height: 220px; overflow: auto; margin-top: 0.4rem; background: var(--surface-alt); padding: 0.5rem; border-radius: 6px;">@context.RawJson</pre>
</details> -->
</div>
<div class="modal-footer">
@if (index > 0)
{
<button class="btn btn-outline-secondary" @onclick="() => CloseAt(stackIndex)">Back</button>
}
<button class="btn btn-outline-secondary" @onclick="CloseAll">Close All</button>
</div>
</div>
}
</div>
}
@code {
[Parameter] public IInventoryEntity? Entity { get; set; }
[Parameter] public ContentTypeName ContentType { get; set; }
[Parameter] public bool IsVisible { get; set; }
[Parameter] public EventCallback OnClose { get; set; }
[Parameter] public Dictionary<ContentTypeName, IReadOnlyList<IInventoryEntity>> AllData { get; set; } = new();
[Parameter] public bool CanEdit { get; set; }
[Parameter] public EventCallback<RelatedEditRequest> OnEditRequested { get; set; }
private readonly List<InspectContext> _stack = new();
private readonly Dictionary<string, string> _groupFilters = new();
private readonly Dictionary<string, GroupSortState> _groupSorts = new();
protected override void OnParametersSet()
{
if (!IsVisible || Entity is null)
{
_stack.Clear();
return;
}
if (_stack.Count == 0 ||
_stack[0].ContentType != ContentType ||
_stack[0].Entity.Id != Entity.Id)
{
_stack.Clear();
_stack.Add(BuildContext(Entity, ContentType));
}
}
private InspectContext BuildContext(IInventoryEntity entity, ContentTypeName contentType)
{
var definition = ContentTypeRegistry.GetDefinition(contentType);
return new InspectContext
{
Entity = entity,
ContentType = contentType,
Definition = definition,
Details = BuildDetails(entity, definition),
RelatedGroups = BuildRelatedGroups(entity, contentType),
RawJson = SerializeEntity(entity),
};
}
private IReadOnlyList<DetailRow> BuildDetails(IInventoryEntity entity, ContentTypeDefinition definition)
{
var rows = new List<DetailRow>();
var knownJsonNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var field in definition.Fields.OrderBy(f => f.SortOrder))
{
var value = GetDisplayValue(entity, field);
rows.Add(new DetailRow
{
Label = field.DisplayName,
Value = string.IsNullOrWhiteSpace(value) ? "(blank)" : value,
});
knownJsonNames.Add(field.JsonPropertyName);
}
if (entity.ExtensionData is not null)
{
foreach (var pair in entity.ExtensionData.OrderBy(p => p.Key, StringComparer.OrdinalIgnoreCase))
{
if (string.Equals(pair.Key, "association_values", StringComparison.OrdinalIgnoreCase) ||
knownJsonNames.Contains(pair.Key))
{
continue;
}
rows.Add(new DetailRow
{
Label = pair.Key,
Value = pair.Value.ToString(),
});
}
}
return rows.AsReadOnly();
}
private IReadOnlyList<RelatedGroupView> BuildRelatedGroups(IInventoryEntity entity, ContentTypeName contentType)
{
var groups = new List<RelatedGroupView>();
var rules = RelationshipRegistry.GetRulesForContentType(contentType);
foreach (var rule in rules)
{
if (!string.IsNullOrEmpty(rule.SourceFilterPropertyName))
{
var filterValue = GetPropertyValue(entity, rule.SourceFilterPropertyName);
if (!string.Equals(filterValue, rule.SourceFilterValue, StringComparison.OrdinalIgnoreCase))
continue;
}
var sourceValue = GetPropertyValue(entity, rule.SourcePropertyName);
if (string.IsNullOrWhiteSpace(sourceValue))
continue;
if (!AllData.TryGetValue(rule.TargetContentType, out var targetEntities))
continue;
var matches = targetEntities
.Where(target => MatchesRule(sourceValue, target, rule))
.ToList();
if (matches.Count == 0)
continue;
var targetDefinition = ContentTypeRegistry.GetDefinition(rule.TargetContentType);
matches = SortRelatedItems(matches, targetDefinition);
var fields = targetDefinition.Fields
.Where(f => f.ShowInGrid)
.OrderBy(f => f.SortOrder)
.ToList()
.AsReadOnly();
groups.Add(new RelatedGroupView
{
Label = rule.DisplayLabel,
ContentType = rule.TargetContentType,
Fields = fields,
Items = matches.AsReadOnly(),
});
}
groups.AddRange(BuildIpSubnetGroups(entity, contentType));
groups.AddRange(BuildHostSubnetGroups(entity, contentType));
return groups.AsReadOnly();
}
private IEnumerable<RelatedGroupView> BuildIpSubnetGroups(IInventoryEntity entity, ContentTypeName contentType)
{
if (contentType == ContentTypeName.Ips && entity is IpRecord ipRecord)
{
if (string.IsNullOrWhiteSpace(ipRecord.Ip) || !AllData.TryGetValue(ContentTypeName.Subnets, out var subnets))
yield break;
var matches = subnets
.OfType<SubnetRecord>()
.Where(subnet => ContainsIp(subnet, ipRecord.Ip))
.Cast<IInventoryEntity>()
.ToList();
if (matches.Count > 0)
{
var def = ContentTypeRegistry.GetDefinition(ContentTypeName.Subnets);
yield return new RelatedGroupView
{
Label = "Containing Subnets",
ContentType = ContentTypeName.Subnets,
Fields = def.Fields.Where(f => f.ShowInGrid).OrderBy(f => f.SortOrder).ToList().AsReadOnly(),
Items = matches.AsReadOnly(),
};
}
}
if (contentType == ContentTypeName.Subnets && entity is SubnetRecord subnetRecord)
{
if (string.IsNullOrWhiteSpace(subnetRecord.Prefix) || subnetRecord.Bits is null || !AllData.TryGetValue(ContentTypeName.Ips, out var ips))
yield break;
var matches = ips
.OfType<IpRecord>()
.Where(ip => ContainsIp(subnetRecord, ip.Ip))
.Cast<IInventoryEntity>()
.ToList();
if (matches.Count > 0)
{
var def = ContentTypeRegistry.GetDefinition(ContentTypeName.Ips);
yield return new RelatedGroupView
{
Label = "Contained IPs",
ContentType = ContentTypeName.Ips,
Fields = def.Fields.Where(f => f.ShowInGrid).OrderBy(f => f.SortOrder).ToList().AsReadOnly(),
Items = matches.AsReadOnly(),
};
}
}
}
private IEnumerable<RelatedGroupView> BuildHostSubnetGroups(IInventoryEntity entity, ContentTypeName contentType)
{
string? hostType = contentType switch
{
ContentTypeName.Systems => "System",
ContentTypeName.Devices => "Device",
_ => null,
};
if (hostType is null || !AllData.TryGetValue(ContentTypeName.Ips, out var ips) || !AllData.TryGetValue(ContentTypeName.Subnets, out var subnets))
yield break;
var relatedIps = ips
.OfType<IpRecord>()
.Where(ip =>
string.Equals(GetPropertyValue(ip, "HostType"), hostType, StringComparison.OrdinalIgnoreCase) &&
string.Equals(GetPropertyValue(ip, "HostId"), entity.Id.ToString(), StringComparison.OrdinalIgnoreCase))
.ToList();
if (relatedIps.Count == 0)
yield break;
var matchedSubnets = subnets
.OfType<SubnetRecord>()
.Where(subnet => relatedIps.Any(ip => ContainsIp(subnet, ip.Ip)))
.Cast<IInventoryEntity>()
.DistinctBy(item => item.Id)
.ToList();
if (matchedSubnets.Count == 0)
yield break;
var def = ContentTypeRegistry.GetDefinition(ContentTypeName.Subnets);
yield return new RelatedGroupView
{
Label = "Related Subnets",
ContentType = ContentTypeName.Subnets,
Fields = def.Fields.Where(f => f.ShowInGrid).OrderBy(f => f.SortOrder).ToList().AsReadOnly(),
Items = matchedSubnets.AsReadOnly(),
};
}
private bool MatchesRule(string sourceValue, IInventoryEntity target, RelationshipRule rule)
{
if (!string.IsNullOrEmpty(rule.TargetFilterPropertyName))
{
var targetFilterValue = GetPropertyValue(target, rule.TargetFilterPropertyName);
if (!string.Equals(targetFilterValue, rule.TargetFilterValue, StringComparison.OrdinalIgnoreCase))
return false;
}
var targetValue = GetPropertyValue(target, rule.TargetPropertyName);
return string.Equals(sourceValue, targetValue, StringComparison.OrdinalIgnoreCase);
}
private string GetDisplayValue(IInventoryEntity entity, FieldDefinition field)
{
var rawValue = EntityValueResolver.GetValue(entity, field.PropertyName, field.JsonPropertyName);
if (string.IsNullOrEmpty(rawValue))
return string.Empty;
if (field.InputType == InputType.Dropdown &&
!string.IsNullOrEmpty(field.DropdownOptionSetName) &&
DropdownRegistry.HasOptionSet(field.DropdownOptionSetName))
{
var option = DropdownRegistry
.GetOptions(field.DropdownOptionSetName)
.FirstOrDefault(o => string.Equals(o.Value, rawValue, StringComparison.OrdinalIgnoreCase));
option ??= DropdownRegistry
.GetOptions(field.DropdownOptionSetName)
.FirstOrDefault(o => o.Value.StartsWith(rawValue + ":", StringComparison.OrdinalIgnoreCase));
return option?.DisplayLabel ?? rawValue;
}
return rawValue;
}
private List<IInventoryEntity> SortRelatedItems(List<IInventoryEntity> items, ContentTypeDefinition definition)
{
var statusField = definition.Fields.FirstOrDefault(f => string.Equals(f.PropertyName, "Status", StringComparison.OrdinalIgnoreCase));
var displayField = definition.Fields.FirstOrDefault(f => f.PropertyName == definition.DisplayPropertyName);
return items
.OrderBy(item => GetStatusRank(item, statusField))
.ThenBy(item => EntityValueResolver.GetValue(item, definition.DisplayPropertyName, displayField?.JsonPropertyName), StringComparer.OrdinalIgnoreCase)
.ThenBy(item => item.Id)
.ToList();
}
private static int GetStatusRank(IInventoryEntity item, FieldDefinition? statusField)
{
if (statusField is null)
return 1;
var status = EntityValueResolver.GetValue(item, statusField.PropertyName, statusField.JsonPropertyName);
if (string.Equals(status, "Active", StringComparison.OrdinalIgnoreCase))
return 0;
if (string.Equals(status, "Retired", StringComparison.OrdinalIgnoreCase))
return 2;
return 1;
}
private static string GetPropertyValue(IInventoryEntity entity, string propertyName)
{
return EntityValueResolver.GetValue(entity, propertyName);
}
private string GetEntityTitle(InspectContext context)
{
var displayField = context.Definition.Fields.FirstOrDefault(f => f.PropertyName == context.Definition.DisplayPropertyName);
var title = EntityValueResolver.GetValue(context.Entity, context.Definition.DisplayPropertyName, displayField?.JsonPropertyName);
return string.IsNullOrWhiteSpace(title) ? $"ID {context.Entity.Id}" : title;
}
private void OpenEntity(IInventoryEntity entity, ContentTypeName contentType)
{
_stack.Add(BuildContext(entity, contentType));
}
private async Task RequestEdit(ContentTypeName contentType, int entityId)
{
if (!CanEdit)
{
return;
}
await OnEditRequested.InvokeAsync(new RelatedEditRequest
{
ContentType = contentType,
EntityId = entityId
});
}
private static string BuildGroupKey(InspectContext context, RelatedGroupView group)
{
return $"{context.ContentType}:{context.Entity.Id}:{group.ContentType}:{group.Label}";
}
private string GetGroupFilter(string groupKey)
{
return _groupFilters.TryGetValue(groupKey, out var value) ? value : string.Empty;
}
private void SetGroupFilter(string groupKey, string value)
{
_groupFilters[groupKey] = value;
}
private void ToggleGroupSort(string groupKey, string propertyName)
{
if (!_groupSorts.TryGetValue(groupKey, out var state))
{
_groupSorts[groupKey] = new GroupSortState
{
PropertyName = propertyName,
Ascending = true
};
return;
}
if (!string.Equals(state.PropertyName, propertyName, StringComparison.Ordinal))
{
_groupSorts[groupKey] = new GroupSortState
{
PropertyName = propertyName,
Ascending = true
};
return;
}
_groupSorts[groupKey] = new GroupSortState
{
PropertyName = propertyName,
Ascending = !state.Ascending
};
}
private string GetSortIndicator(string groupKey, string propertyName)
{
if (!_groupSorts.TryGetValue(groupKey, out var state) ||
!string.Equals(state.PropertyName, propertyName, StringComparison.Ordinal))
{
return string.Empty;
}
return state.Ascending ? "▲" : "▼";
}
private IReadOnlyList<IInventoryEntity> GetVisibleGroupItems(InspectContext context, RelatedGroupView group)
{
var groupKey = BuildGroupKey(context, group);
IEnumerable<IInventoryEntity> items = group.Items;
if (_groupFilters.TryGetValue(groupKey, out var filter) && !string.IsNullOrWhiteSpace(filter))
{
items = items.Where(item => group.Fields.Any(field =>
{
var value = GetDisplayValue(item, field);
return value.Contains(filter, StringComparison.OrdinalIgnoreCase);
}));
}
if (_groupSorts.TryGetValue(groupKey, out var sortState))
{
var field = group.Fields.FirstOrDefault(f => string.Equals(f.PropertyName, sortState.PropertyName, StringComparison.Ordinal));
if (field is not null)
{
items = sortState.Ascending
? items.OrderBy(item => GetDisplayValue(item, field), StringComparer.OrdinalIgnoreCase)
: items.OrderByDescending(item => GetDisplayValue(item, field), StringComparer.OrdinalIgnoreCase);
}
}
return items.ToList().AsReadOnly();
}
private async Task CloseAt(int index)
{
if (index <= 0)
{
await CloseAll();
return;
}
_stack.RemoveRange(index, _stack.Count - index);
}
private async Task CloseAll()
{
_stack.Clear();
await OnClose.InvokeAsync();
}
private async Task HandleKeyDown(KeyboardEventArgs args)
{
if (string.Equals(args.Key, "Escape", StringComparison.Ordinal))
await CloseAll();
}
private string GetDialogStyle(int index)
{
var offset = index * 28;
var zIndex = 1050 + index;
return $"max-width: min(1200px, calc(96vw - {offset}px)); margin-top: {offset}px; margin-left: {offset}px; z-index: {zIndex}; position: relative;";
}
private static string SerializeEntity(IInventoryEntity entity)
{
return System.Text.Json.JsonSerializer.Serialize(entity, new System.Text.Json.JsonSerializerOptions
{
WriteIndented = true
});
}
private static bool ContainsIp(SubnetRecord subnet, string ipText)
{
if (string.IsNullOrWhiteSpace(subnet.Prefix) || subnet.Bits is null || string.IsNullOrWhiteSpace(ipText))
return false;
if (!IPAddress.TryParse(subnet.Prefix, out var networkIp) || !IPAddress.TryParse(ipText, out var targetIp))
return false;
var networkBytes = networkIp.GetAddressBytes();
var targetBytes = targetIp.GetAddressBytes();
if (networkBytes.Length != targetBytes.Length)
return false;
var bits = subnet.Bits.Value;
var fullBytes = bits / 8;
var remainingBits = bits % 8;
for (var i = 0; i < fullBytes; i++)
{
if (networkBytes[i] != targetBytes[i])
return false;
}
if (remainingBits == 0)
return true;
var mask = (byte)(0xFF << (8 - remainingBits));
return (networkBytes[fullBytes] & mask) == (targetBytes[fullBytes] & mask);
}
private sealed class InspectContext
{
public required IInventoryEntity Entity { get; init; }
public required ContentTypeName ContentType { get; init; }
public required ContentTypeDefinition Definition { get; init; }
public required IReadOnlyList<DetailRow> Details { get; init; }
public required IReadOnlyList<RelatedGroupView> RelatedGroups { get; init; }
public required string RawJson { get; init; }
}
private sealed class DetailRow
{
public required string Label { get; init; }
public required string Value { get; init; }
}
private sealed class RelatedGroupView
{
public required string Label { get; init; }
public required ContentTypeName ContentType { get; init; }
public required IReadOnlyList<FieldDefinition> Fields { get; init; }
public required IReadOnlyList<IInventoryEntity> Items { get; init; }
}
private sealed class GroupSortState
{
public required string PropertyName { get; init; }
public required bool Ascending { get; init; }
}
}
@@ -0,0 +1,28 @@
@inject IToastService ToastService
@if (ToastService.Toasts.Any())
{
<div class="toast-container">
@foreach (var toast in ToastService.Toasts)
{
<div class="toast toast-@toast.Type.ToString().ToLower()">
<i class="bi @GetIcon(toast.Type)"></i>
<span class="toast-message">@toast.Message</span>
<button class="toast-close" @onclick="() => ToastService.Remove(toast.Id)">
<i class="bi bi-x"></i>
</button>
</div>
}
</div>
}
@code {
private static string GetIcon(ToastType type) => type switch
{
ToastType.Success => "bi-check-circle",
ToastType.Error => "bi-exclamation-circle",
ToastType.Warning => "bi-exclamation-triangle",
ToastType.Info => "bi-info-circle",
_ => "bi-info-circle"
};
}
@@ -0,0 +1,19 @@
@using System
@using System.Collections.Generic
@using System.Linq
@using System.Threading
@using System.Threading.Tasks
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using Microsoft.JSInterop
@using MaxInventory.Core.Configuration
@using MaxInventory.Core.Enums
@using MaxInventory.Core.Models
@using MaxInventory.Core.Registry
@using MaxInventory.Core.Services
@using MaxInventory.Web.Services
@using MaxInventory.Web.Components.Layout
@using MaxInventory.Web.Components.Shared
+30
View File
@@ -0,0 +1,30 @@
# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
# This stage is used to build the service project
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["MaxInventory.Web/MaxInventory.Web.csproj", "MaxInventory.Web/"]
RUN dotnet restore "./MaxInventory.Web/MaxInventory.Web.csproj"
COPY . .
WORKDIR "/src/MaxInventory.Web"
RUN dotnet build "./MaxInventory.Web.csproj" -c $BUILD_CONFIGURATION -o /app/build
# This stage is used to publish the service project to be copied to the final stage
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./MaxInventory.Web.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MaxInventory.Web.dll"]
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>6901b089-38e1-4cda-ba5b-a65c75681617</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\MaxInventory.Authentication\MaxInventory.Authentication.csproj" />
<ProjectReference Include="..\MaxInventory.Core\MaxInventory.Core.csproj" />
<ProjectReference Include="..\MaxInventory.Infrastructure\MaxInventory.Infrastructure.csproj" />
</ItemGroup>
</Project>
+64
View File
@@ -0,0 +1,64 @@
using MaxInventory.Authentication.Core;
using MaxInventory.Authentication.Extensions;
using MaxInventory.Infrastructure.Extensions;
using MaxInventory.Web.Components;
using MaxInventory.Web.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment())
{
builder.Configuration.AddJsonFile("FutureSecrets.json", optional: true, reloadOnChange: true);
}
var secretsDirectory = builder.Configuration["K8S_SECRET_PATH"] ?? "/programdata/docker/secrets";
if (Directory.Exists(secretsDirectory))
{
builder.Configuration.AddKeyPerFile(secretsDirectory, optional: true, reloadOnChange: true);
}
//Blazor Server Services
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddMemoryCache();
builder.Services.AddSingleton<ITicketStore, MemoryCacheTicketStore>();
builder.Services.AddCascadingAuthenticationState();
//Register all inventory services
builder.Services.AddInventoryServices(builder.Configuration);
builder.Services.AddAuthentication(builder.Configuration);
builder.Services
.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
.Configure<ITicketStore>((options, ticketStore) =>
{
options.SessionStore = ticketStore;
});
builder.Services.AddScoped<AdminCookieValidationEvents>();
//Register Blazor-specific
builder.Services.AddScoped<IThemeService, ThemeService>();
builder.Services.AddScoped<IToastService, ToastService>();
var app = builder.Build();
//configure the HTTP Request pipeline
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.RequireAuthorization("ViewOnly");
app.Run();
@@ -0,0 +1,49 @@
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5278"
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:44374;http://localhost:5278"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"environmentVariables": {
"ASPNETCORE_HTTPS_PORTS": "8081",
"ASPNETCORE_HTTP_PORTS": "8080"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:44374",
"sslPort": 44374
}
}
}
@@ -0,0 +1,34 @@
namespace MaxInventory.Web.Services
{
/// <summary>
/// Manages the application theme (light/dark mode).
/// Persists preference to browser localStorage and applies the theme via data-theme attribute.
/// </summary>
public interface IThemeService
{
/// <summary>
/// The current theme name.
/// </summary>
string CurrentTheme { get; }
/// <summary>
/// Whether dark mode is currently active.
/// </summary>
bool IsDarkMode { get; }
/// <summary>
/// Event fired when the theme changes.
/// </summary>
event Action? OnThemeChanged;
/// <summary>
/// Initializes the theme from saved preferences.
/// </summary>
Task InitializeAsync();
/// <summary>
/// Toggles between light and dark mode.
/// </summary>
Task ToggleThemeAsync();
}
}
@@ -0,0 +1,48 @@
namespace MaxInventory.Web.Services
{
/// <summary>
/// Service for showing toast notification messages to the user.
/// </summary>
public interface IToastService
{
/// <summary>
/// Event fired when a new toast is added.
/// </summary>
event Action? OnToastsChanged;
/// <summary>
/// Gets the current list of active toasts.
/// </summary>
IReadOnlyList<ToastMessage> Toasts { get; }
/// <summary>
/// Shows a success toast.
/// </summary>
/// <param name="message"></param>
void ShowSuccess(string message);
/// <summary>
/// Shows an error toast.
/// </summary>
/// <param name="message"></param>
void ShowError(string message);
/// <summary>
/// Shows a warning toast.
/// </summary>
/// <param name="message"></param>
void ShowWarning(string message);
/// <summary>
/// Shows an info toast.
/// </summary>
/// <param name="message"></param>
void ShowInfo(string message);
/// <summary>
/// Removes a toast by ID.
/// </summary>
/// <param name="id"></param>
void Remove(Guid id);
}
}
@@ -0,0 +1,81 @@
using Microsoft.JSInterop;
namespace MaxInventory.Web.Services
{
/// <summary>
/// Implementation of IThemeService using JavaScript interop
/// to read/write localStorage and set the data-theme attribute.
/// Registered as scoped (one per Blazor circuit).
/// </summary>
public sealed class ThemeService : IThemeService
{
private readonly IJSRuntime _js;
private string _currentTheme = "light";
public ThemeService(IJSRuntime js)
{
_js = js;
}
///<inheritdoc/>
public string CurrentTheme => _currentTheme;
///<inheritdoc/>
public bool IsDarkMode => _currentTheme == "dark";
///<inheritdoc/>
public event Action? OnThemeChanged;
///<inheritdoc/>
public async Task InitializeAsync()
{
try
{
var saved = await _js.InvokeAsync<string>("localStorage.getItem", "theme");
_currentTheme = saved ?? "light";
await ApplyThemeAsync();
}
catch
{
_currentTheme = "light";
}
}
///<inheritdoc/>
public async Task ToggleThemeAsync()
{
_currentTheme = IsDarkMode ? "light" : "dark";
await ApplyThemeAsync();
try
{
await _js.InvokeVoidAsync("localStorage.setItem", "theme", _currentTheme);
}
catch
{
//ignore
}
OnThemeChanged?.Invoke();
}
private async Task ApplyThemeAsync()
{
try
{
await _js.InvokeVoidAsync(
"document.documentElement.setAttribute", "data-theme", _currentTheme
);
}
catch
{
//Ignore
}
}
public void Dispose()
{
//Nothing to dispose, but DI pattern.....
}
}
}

Some files were not shown because too many files have changed in this diff Show More