Compare commits

..

54 Commits

Author SHA1 Message Date
OlgunR
292ce02370 Refactor using statements for clearer layer boundaries
Clean up and reorganize using/import statements across the solution. Remove unnecessary DTO imports from Application and Infrastructure layers, and ensure Contracts DTOs are only referenced in API and BlazorWebApp layers. No business logic is changed; these updates improve code organization, reduce coupling, and clarify architectural separation between layers.
2026-04-23 13:55:05 +02:00
OlgunR
df4de5d5f5 Refactor imports and ensure enum type safety in Catalogs
Reorganize and deduplicate using directives in _Imports.razor for clarity and maintainability. Explicitly cast UpdateProcedure to CatalogUpdateProcedure in CatalogsGrid.razor to enforce type safety. Restore necessary DevExpress and DbFirst namespaces.
2026-04-23 13:54:50 +02:00
OlgunR
e4624c92ef Refactor DTOs: make public, add properties, clean up
Refactored DTO classes by removing unnecessary using statements and internal wrappers, making them public, and adding explicit properties with default values. Clarified namespaces and improved accessibility for use in API contracts or service layers. Added CatalogUpdateProcedure to CatalogWriteDto to specify update operation type.
2026-04-23 11:48:45 +02:00
OlgunR
b0d60461b4 Standardize DTO naming and namespaces for MassData
Refactored DTO class and namespace names from Massdata* to MassData* in DbFirst.Contracts. Updated all relevant application files to use the correct DTO namespaces for Catalogs and MassData. Adjusted _Imports.razor to include new DTO namespaces and removed unused usings. These changes improve code consistency and reduce namespace-related errors.
2026-04-23 11:41:10 +02:00
OlgunR
c45c1a69a7 Remove obsolete DTO classes and add Layouts folder
Deleted DTOs for catalogs, layouts, mass data, and dashboard info from both Application and BlazorWebApp.Models namespaces. Updated DbFirst.Application.csproj to include a new Layouts folder for future organization. No functional code changes in this commit.
2026-04-23 11:25:31 +02:00
OlgunR
b268e53e1f Add project references to Contracts and Domain projects
Added DbFirst.Contracts as a project reference to both DbFirst.Application and DbFirst.BlazorWebApp, and added DbFirst.Domain to DbFirst.Application. Also, a BOM was introduced in the BlazorWebApp project file. These changes enable shared use of contracts and domain types across projects.
2026-04-23 11:23:24 +02:00
OlgunR
a1fee6f5c0 Add initial empty DTO classes for Catalogs, Dashboards, etc.
Introduced six new internal DTO classes: CatalogReadDto, CatalogWriteDto, DashboardInfoDto, LayoutDto, MassdataReadDto, and MassdataWriteDto. Each class resides in its appropriate namespace and currently contains no properties or methods, serving as placeholders for future data transfer logic.
2026-04-23 11:22:58 +02:00
OlgunR
dbb39354ab Add DbFirst.Contracts project to solution
Added new DbFirst.Contracts project targeting .NET 8.0 with nullable and implicit usings enabled. Included a project reference to DbFirst.Domain and updated the solution file to register the new project with all build configurations.
2026-04-23 11:15:53 +02:00
OlgunR
2ffa389978 Update AutoMapper to 16.1.1 and adjust registration
Upgraded AutoMapper to version 16.1.1 across API, Application, and Infrastructure projects. Removed AutoMapper.Extensions.Microsoft.DependencyInjection where no longer needed. Updated AutoMapper registration in DependencyInjection.cs to use the new API. No other changes made.
2026-04-22 09:35:50 +02:00
OlgunR
f54de87ca2 Standardize string property initialization to string.Empty
Replaced String.Empty and null! with string.Empty for string properties
in CatalogReadDto, CatalogWriteDto, and VwmyCatalog classes. This
ensures consistent initialization and helps prevent null reference
issues across the codebase.
2026-04-22 09:25:03 +02:00
OlgunR
1b4205219f Set string defaults to String.Empty in CatalogReadDto
Changed default values of CatTitle, CatString, and AddedWho from null! to String.Empty to prevent potential null reference issues.
2026-04-21 17:01:44 +02:00
OlgunR
b35c167648 Add [FromBody] to DTO params in controller actions
Explicitly annotate DTO parameters with [FromBody] in CatalogsController (Create, Update) and MassDataController (Upsert) to ensure correct model binding from the request body and improve API clarity.
2026-04-21 15:22:33 +02:00
OlgunR
087708dcf7 Use array literal [] for empty CORS origins default
Replaces Array.Empty<string>() with the C# array literal [] when defaulting the CORS allowed origins array. This is a syntactic improvement with no change in behavior.
2026-04-21 15:22:19 +02:00
OlgunR
be40c39f47 Initialize VwmyCatalog string properties with String.Empty
Changed default values of CatTitle, CatString, and AddedWho from null! to String.Empty to prevent potential null reference issues and ensure safer property initialization.
2026-04-21 13:43:33 +02:00
OlgunR
4fa3bcae3d Make dashboard change notifications async and robust
Refactored DashboardChangeNotifier and IDashboardChangeNotifier to use async notification with improved error handling and logging. Updated SqlDashboardStorage to call the new async notification method after dashboard changes, ensuring non-blocking and reliable client updates.
2026-04-21 13:42:31 +02:00
OlgunR
612d8371d3 Improve exception handling with ProblemDetails responses
ExceptionHandlingMiddleware now returns structured ProblemDetails
responses for errors, including specific handling for
InvalidOperationException (400 Bad Request) and general exceptions
(500 Internal Server Error). Responses use "application/problem+json"
content type and include trace IDs. ProblemDetails support is also
registered in Program.cs.
2026-04-21 13:18:59 +02:00
OlgunR
b7e66ab5f9 Update MediatR and DI packages; refactor registration
Upgraded to MediatR 14.1.0 and updated registration to use the new syntax. Removed MediatR.Extensions.Microsoft.DependencyInjection where no longer needed. Bumped Microsoft.Extensions.DependencyInjection.Abstractions to 10.0.0 in Application and Infrastructure projects.
2026-04-21 12:01:23 +02:00
OlgunR
95a388015a Remove GetAllAsync method from MassDataRepository
The GetAllAsync method, which returned all Massdata records, has been removed from the MassDataRepository class. No other changes were made in this commit.
2026-04-21 10:30:10 +02:00
OlgunR
c16f0483c3 Remove unused using directives from API and client files
Cleaned up unnecessary System.Net and System.Net.Http.Json usings across multiple files, including controllers and API client classes, to reduce dependencies and improve code clarity.
2026-04-21 10:16:05 +02:00
OlgunR
83292f23f3 Refactor dashboard config to factory class
Move DashboardConfigurator setup from Program.cs to a new static DashboardConfiguratorFactory. This centralizes dashboard file creation, data source registration, and storage logic, improving code organization and maintainability. Unused usings are cleaned up accordingly.
2026-04-21 10:09:50 +02:00
OlgunR
c73c7e63fe Move LayoutDto to its own file and update namespace
Separated LayoutDto from LayoutsController.cs into LayoutDto.cs and set its namespace to DbFirst.Application.Layouts for better code organization and maintainability.
2026-04-20 16:51:57 +02:00
OlgunR
3e78e2e2cf Move catalog title update validation to handler
Validation preventing CatTitle changes during updates is now enforced in UpdateCatalogHandler instead of the controller. The handler throws an exception if a title change is attempted. Also, streamlined UpdateProcedure handling and removed redundant CatTitle mapping logic.
2026-04-20 16:38:29 +02:00
OlgunR
05825b6815 Refactor DI: move repository registrations to Infrastructure
Centralize repository service registrations in Infrastructure's
DependencyInjection.cs for better maintainability and separation
of concerns. Remove direct registrations from Program.cs and
add necessary using statements.
2026-04-20 16:28:37 +02:00
OlgunR
4720c8f87b Use UTC for AddedWhen timestamps in layout repository
Changed AddedWhen to use DateTime.UtcNow instead of DateTime.Now to ensure timestamps are stored in UTC, avoiding issues with local time zones.
2026-04-20 16:22:18 +02:00
OlgunR
0c936d0bf9 Adopt C# 12 collection expressions for empty lists/dicts
Refactored code to use C# 12 collection expressions ([]) for initializing empty lists and dictionaries instead of the older constructors. This change modernizes and simplifies collection initialization across models, services, and API clients without altering any logic.
2026-04-20 14:33:08 +02:00
OlgunR
fcbc66f8f5 Add CancellationToken support to all API client methods
All API client interfaces and implementations now accept an optional CancellationToken parameter for each method. This enables consumers to cancel HTTP requests, improving responsiveness and resource management. No changes were made to core logic or return types; only method signatures and HttpClient calls were updated to support cancellation.
2026-04-20 13:50:53 +02:00
OlgunR
aab6478f9a Refactor API clients to use interface-based DI
Introduce interfaces for all API clients and update dependency injection to use these interfaces. Refactor services and components to depend on abstractions instead of concrete implementations, improving testability and maintainability.
2026-04-20 13:23:16 +02:00
OlgunR
177d418ac3 Use InvokeAsync for async state updates in BandGridBase
Replaced direct StateHasChanged() calls with InvokeAsync(StateHasChanged) to ensure asynchronous state updates. This helps prevent issues that can arise from synchronous state changes during component lifecycle events or event callbacks in Blazor.
2026-04-20 12:59:27 +02:00
OlgunR
7cc88c13f3 Cache layout user to reduce localStorage access
Add a private _cachedLayoutUser field to BandLayoutService and update EnsureLayoutUserAsync to cache the layout user value after first retrieval or generation. This avoids repeated localStorage calls and improves performance.
2026-04-20 11:48:50 +02:00
OlgunR
8bf172755b Update using directives in _Imports.razor for clarity
Added @using DbFirst.BlazorWebApp and reorganized the placement of @using Microsoft.Extensions.Options to improve code organization and maintain consistent dependency order.
2026-04-20 11:34:15 +02:00
OlgunR
27c8f92a3b Refactor API base URL config to use AppSettings class
Replaced direct IConfiguration usage with a strongly-typed AppSettings class for accessing the API base URL. Registered AppSettings with DI and updated Dashboard.razor to use IOptions<AppSettings>. Updated using statements and DI setup for improved type safety and centralized configuration management.
2026-04-20 11:32:45 +02:00
OlgunR
cd0a824064 Refactor grid logic into BandGridBase<TItem> base class
Move shared state and methods from CatalogsGrid and MassDataGrid into BandGridBase<TItem>. This centralizes edit context handling, validation, popup header logic, row editing/deleting, and layout feedback, reducing duplication and improving maintainability. Individual grid components now only override OnEditFieldChanged for custom validation.
2026-04-20 10:52:05 +02:00
OlgunR
0008fac1d2 Refactor HTTP client registration for API clients
Simplified registration of CatalogApiClient, DashboardApiClient, MassDataApiClient, and LayoutApiClient by introducing a ConfigureClient method. This method sets the BaseAddress if ApiBaseUrl is configured, removing the previous if-else logic and reducing code duplication.
2026-04-20 10:29:17 +02:00
OlgunR
4659913711 Move ApiResult<T> to ApiResult.cs with proper namespace
ApiResult<T> and its static methods were relocated from CatalogApiClient.cs to a new ApiResult.cs file. The new file now includes the DbFirst.BlazorWebApp.Models namespace for better code organization.
2026-04-20 10:24:47 +02:00
OlgunR
bb23cb6629 Refactor error handling to use ApiClientHelper
Replaced the private ReadErrorAsync method in LayoutApiClient with calls to ApiClientHelper.ReadErrorAsync, centralizing error handling logic for improved consistency and reuse.
2026-04-20 10:19:40 +02:00
OlgunR
b3f7df6801 Initialize SignalR hub in OnAfterRenderAsync after first render
Moved SignalR hub connection setup from OnInitializedAsync to OnAfterRenderAsync, ensuring initialization occurs only after the component's first render. This prevents premature connection attempts and aligns with best practices for component lifecycle management.
2026-04-20 10:08:24 +02:00
OlgunR
3a1cb68cf0 Change OnCustomizeEditModel to synchronous void method
Converted OnCustomizeEditModel in MassDataGrid.razor from async Task to synchronous void, removing asynchronous support from this method.
2026-04-17 14:28:50 +02:00
OlgunR
c93518202b Add custom toolbar actions with icons to grids
Introduce Add, Edit, and Delete buttons with Bootstrap Icons in the toolbars of CatalogsGrid and MassDataGrid. Hide the default command column by overriding ShowCommandColumn. Update BandGridBase to conditionally render the command column. Track focused row index for toolbar actions, enabling row operations via toolbar instead of the grid's built-in command column. Add Bootstrap Icons stylesheet to App.razor.
2026-04-17 12:08:39 +02:00
OlgunR
6792b426ff Enhance grid UI: column chooser button & default widths
- Set default width and hide new button for DxGridBandColumn in BandGridBase.cs
- Always show column chooser button in CatalogsGrid and MassDataGrid
- Add "Spalten" toolbar button to open column chooser dialog
- Improves accessibility and consistency of grid column customization
2026-04-16 16:02:31 +02:00
OlgunR
6ac48a472d Simplify Fluent theme registration in App.razor
Replaced custom Fluent theme registration (with ApplyToPageElements set to true) with the default Fluent theme registration, removing unnecessary property customization for a cleaner setup.
2026-04-15 14:16:35 +02:00
OlgunR
96dfd5b3c6 Set default values for CarouselData string properties
Initialized Source and AlternateText with empty strings in the
CarouselData class to prevent potential null reference issues.
2026-04-15 14:16:03 +02:00
OlgunR
810771f385 Remove auto-refresh of dashboards in OnParametersSetAsync
Previously, RefreshDashboards() was called automatically if the dashboards list was empty during parameter setting. This logic has been removed, so dashboards will no longer refresh automatically in this scenario.
2026-04-15 14:08:14 +02:00
OlgunR
a0e0d7ed03 Centralize API error handling in ApiClientHelper
Refactored error handling logic for API responses into a new static ApiClientHelper class, consolidating the ReadErrorAsync method and ProblemDetailsDto. Updated CatalogApiClient and MassDataApiClient to use the shared helper, removing redundant local methods and classes. This change improves consistency, reduces duplication, and streamlines error message formatting across the application.
2026-04-15 13:55:57 +02:00
OlgunR
39cb63a78d Refactor UpsertAsync to use ApiResult for error handling
MassDataApiClient.UpsertAsync now returns ApiResult to standardize success and error reporting, including detailed error extraction from API responses. Updated MassDataGrid.razor to handle the new result type and display error messages accordingly. Removed obsolete try-catch logic in favor of the new pattern.
2026-04-15 11:27:48 +02:00
OlgunR
7d08923444 Remove unused bandEditorExpanded field from BandGridBase
The protected bool bandEditorExpanded, which tracked the expansion
state of the band editor, has been removed from BandGridBase<TItem>
as it is no longer used. This helps clean up unused state from
the component.
2026-04-15 11:01:22 +02:00
OlgunR
11374347d3 Refactor band editor into reusable BandEditor component
Extract band editor UI and logic from CatalogsGrid.razor and MassDataGrid.razor into a new BandEditor.razor component. This centralizes band management features (add/remove bands, edit captions, assign columns, save/reset layout) and reduces code duplication, improving maintainability and reusability. Existing UI and event handling remain functionally unchanged.
2026-04-15 10:57:28 +02:00
OlgunR
7552b34ced Refactor MassDataGrid to use BandGridBase for layout logic
Move band and column management to BandGridBase, reducing duplication in MassDataGrid. Column definitions and layout key are now provided via overridden properties. Band editor actions now use feedback methods for user messages. Grid layout application and error display are streamlined. Improves maintainability and enables reuse across grid components.
2026-04-14 16:55:14 +02:00
OlgunR
13d134df0e Refactor CatalogsGrid to use BandGridBase and async layout ops
Refactored CatalogsGrid.razor to inherit from BandGridBase<CatalogReadDto>, moving band layout and grid logic into the base class. Updated UI to use new async methods for saving and resetting the layout with user feedback. Removed redundant local fields and methods, centralizing layout management and improving maintainability and code reuse. Error and info messages are now shown after layout operations.
2026-04-14 16:37:59 +02:00
OlgunR
285f029311 Add BandGridBase<TItem> for reusable banded grid logic
Introduced an abstract base class BandGridBase<TItem> to centralize banded grid functionality in Blazor apps using DevExpress. This class manages band layouts, column definitions, user-specific layout persistence, grid size modes, and rendering logic. It integrates with BandLayoutService for layout storage and retrieval, and is intended for inheritance by specific grid components.
2026-04-14 16:10:14 +02:00
OlgunR
cdf225bad1 Add full project documentation (PROJEKTDOKUMENTATION.md)
Comprehensive documentation for the DbFirst solution, detailing project goals, architecture (Clean Architecture), technology stack, solution/project structure, Database-First approach, CQRS with MediatR, API endpoints, Blazor/DevExpress frontend, dashboard and layout persistence, SignalR integration, configuration, development setup, architecture decisions (ADRs), extensibility, and glossary. Includes diagrams, code snippets, and workflow guidance for the developer team.
2026-04-09 15:45:32 +02:00
OlgunR
59e051f162 Test push für Marvin No. 4 2026-03-31 11:52:42 +02:00
OlgunR
1352dda20e Test push für Marvin No. 3 2026-03-31 10:39:12 +02:00
OlgunR
33b5b03bf4 Test push für Marvin No. 2 2026-03-31 09:42:46 +02:00
OlgunR
6b986db62e Test push für Marvin 2026-03-31 09:33:08 +02:00
82 changed files with 2121 additions and 1250 deletions

View File

@@ -1,7 +1,7 @@
using DbFirst.Application.Catalogs;
using DbFirst.Application.Catalogs.Commands;
using DbFirst.Application.Catalogs.Queries;
using DbFirst.Domain;
using DbFirst.Contracts.Catalogs;
using MediatR;
using Microsoft.AspNetCore.Mvc;
@@ -37,7 +37,7 @@ public class CatalogsController : ControllerBase
}
[HttpPost]
public async Task<ActionResult<CatalogReadDto>> Create(CatalogWriteDto dto, CancellationToken cancellationToken)
public async Task<ActionResult<CatalogReadDto>> Create([FromBody]CatalogWriteDto dto, CancellationToken cancellationToken)
{
var created = await _mediator.Send(new CreateCatalogCommand(dto), cancellationToken);
if (created == null)
@@ -48,19 +48,8 @@ public class CatalogsController : ControllerBase
}
[HttpPut("{id:int}")]
public async Task<ActionResult<CatalogReadDto>> Update(int id, CatalogWriteDto dto, CancellationToken cancellationToken)
public async Task<ActionResult<CatalogReadDto>> Update(int id, [FromBody] CatalogWriteDto dto, CancellationToken cancellationToken)
{
var current = await _mediator.Send(new GetCatalogByIdQuery(id), cancellationToken);
if (current == null)
{
return NotFound();
}
if (dto.UpdateProcedure == CatalogUpdateProcedure.Update &&
!string.Equals(current.CatTitle, dto.CatTitle, StringComparison.OrdinalIgnoreCase))
{
return BadRequest("Titel kann nicht geändert werden.");
}
var updated = await _mediator.Send(new UpdateCatalogCommand(id, dto), cancellationToken);
if (updated == null)
{

View File

@@ -1,7 +1,8 @@
using System.Text;
using DbFirst.Application.Repositories;
using DbFirst.Contracts.Layouts;
using DbFirst.Domain.Entities;
using Microsoft.AspNetCore.Mvc;
using System.Text;
namespace DbFirst.API.Controllers;
@@ -83,12 +84,4 @@ public class LayoutsController : ControllerBase
LayoutData = layoutData
};
}
public sealed class LayoutDto
{
public string LayoutType { get; set; } = string.Empty;
public string LayoutKey { get; set; } = string.Empty;
public string UserName { get; set; } = string.Empty;
public string LayoutData { get; set; } = string.Empty;
}
}

View File

@@ -1,6 +1,6 @@
using DbFirst.Application.MassData;
using DbFirst.Application.MassData.Commands;
using DbFirst.Application.MassData.Queries;
using DbFirst.Contracts.MassData;
using MediatR;
using Microsoft.AspNetCore.Mvc;
@@ -50,7 +50,7 @@ public class MassDataController : ControllerBase
}
[HttpPost("upsert")]
public async Task<ActionResult<MassDataReadDto>> Upsert(MassDataWriteDto dto, CancellationToken cancellationToken)
public async Task<ActionResult<MassDataReadDto>> Upsert([FromBody]MassDataWriteDto dto, CancellationToken cancellationToken)
{
var result = await _mediator.Send(new UpsertMassDataByCustomerNameCommand(dto), cancellationToken);
return Ok(result);

View File

@@ -1,28 +0,0 @@
using DbFirst.Application.Time.Commands;
using DbFirst.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace DbFirst.API.Controllers;
[ApiController]
[Route("api/[controller]")]
public class TimeController : ControllerBase
{
private readonly IMediator _mediator;
public TimeController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<ActionResult<TimeRecord>> InsertAndGetLast(CancellationToken cancellationToken)
{
var result = await _mediator.Send(new InsertTimeCommand(), cancellationToken);
if (result == null)
return NotFound();
return Ok(result);
}
}

View File

@@ -6,14 +6,23 @@ namespace DbFirst.API.Dashboards;
public class DashboardChangeNotifier : IDashboardChangeNotifier
{
private readonly IHubContext<DashboardsHub> _hubContext;
private readonly ILogger<DashboardChangeNotifier> _logger;
public DashboardChangeNotifier(IHubContext<DashboardsHub> hubContext)
public DashboardChangeNotifier(IHubContext<DashboardsHub> hubContext, ILogger<DashboardChangeNotifier> logger)
{
_hubContext = hubContext;
_logger = logger;
}
public void NotifyChanged()
public async Task NotifyChangedAsync()
{
_ = _hubContext.Clients.All.SendAsync("DashboardsChanged");
try
{
await _hubContext.Clients.All.SendAsync("DashboardsChanged");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to notify dashboard clients.");
}
}
}

View File

@@ -0,0 +1,115 @@
using DbFirst.Domain.Entities;
using DevExpress.DashboardCommon;
using DevExpress.DashboardWeb;
using DevExpress.DataAccess.Json;
using System.Xml.Linq;
namespace DbFirst.API.Dashboards;
public static class DashboardConfiguratorFactory
{
public static DashboardConfigurator Create(
IServiceProvider serviceProvider,
IConfiguration configuration,
IWebHostEnvironment environment)
{
// Den gesamten Inhalt des Lambdas hierher verschieben
// serviceProvider, configuration, environment statt builder.* verwenden
var dashboardsPath = Path.Combine(environment.ContentRootPath, "Data", "Dashboards");
Directory.CreateDirectory(dashboardsPath);
var defaultDashboardPath = Path.Combine(dashboardsPath, "DefaultDashboard.xml");
if (!File.Exists(defaultDashboardPath))
{
var defaultDashboard = new Dashboard();
defaultDashboard.Title.Text = "Default Dashboard";
defaultDashboard.SaveToXml(defaultDashboardPath);
}
var dashboardBaseUrl = configuration["Dashboard:BaseUrl"]
?? configuration["ApiBaseUrl"]
?? configuration["ASPNETCORE_URLS"]?.Split(';', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault()
?? "https://localhost:7204";
dashboardBaseUrl = dashboardBaseUrl.TrimEnd('/');
var catalogsGridDashboardPath = Path.Combine(dashboardsPath, "CatalogsGrid.xml");
if (!File.Exists(catalogsGridDashboardPath))
{
var dashboard = new Dashboard();
dashboard.Title.Text = "Catalogs (Dashboard Grid)";
var catalogDataSource = new DashboardJsonDataSource("Catalogs (API)")
{
ComponentName = "catalogsDataSource",
JsonSource = new UriJsonSource(new Uri($"{dashboardBaseUrl}/api/catalogs"))
};
dashboard.DataSources.Add(catalogDataSource);
var grid = new GridDashboardItem
{
DataSource = catalogDataSource,
Name = "Catalogs"
};
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.Guid))) { Name = "Id" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.CatTitle))) { Name = "Titel" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.CatString))) { Name = "String" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.AddedWho))) { Name = "Angelegt von" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.AddedWhen))) { Name = "Angelegt am" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.ChangedWho))) { Name = "Geändert von" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.ChangedWhen))) { Name = "Geändert am" });
dashboard.Items.Add(grid);
var layoutGroup = new DashboardLayoutGroup { Orientation = DashboardLayoutGroupOrientation.Vertical };
layoutGroup.ChildNodes.Add(new DashboardLayoutItem(grid));
dashboard.LayoutRoot = layoutGroup;
dashboard.SaveToXml(catalogsGridDashboardPath);
}
DashboardConfigurator configurator = new DashboardConfigurator();
var connectionString = configuration.GetConnectionString("DefaultConnection") ?? string.Empty;
var notifier = serviceProvider.GetRequiredService<IDashboardChangeNotifier>();
var dashboardStorage = new SqlDashboardStorage(connectionString, "TBDD_SMF_CONFIG", notifier: notifier);
configurator.SetDashboardStorage(dashboardStorage);
DataSourceInMemoryStorage dataSourceStorage = new DataSourceInMemoryStorage();
DashboardJsonDataSource jsonDataSourceUrl = new DashboardJsonDataSource("JSON Data Source (URL)");
jsonDataSourceUrl.JsonSource = new UriJsonSource(
new Uri("https://raw.githubusercontent.com/DevExpress-Examples/DataSources/master/JSON/customers.json"));
jsonDataSourceUrl.RootElement = "Customers";
dataSourceStorage.RegisterDataSource("jsonDataSourceUrl", jsonDataSourceUrl.SaveToXml());
var catalogsJsonDataSource = new DashboardJsonDataSource("Catalogs (API)")
{
ComponentName = "catalogsDataSource",
JsonSource = new UriJsonSource(new Uri($"{dashboardBaseUrl}/api/catalogs"))
};
dataSourceStorage.RegisterDataSource(catalogsJsonDataSource.ComponentName, catalogsJsonDataSource.SaveToXml());
dataSourceStorage.RegisterDataSource(catalogsJsonDataSource.Name, catalogsJsonDataSource.SaveToXml());
configurator.SetDataSourceStorage(dataSourceStorage);
EnsureDashboardInStorage(dashboardStorage, "DefaultDashboard", defaultDashboardPath);
EnsureDashboardInStorage(dashboardStorage, "CatalogsGrid", catalogsGridDashboardPath);
return configurator;
}
private static void EnsureDashboardInStorage(IEditableDashboardStorage storage, string id, string filePath)
{
var exists = storage.GetAvailableDashboardsInfo().Any(info => string.Equals(info.ID, id, StringComparison.OrdinalIgnoreCase));
if (exists || !File.Exists(filePath))
{
return;
}
var doc = XDocument.Load(filePath);
storage.AddDashboard(doc, id);
}
}

View File

@@ -2,5 +2,5 @@ namespace DbFirst.API.Dashboards;
public interface IDashboardChangeNotifier
{
void NotifyChanged();
Task NotifyChangedAsync();
}

View File

@@ -1,8 +1,8 @@
using DevExpress.DashboardWeb;
using Microsoft.Data.SqlClient;
using System.Data;
using System.Text;
using System.Xml.Linq;
using DevExpress.DashboardWeb;
using Microsoft.Data.SqlClient;
namespace DbFirst.API.Dashboards;
@@ -100,7 +100,7 @@ public sealed class SqlDashboardStorage : IEditableDashboardStorage
connection.Open();
command.ExecuteNonQuery();
_notifier?.NotifyChanged();
_ = _notifier?.NotifyChangedAsync();
return id;
}
@@ -122,7 +122,7 @@ public sealed class SqlDashboardStorage : IEditableDashboardStorage
throw new ArgumentException($"Dashboard '{dashboardId}' not found.");
}
_notifier?.NotifyChanged();
_ = _notifier?.NotifyChangedAsync();
}
public void DeleteDashboard(string dashboardId)
@@ -133,6 +133,6 @@ public sealed class SqlDashboardStorage : IEditableDashboardStorage
connection.Open();
command.ExecuteNonQuery();
_notifier?.NotifyChanged();
_ = _notifier?.NotifyChangedAsync();
}
}

View File

@@ -7,8 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="DevExpress.AspNetCore.Dashboard" Version="25.2.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.22" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.22" />
@@ -17,7 +16,6 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,5 +1,4 @@
using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
namespace DbFirst.API.Middleware;
@@ -20,33 +19,35 @@ public class ExceptionHandlingMiddleware
{
await _next(context);
}
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Domain validation error");
await WriteProblemAsync(context, StatusCodes.Status400BadRequest, "Eingabe ungültig", ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception");
await WriteProblemDetailsAsync(context, ex);
await WriteProblemAsync(context, StatusCodes.Status500InternalServerError, "Serverfehler", ex.Message);
}
}
private static async Task WriteProblemDetailsAsync(HttpContext context, Exception ex)
private static async Task WriteProblemAsync(HttpContext context, int status, string title, string detail)
{
if (context.Response.HasStarted)
{
throw ex;
}
if (context.Response.HasStarted) return;
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
context.Response.StatusCode = status;
context.Response.ContentType = "application/problem+json";
var problem = new
var problem = new ProblemDetails
{
type = "https://tools.ietf.org/html/rfc9110#section-15.6.1",
title = "Serverfehler",
status = context.Response.StatusCode,
detail = ex.Message,
traceId = context.TraceIdentifier
Type = $"https://tools.ietf.org/html/rfc9110#section-{(status == 400 ? "15.5.1" : "15.6.1")}",
Title = title,
Status = status,
Detail = detail,
Extensions = { ["traceId"] = context.TraceIdentifier }
};
await context.Response.WriteAsync(JsonSerializer.Serialize(problem));
await context.Response.WriteAsJsonAsync(problem);
}
}

View File

@@ -1,18 +1,11 @@
using DbFirst.API.Middleware;
using DbFirst.API.Dashboards;
using DbFirst.API.Hubs;
using DbFirst.API.Middleware;
using DbFirst.Application;
using DbFirst.Application.Repositories;
using DbFirst.Domain;
using DbFirst.Domain.Entities;
using DbFirst.Infrastructure;
using DbFirst.Infrastructure.Repositories;
using DevExpress.AspNetCore;
using DevExpress.DashboardAspNetCore;
using DevExpress.DashboardCommon;
using DevExpress.DashboardWeb;
using DevExpress.DataAccess.Json;
using System.Xml.Linq;
var builder = WebApplication.CreateBuilder(args);
@@ -20,6 +13,7 @@ var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddProblemDetails();
// TODO: allow listed origins configured in appsettings.json
// In any case, dont let them to free to use without cors. if there is no origin specified, block all.
@@ -36,7 +30,7 @@ builder.Services.AddCors(options =>
}
else
{
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
if (origins.Length > 0)
{
policy.WithOrigins(origins)
@@ -51,99 +45,11 @@ builder.Services.AddCors(options =>
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddApplication();
builder.Services.AddScoped<ICatalogRepository, CatalogRepository>();
builder.Services.AddScoped<IMassDataRepository, MassDataRepository>();
builder.Services.AddScoped<ILayoutRepository, LayoutRepository>();
builder.Services.AddScoped<ITimeRepository, TimeRepository>();
builder.Services.AddDevExpressControls();
builder.Services.AddSignalR();
builder.Services.AddSingleton<IDashboardChangeNotifier, DashboardChangeNotifier>();
builder.Services.AddScoped<DashboardConfigurator>((IServiceProvider serviceProvider) => {
var dashboardsPath = Path.Combine(builder.Environment.ContentRootPath, "Data", "Dashboards");
Directory.CreateDirectory(dashboardsPath);
var defaultDashboardPath = Path.Combine(dashboardsPath, "DefaultDashboard.xml");
if (!File.Exists(defaultDashboardPath))
{
var defaultDashboard = new Dashboard();
defaultDashboard.Title.Text = "Default Dashboard";
defaultDashboard.SaveToXml(defaultDashboardPath);
}
var dashboardBaseUrl = builder.Configuration["Dashboard:BaseUrl"]
?? builder.Configuration["ApiBaseUrl"]
?? builder.Configuration["ASPNETCORE_URLS"]?.Split(';', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault()
?? "https://localhost:7204";
dashboardBaseUrl = dashboardBaseUrl.TrimEnd('/');
var catalogsGridDashboardPath = Path.Combine(dashboardsPath, "CatalogsGrid.xml");
if (!File.Exists(catalogsGridDashboardPath))
{
var dashboard = new Dashboard();
dashboard.Title.Text = "Catalogs (Dashboard Grid)";
var catalogDataSource = new DashboardJsonDataSource("Catalogs (API)")
{
ComponentName = "catalogsDataSource",
JsonSource = new UriJsonSource(new Uri($"{dashboardBaseUrl}/api/catalogs"))
};
dashboard.DataSources.Add(catalogDataSource);
var grid = new GridDashboardItem
{
DataSource = catalogDataSource,
Name = "Catalogs"
};
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.Guid))) { Name = "Id" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.CatTitle))) { Name = "Titel" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.CatString))) { Name = "String" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.AddedWho))) { Name = "Angelegt von" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.AddedWhen))) { Name = "Angelegt am" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.ChangedWho))) { Name = "Geändert von" });
grid.Columns.Add(new GridDimensionColumn(new Dimension(nameof(VwmyCatalog.ChangedWhen))) { Name = "Geändert am" });
dashboard.Items.Add(grid);
var layoutGroup = new DashboardLayoutGroup { Orientation = DashboardLayoutGroupOrientation.Vertical };
layoutGroup.ChildNodes.Add(new DashboardLayoutItem(grid));
dashboard.LayoutRoot = layoutGroup;
dashboard.SaveToXml(catalogsGridDashboardPath);
}
DashboardConfigurator configurator = new DashboardConfigurator();
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? string.Empty;
var notifier = serviceProvider.GetRequiredService<IDashboardChangeNotifier>();
var dashboardStorage = new SqlDashboardStorage(connectionString, "TBDD_SMF_CONFIG", notifier: notifier);
configurator.SetDashboardStorage(dashboardStorage);
DataSourceInMemoryStorage dataSourceStorage = new DataSourceInMemoryStorage();
DashboardJsonDataSource jsonDataSourceUrl = new DashboardJsonDataSource("JSON Data Source (URL)");
jsonDataSourceUrl.JsonSource = new UriJsonSource(
new Uri("https://raw.githubusercontent.com/DevExpress-Examples/DataSources/master/JSON/customers.json"));
jsonDataSourceUrl.RootElement = "Customers";
dataSourceStorage.RegisterDataSource("jsonDataSourceUrl", jsonDataSourceUrl.SaveToXml());
var catalogsJsonDataSource = new DashboardJsonDataSource("Catalogs (API)")
{
ComponentName = "catalogsDataSource",
JsonSource = new UriJsonSource(new Uri($"{dashboardBaseUrl}/api/catalogs"))
};
dataSourceStorage.RegisterDataSource(catalogsJsonDataSource.ComponentName, catalogsJsonDataSource.SaveToXml());
dataSourceStorage.RegisterDataSource(catalogsJsonDataSource.Name, catalogsJsonDataSource.SaveToXml());
configurator.SetDataSourceStorage(dataSourceStorage);
EnsureDashboardInStorage(dashboardStorage, "DefaultDashboard", defaultDashboardPath);
EnsureDashboardInStorage(dashboardStorage, "CatalogsGrid", catalogsGridDashboardPath);
return configurator;
});
builder.Services.AddScoped<DashboardConfigurator>(sp =>
DashboardConfiguratorFactory.Create(sp, builder.Configuration, builder.Environment));
var app = builder.Build();
@@ -166,15 +72,3 @@ app.MapHub<DashboardsHub>("/hubs/dashboards");
app.MapControllers();
app.Run();
static void EnsureDashboardInStorage(IEditableDashboardStorage storage, string id, string filePath)
{
var exists = storage.GetAvailableDashboardsInfo().Any(info => string.Equals(info.ID, id, StringComparison.OrdinalIgnoreCase));
if (exists || !File.Exists(filePath))
{
return;
}
var doc = XDocument.Load(filePath);
storage.AddDashboard(doc, id);
}

View File

@@ -1,4 +1,5 @@
using AutoMapper;
using DbFirst.Contracts.Catalogs;
using DbFirst.Domain.Entities;
namespace DbFirst.Application.Catalogs;

View File

@@ -1,12 +0,0 @@
namespace DbFirst.Application.Catalogs;
public class CatalogReadDto
{
public int Guid { get; set; }
public string CatTitle { get; set; } = null!;
public string CatString { get; set; } = null!;
public string AddedWho { get; set; } = null!;
public DateTime AddedWhen { get; set; }
public string? ChangedWho { get; set; }
public DateTime? ChangedWhen { get; set; }
}

View File

@@ -1,10 +0,0 @@
using DbFirst.Domain;
namespace DbFirst.Application.Catalogs;
public class CatalogWriteDto
{
public string CatTitle { get; set; } = null!;
public string CatString { get; set; } = null!;
public CatalogUpdateProcedure UpdateProcedure { get; set; } = CatalogUpdateProcedure.Update;
}

View File

@@ -1,3 +1,4 @@
using DbFirst.Contracts.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;

View File

@@ -1,5 +1,6 @@
using AutoMapper;
using DbFirst.Application.Repositories;
using DbFirst.Contracts.Catalogs;
using DbFirst.Domain.Entities;
using MediatR;

View File

@@ -1,3 +1,4 @@
using DbFirst.Contracts.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;

View File

@@ -1,7 +1,8 @@
using AutoMapper;
using DbFirst.Application.Repositories;
using DbFirst.Domain.Entities;
using DbFirst.Contracts.Catalogs;
using DbFirst.Domain;
using DbFirst.Domain.Entities;
using MediatR;
namespace DbFirst.Application.Catalogs.Commands;
@@ -25,18 +26,20 @@ public class UpdateCatalogHandler : IRequestHandler<UpdateCatalogCommand, Catalo
return null;
}
if (request.Dto.UpdateProcedure == CatalogUpdateProcedure.Update &&
!string.Equals(existing.CatTitle, request.Dto.CatTitle, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Titel kann nicht geändert werden.");
}
var entity = _mapper.Map<VwmyCatalog>(request.Dto);
entity.Guid = request.Id;
entity.CatTitle = request.Dto.UpdateProcedure == CatalogUpdateProcedure.Update
? existing.CatTitle
: request.Dto.CatTitle;
entity.AddedWho = existing.AddedWho;
entity.AddedWhen = existing.AddedWhen;
entity.ChangedWho = "system";
entity.ChangedWhen = DateTime.UtcNow;
var procedure = request.Dto.UpdateProcedure;
var updated = await _repository.UpdateAsync(request.Id, entity, procedure, cancellationToken);
var updated = await _repository.UpdateAsync(request.Id, entity, request.Dto.UpdateProcedure, cancellationToken);
return updated == null ? null : _mapper.Map<CatalogReadDto>(updated);
}
}

View File

@@ -1,5 +1,6 @@
using AutoMapper;
using DbFirst.Application.Repositories;
using DbFirst.Contracts.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Queries;

View File

@@ -1,3 +1,4 @@
using DbFirst.Contracts.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Queries;

View File

@@ -1,5 +1,6 @@
using AutoMapper;
using DbFirst.Application.Repositories;
using DbFirst.Contracts.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Queries;

View File

@@ -1,3 +1,4 @@
using DbFirst.Contracts.Catalogs;
using MediatR;
namespace DbFirst.Application.Catalogs.Queries;

View File

@@ -7,14 +7,18 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0" />
<PackageReference Include="MediatR" Version="14.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DbFirst.Contracts\DbFirst.Contracts.csproj" />
<ProjectReference Include="..\DbFirst.Domain\DbFirst.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Layouts\" />
</ItemGroup>
</Project>

View File

@@ -1,5 +1,4 @@
using Microsoft.Extensions.DependencyInjection;
using MediatR;
namespace DbFirst.Application;
@@ -7,8 +6,9 @@ public static class DependencyInjection
{
public static IServiceCollection AddApplication(this IServiceCollection services)
{
services.AddAutoMapper(typeof(DependencyInjection).Assembly);
services.AddMediatR(typeof(DependencyInjection).Assembly);
services.AddAutoMapper(cfg => cfg.AddMaps(typeof(DependencyInjection).Assembly));
services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssembly(typeof(DependencyInjection).Assembly));
return services;
}
}

View File

@@ -1,3 +1,4 @@
using DbFirst.Contracts.MassData;
using MediatR;
namespace DbFirst.Application.MassData.Commands;

View File

@@ -1,5 +1,6 @@
using AutoMapper;
using DbFirst.Application.Repositories;
using DbFirst.Contracts.MassData;
using MediatR;
namespace DbFirst.Application.MassData.Commands;

View File

@@ -1,4 +1,5 @@
using AutoMapper;
using DbFirst.Contracts.MassData;
using DbFirst.Domain.Entities;
namespace DbFirst.Application.MassData;

View File

@@ -1,12 +0,0 @@
namespace DbFirst.Application.MassData;
public class MassDataReadDto
{
public int Id { get; set; }
public string CustomerName { get; set; } = string.Empty;
public decimal Amount { get; set; }
public string Category { get; set; } = string.Empty;
public bool StatusFlag { get; set; }
public DateTime AddedWhen { get; set; }
public DateTime? ChangedWhen { get; set; }
}

View File

@@ -1,5 +1,6 @@
using AutoMapper;
using DbFirst.Application.Repositories;
using DbFirst.Contracts.MassData;
using MediatR;
namespace DbFirst.Application.MassData.Queries;

View File

@@ -1,3 +1,4 @@
using DbFirst.Contracts.MassData;
using MediatR;
namespace DbFirst.Application.MassData.Queries;

View File

@@ -1,5 +1,6 @@
using AutoMapper;
using DbFirst.Application.Repositories;
using DbFirst.Contracts.MassData;
using MediatR;
namespace DbFirst.Application.MassData.Queries;

View File

@@ -1,3 +1,4 @@
using DbFirst.Contracts.MassData;
using MediatR;
namespace DbFirst.Application.MassData.Queries;

View File

@@ -1,9 +0,0 @@
using DbFirst.Domain.Entities;
namespace DbFirst.Application.Repositories;
public interface ITimeRepository
{
Task InsertAsync(CancellationToken cancellationToken = default);
Task<TimeRecord?> GetLastAsync(CancellationToken cancellationToken = default);
}

View File

@@ -1,6 +0,0 @@
using DbFirst.Domain.Entities;
using MediatR;
namespace DbFirst.Application.Time.Commands;
public record InsertTimeCommand : IRequest<TimeRecord?>;

View File

@@ -1,21 +0,0 @@
using DbFirst.Application.Repositories;
using DbFirst.Domain.Entities;
using MediatR;
namespace DbFirst.Application.Time.Commands;
public class InsertTimeHandler : IRequestHandler<InsertTimeCommand, TimeRecord?>
{
private readonly ITimeRepository _repository;
public InsertTimeHandler(ITimeRepository repository)
{
_repository = repository;
}
public async Task<TimeRecord?> Handle(InsertTimeCommand request, CancellationToken cancellationToken)
{
await _repository.InsertAsync(cancellationToken);
return await _repository.GetLastAsync(cancellationToken);
}
}

View File

@@ -0,0 +1,6 @@
namespace DbFirst.BlazorWebApp;
public class AppSettings
{
public string ApiBaseUrl { get; set; } = string.Empty;
}

View File

@@ -5,10 +5,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="/" />
@DxResourceManager.RegisterTheme(Themes.Fluent.Clone(properties =>
{
properties.ApplyToPageElements = true;
}))
@DxResourceManager.RegisterTheme(Themes.Fluent)
@DxResourceManager.RegisterScripts()
<link href="_content/DevExpress.Blazor.Dashboard/ace.css" rel="stylesheet" />
@@ -21,6 +18,7 @@
<link href="_content/DevExpress.Blazor.Dashboard/dx-dashboard.light.min.css" rel="stylesheet" />
<link rel="stylesheet" href="bootstrap/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" />
<link rel="stylesheet" href="app.css" />
<link rel="stylesheet" href="DbFirst.BlazorWebApp.styles.css" />

View File

@@ -0,0 +1,55 @@
<div class="band-editor">
<button class="band-editor-toggle" @onclick="() => IsExpanded = !IsExpanded">
<span class="band-editor-toggle-icon @(IsExpanded ? "expanded" : "")">&#9658;</span>
<span>Layout</span>
</button>
@if (IsExpanded)
{
<div class="band-editor-body">
<div class="band-controls">
<DxButton Text="Band hinzufügen" Click="OnAddBand" />
<DxButton Text="Layout speichern" Click="OnSaveLayout" Enabled="@CanSave" />
<DxButton Text="Layout zurücksetzen" Click="OnResetLayout" />
</div>
@foreach (var band in Bands)
{
<div class="band-row">
<DxTextBox Text="@band.Caption" TextChanged="@(value => OnBandCaptionChanged.InvokeAsync((band, value)))" />
<DxButton Text="Entfernen" Click="@(() => OnRemoveBand.InvokeAsync(band))" />
</div>
}
<DxFormLayout CssClass="band-columns" ColCount="2">
@foreach (var column in Columns)
{
<DxFormLayoutItem Caption="@column.Caption">
<DxComboBox Data="@BandOptions"
TData="BandOption"
TValue="string"
TextFieldName="Caption"
ValueFieldName="Id"
Value="@GetColumnBand(column.FieldName)"
ValueChanged="@(value => OnColumnBandChanged.InvokeAsync((column.FieldName, value)))"
Width="100%" />
</DxFormLayoutItem>
}
</DxFormLayout>
</div>
}
</div>
@code {
private bool IsExpanded { get; set; }
[Parameter, EditorRequired] public List<BandDefinition> Bands { get; set; } = new();
[Parameter, EditorRequired] public List<BandOption> BandOptions { get; set; } = new();
[Parameter, EditorRequired] public List<ColumnDefinition> Columns { get; set; } = new();
[Parameter, EditorRequired] public Func<string, string> GetColumnBand { get; set; } = _ => string.Empty;
[Parameter, EditorRequired] public bool CanSave { get; set; }
[Parameter] public EventCallback OnAddBand { get; set; }
[Parameter] public EventCallback OnSaveLayout { get; set; }
[Parameter] public EventCallback OnResetLayout { get; set; }
[Parameter] public EventCallback<BandDefinition> OnRemoveBand { get; set; }
[Parameter] public EventCallback<(BandDefinition Band, string Value)> OnBandCaptionChanged { get; set; }
[Parameter] public EventCallback<(string FieldName, string? BandId)> OnColumnBandChanged { get; set; }
}

View File

@@ -0,0 +1,278 @@
using DbFirst.BlazorWebApp.Models.Grid;
using DbFirst.BlazorWebApp.Services;
using DevExpress.Blazor;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Rendering;
namespace DbFirst.BlazorWebApp.Components;
public abstract class BandGridBase<TItem> : ComponentBase
{
[Inject] protected BandLayoutService BandLayoutService { get; set; } = default!;
// --- Abstract: jedes Grid definiert diese selbst ---
protected abstract string LayoutKey { get; }
protected abstract List<ColumnDefinition> ColumnDefinitions { get; }
// --- Band-Layout Felder ---
protected BandLayout bandLayout = new();
protected Dictionary<string, string> columnBandAssignments = new();
protected List<BandOption> bandOptions = new();
protected Dictionary<string, ColumnDefinition> columnLookup = new();
protected string? layoutUser;
protected bool gridLayoutApplied;
protected IGrid? gridRef;
// --- SizeMode ---
protected SizeMode _sizeMode = SizeMode.Medium;
protected static readonly List<SizeMode> _sizeModes = Enum.GetValues<SizeMode>().ToList();
protected string? errorMessage;
protected string? infoMessage;
protected bool isLoading;
protected bool hasLoaded;
protected EditContext? editContext;
protected ValidationMessageStore? validationMessageStore;
protected string popupHeaderText = "Edit";
protected int _focusedVisibleIndex;
private const string LayoutType = "GRID_BANDS";
// --- Lifecycle ---
protected async Task InitializeBandLayoutAsync()
{
columnLookup = ColumnDefinitions.ToDictionary(c => c.FieldName, StringComparer.OrdinalIgnoreCase);
layoutUser = await BandLayoutService.EnsureLayoutUserAsync();
bandLayout = await BandLayoutService.LoadBandLayoutAsync(LayoutType, LayoutKey, layoutUser, columnLookup);
columnBandAssignments = BandLayoutService.BuildAssignmentsFromLayout(bandLayout);
ApplyColumnLayoutFromStorage();
_sizeMode = bandLayout.SizeMode;
UpdateBandOptions();
}
protected async Task ApplyGridLayoutAfterRenderAsync()
{
if (!gridLayoutApplied && gridRef != null && bandLayout.GridLayout != null)
{
gridRef.LoadLayout(bandLayout.GridLayout);
gridLayoutApplied = true;
await InvokeAsync(StateHasChanged);
}
}
// --- Layout speichern / zurücksetzen ---
protected async Task SaveLayoutAsync()
{
if (string.IsNullOrWhiteSpace(layoutUser)) return;
CaptureColumnLayoutFromGrid();
await BandLayoutService.SaveBandLayoutAsync(LayoutType, LayoutKey, layoutUser, bandLayout);
}
protected async Task ResetLayoutAsync()
{
if (string.IsNullOrWhiteSpace(layoutUser)) return;
await BandLayoutService.ResetBandLayoutAsync(LayoutType, LayoutKey, layoutUser);
bandLayout = new BandLayout();
columnBandAssignments.Clear();
UpdateBandOptions();
foreach (var column in ColumnDefinitions)
column.Width = null;
columnLookup = ColumnDefinitions.ToDictionary(c => c.FieldName, StringComparer.OrdinalIgnoreCase);
_sizeMode = SizeMode.Medium;
gridRef?.LoadLayout(new GridPersistentLayout());
gridLayoutApplied = false;
}
private void CaptureColumnLayoutFromGrid()
{
if (gridRef == null) return;
var layout = gridRef.SaveLayout();
bandLayout.GridLayout = layout;
bandLayout.SizeMode = _sizeMode;
var orderedColumns = layout.Columns
.Where(c => !string.IsNullOrWhiteSpace(c.FieldName))
.OrderBy(c => c.VisibleIndex)
.ToList();
bandLayout.ColumnOrder = orderedColumns.Select(c => c.FieldName).ToList();
bandLayout.ColumnWidths = orderedColumns
.Where(c => !string.IsNullOrWhiteSpace(c.Width))
.ToDictionary(c => c.FieldName, c => c.Width, StringComparer.OrdinalIgnoreCase);
}
private void ApplyColumnLayoutFromStorage()
{
foreach (var column in ColumnDefinitions)
{
if (bandLayout.ColumnWidths.TryGetValue(column.FieldName, out var width) && !string.IsNullOrWhiteSpace(width))
column.Width = width;
}
columnLookup = ColumnDefinitions.ToDictionary(c => c.FieldName, StringComparer.OrdinalIgnoreCase);
}
// --- Band-Methoden ---
protected bool CanSaveBandLayout => !string.IsNullOrWhiteSpace(layoutUser);
protected virtual bool ShowCommandColumn => true;
protected void AddBand()
{
bandLayout.Bands.Add(new BandDefinition { Id = Guid.NewGuid().ToString("N"), Caption = "Band" });
UpdateBandOptions();
}
protected void RemoveBand(BandDefinition band)
{
bandLayout.Bands.Remove(band);
foreach (var key in columnBandAssignments.Where(p => p.Value == band.Id).Select(p => p.Key).ToList())
columnBandAssignments.Remove(key);
UpdateBandOptions();
SyncBandsFromAssignments();
}
protected void UpdateBandCaption(BandDefinition band, string value)
{
band.Caption = value;
UpdateBandOptions();
}
protected void UpdateColumnBand(string fieldName, string? bandId)
{
if (string.IsNullOrWhiteSpace(bandId))
columnBandAssignments.Remove(fieldName);
else
columnBandAssignments[fieldName] = bandId;
SyncBandsFromAssignments();
}
protected string GetColumnBand(string fieldName)
=> columnBandAssignments.TryGetValue(fieldName, out var bandId) ? bandId : string.Empty;
protected void SyncBandsFromAssignments()
{
foreach (var band in bandLayout.Bands)
{
band.Columns = ColumnDefinitions
.Where(c => columnBandAssignments.TryGetValue(c.FieldName, out var id) && id == band.Id)
.Select(c => c.FieldName)
.ToList();
}
_ = InvokeAsync(StateHasChanged);
}
protected void UpdateBandOptions()
{
bandOptions = [new() { Id = string.Empty, Caption = "Ohne Band" }];
bandOptions.AddRange(bandLayout.Bands.Select(b => new BandOption { Id = b.Id, Caption = b.Caption }));
}
// --- SizeMode ---
protected string FormatSizeText(SizeMode size) => size switch
{
SizeMode.Small => "Klein",
SizeMode.Medium => "Mittel",
SizeMode.Large => "Groß",
_ => size.ToString()
};
protected void OnSizeChange(DropDownButtonItemClickEventArgs args)
{
_sizeMode = Enum.Parse<SizeMode>(args.ItemInfo.Id);
}
// --- RenderColumns / BuildDataColumn ---
protected RenderFragment RenderColumns() => builder =>
{
var seq = 0;
if (ShowCommandColumn)
{
builder.OpenComponent<DxGridCommandColumn>(seq++);
builder.AddAttribute(seq++, "Width", "120px");
builder.CloseComponent();
}
var grouped = bandLayout.Bands.SelectMany(b => b.Columns).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var column in ColumnDefinitions.Where(c => !grouped.Contains(c.FieldName)))
BuildDataColumn(builder, ref seq, column);
foreach (var band in bandLayout.Bands)
{
if (band.Columns.Count == 0) continue;
builder.OpenComponent<DxGridBandColumn>(seq++);
builder.AddAttribute(seq++, "Caption", band.Caption);
builder.AddAttribute(seq++, "Columns", (RenderFragment)(bandBuilder =>
{
var bandSeq = 0;
foreach (var columnName in band.Columns)
{
if (columnLookup.TryGetValue(columnName, out var column))
BuildDataColumn(bandBuilder, ref bandSeq, column);
}
}));
builder.CloseComponent();
}
};
protected void BuildDataColumn(RenderTreeBuilder builder, ref int seq, ColumnDefinition column)
{
builder.OpenComponent<DxGridDataColumn>(seq++);
builder.AddAttribute(seq++, "FieldName", column.FieldName);
builder.AddAttribute(seq++, "Caption", column.Caption);
if (!string.IsNullOrWhiteSpace(column.Width))
builder.AddAttribute(seq++, "Width", column.Width);
if (!string.IsNullOrWhiteSpace(column.DisplayFormat))
builder.AddAttribute(seq++, "DisplayFormat", column.DisplayFormat);
if (column.ReadOnly)
builder.AddAttribute(seq++, "ReadOnly", true);
builder.CloseComponent();
}
protected void SetEditContext(EditContext context)
{
if (editContext == context) return;
if (editContext != null)
editContext.OnFieldChanged -= OnEditFieldChanged;
editContext = context;
validationMessageStore = new ValidationMessageStore(editContext);
editContext.OnFieldChanged += OnEditFieldChanged;
}
protected virtual void OnEditFieldChanged(object? sender, FieldChangedEventArgs e)
{
validationMessageStore?.Clear();
editContext?.NotifyValidationStateChanged();
}
protected void SetPopupHeaderText(bool isNew) => popupHeaderText = isNew ? "Neu" : "Edit";
protected async Task EditFocusedRow()
=> await gridRef!.StartEditRowAsync(_focusedVisibleIndex);
protected Task DeleteFocusedRow()
{
gridRef!.ShowRowDeleteConfirmation(_focusedVisibleIndex);
return Task.CompletedTask;
}
protected async Task SaveLayoutWithFeedbackAsync()
{
try
{
await SaveLayoutAsync();
infoMessage = "Layout gespeichert.";
errorMessage = null;
}
catch (Exception ex)
{
errorMessage = $"Layout konnte nicht gespeichert werden: {ex.Message}";
}
}
protected async Task ResetLayoutWithFeedbackAsync()
{
await ResetLayoutAsync();
infoMessage = "Layout zurückgesetzt.";
errorMessage = null;
}
}

View File

@@ -1,5 +1,5 @@
@inject CatalogApiClient Api
@inject BandLayoutService BandLayoutService
@inherits BandGridBase<CatalogReadDto>
@inject ICatalogApiClient Api
@if (!string.IsNullOrWhiteSpace(errorMessage))
{
@@ -24,47 +24,21 @@ else if (items.Count == 0)
}
else
{
<div class="band-editor">
<button class="band-editor-toggle" @onclick="() => bandEditorExpanded = !bandEditorExpanded">
<span class="band-editor-toggle-icon @(bandEditorExpanded ? "expanded" : "")">&#9658;</span>
<span>Layout</span>
</button>
@if (bandEditorExpanded)
{
<div class="band-editor-body">
<div class="band-controls">
<DxButton Text="Band hinzufügen" Click="AddBand" />
<DxButton Text="Layout speichern" Click="SaveLayoutAsync" Enabled="@CanSaveBandLayout" />
<DxButton Text="Layout zurücksetzen" Click="ResetLayoutAsync" />
</div>
@foreach (var band in bandLayout.Bands)
{
<div class="band-row">
<DxTextBox Text="@band.Caption" TextChanged="@(value => UpdateBandCaption(band, value))" />
<DxButton Text="Entfernen" Click="@(() => RemoveBand(band))" />
</div>
}
<DxFormLayout CssClass="band-columns" ColCount="2">
@foreach (var column in columnDefinitions)
{
<DxFormLayoutItem Caption="@column.Caption">
<DxComboBox Data="@bandOptions"
TData="BandOption"
TValue="string"
TextFieldName="Caption"
ValueFieldName="Id"
Value="@GetColumnBand(column.FieldName)"
ValueChanged="@(value => UpdateColumnBand(column.FieldName, value))"
Width="100%" />
</DxFormLayoutItem>
}
</DxFormLayout>
</div>
}
</div>
<BandEditor Bands="@bandLayout.Bands"
BandOptions="@bandOptions"
Columns="@ColumnDefinitions"
GetColumnBand="GetColumnBand"
CanSave="@CanSaveBandLayout"
OnAddBand="AddBand"
OnSaveLayout="SaveLayoutWithFeedbackAsync"
OnResetLayout="ResetLayoutWithFeedbackAsync"
OnRemoveBand="RemoveBand"
OnBandCaptionChanged="@(args => UpdateBandCaption(args.Band, args.Value))"
OnColumnBandChanged="@(args => UpdateColumnBand(args.FieldName, args.BandId))" />
<div class="grid-section">
<DxGrid Data="@items"
ColumnChooserButtonDisplayMode="GridColumnChooserButtonDisplayMode.Always"
TItem="CatalogReadDto"
KeyFieldName="@nameof(CatalogReadDto.Guid)"
SizeMode="@_sizeMode"
@@ -85,9 +59,42 @@ else
DataItemDeleting="OnDataItemDeleting"
FocusedRowEnabled="true"
@bind-FocusedRowKey="focusedRowKey"
RowClick="@(args => _focusedVisibleIndex = args.VisibleIndex)"
@ref="gridRef">
<ToolbarTemplate>
<DxToolbar>
<DxToolbarItem Alignment="ToolbarItemAlignment.Left">
<Template Context="_">
<DxButton IconCssClass="bi bi-plus-lg"
RenderStyle="ButtonRenderStyle.Secondary"
RenderStyleMode="ButtonRenderStyleMode.Text"
Click="@(() => gridRef!.StartEditNewRowAsync())" />
</Template>
</DxToolbarItem>
<DxToolbarItem Alignment="ToolbarItemAlignment.Left">
<Template Context="_">
<DxButton IconCssClass="bi bi-pencil"
RenderStyle="ButtonRenderStyle.Secondary"
RenderStyleMode="ButtonRenderStyleMode.Text"
Click="EditFocusedRow" />
</Template>
</DxToolbarItem>
<DxToolbarItem Alignment="ToolbarItemAlignment.Left">
<Template Context="_">
<DxButton IconCssClass="bi bi-trash"
RenderStyle="ButtonRenderStyle.Secondary"
RenderStyleMode="ButtonRenderStyleMode.Text"
Click="DeleteFocusedRow" />
</Template>
</DxToolbarItem>
<DxToolbarItem Alignment="ToolbarItemAlignment.Right">
<Template Context="_">
<DxButton Text="Spalten"
RenderStyle="ButtonRenderStyle.Secondary"
RenderStyleMode="ButtonRenderStyleMode.Text"
Click="@(() => gridRef!.ShowColumnChooser())" />
</Template>
</DxToolbarItem>
<DxToolbarItem Alignment="ToolbarItemAlignment.Right">
<Template Context="_">
<DxDropDownButton Text="@FormatSizeText(_sizeMode)"
@@ -142,35 +149,21 @@ else
@code {
private List<CatalogReadDto> items = new();
private bool isLoading;
private bool hasLoaded;
private string? errorMessage;
private string? infoMessage;
private EditContext? editContext;
private ValidationMessageStore? validationMessageStore;
private IGrid? gridRef;
private int? focusedRowKey;
private string popupHeaderText = "Edit";
private const string LayoutType = "GRID_BANDS";
private const string LayoutKey = "CatalogsGrid";
private string? layoutUser;
private BandLayout bandLayout = new();
private Dictionary<string, string> columnBandAssignments = new();
private List<BandOption> bandOptions = new();
private Dictionary<string, ColumnDefinition> columnLookup = new();
private bool gridLayoutApplied;
private bool bandEditorExpanded;
private List<ColumnDefinition> columnDefinitions = new()
{
new() { FieldName = nameof(CatalogReadDto.Guid), Caption = "Id", Width = "140px", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.CatTitle), Caption = "Titel", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.CatString), Caption = "String", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.AddedWho), Caption = "Angelegt von", ReadOnly = true, FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.AddedWhen), Caption = "Angelegt am", ReadOnly = true, FilterType = ColumnFilterType.Date },
new() { FieldName = nameof(CatalogReadDto.ChangedWho), Caption = "Geändert von", ReadOnly = true, FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.ChangedWhen), Caption = "Geändert am", ReadOnly = true, FilterType = ColumnFilterType.Date }
};
protected override string LayoutKey => "CatalogsGrid";
protected override bool ShowCommandColumn => false;
protected override List<ColumnDefinition> ColumnDefinitions { get; } = new()
{
new() { FieldName = nameof(CatalogReadDto.Guid), Caption = "Id", Width = "140px", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.CatTitle), Caption = "Titel", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.CatString), Caption = "String", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.AddedWho), Caption = "Angelegt von", ReadOnly = true, FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.AddedWhen), Caption = "Angelegt am", ReadOnly = true, FilterType = ColumnFilterType.Date },
new() { FieldName = nameof(CatalogReadDto.ChangedWho), Caption = "Geändert von", ReadOnly = true, FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(CatalogReadDto.ChangedWhen),Caption = "Geändert am", ReadOnly = true, FilterType = ColumnFilterType.Date }
};
private readonly List<ProcedureOption> procedureOptions = new()
{
@@ -178,44 +171,15 @@ else
new() { Value = 1, Text = "PRTBMY_CATALOG_SAVE" }
};
private bool CanSaveBandLayout => !string.IsNullOrWhiteSpace(layoutUser);
private SizeMode _sizeMode = SizeMode.Medium;
private static readonly List<SizeMode> _sizeModes = Enum.GetValues<SizeMode>().ToList();
private string FormatSizeText(SizeMode size) => size switch
{
SizeMode.Small => "Klein",
SizeMode.Medium => "Mittel",
SizeMode.Large => "Groß",
_ => size.ToString()
};
private void OnSizeChange(DropDownButtonItemClickEventArgs args)
{
_sizeMode = Enum.Parse<SizeMode>(args.ItemInfo.Id);
}
protected override async Task OnInitializedAsync()
{
columnLookup = columnDefinitions.ToDictionary(c => c.FieldName, StringComparer.OrdinalIgnoreCase);
layoutUser = await BandLayoutService.EnsureLayoutUserAsync();
bandLayout = await BandLayoutService.LoadBandLayoutAsync(LayoutType, LayoutKey, layoutUser, columnLookup);
columnBandAssignments = BandLayoutService.BuildAssignmentsFromLayout(bandLayout);
ApplyColumnLayoutFromStorage();
_sizeMode = bandLayout.SizeMode;
UpdateBandOptions();
await InitializeBandLayoutAsync();
await LoadCatalogs();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!gridLayoutApplied && gridRef != null && bandLayout.GridLayout != null)
{
gridRef.LoadLayout(bandLayout.GridLayout);
gridLayoutApplied = true;
await InvokeAsync(StateHasChanged);
}
await ApplyGridLayoutAfterRenderAsync();
}
private async Task LoadCatalogs()
@@ -238,185 +202,7 @@ else
}
}
private async Task SaveLayoutAsync()
{
if (string.IsNullOrWhiteSpace(layoutUser))
return;
try
{
CaptureColumnLayoutFromGrid();
await BandLayoutService.SaveBandLayoutAsync(LayoutType, LayoutKey, layoutUser, bandLayout);
infoMessage = "Layout gespeichert.";
errorMessage = null;
}
catch (Exception ex)
{
errorMessage = $"Layout konnte nicht gespeichert werden: {ex.Message}";
}
}
private async Task ResetLayoutAsync()
{
if (string.IsNullOrWhiteSpace(layoutUser))
return;
await BandLayoutService.ResetBandLayoutAsync(LayoutType, LayoutKey, layoutUser);
bandLayout = new BandLayout();
columnBandAssignments.Clear();
UpdateBandOptions();
foreach (var column in columnDefinitions)
column.Width = null;
columnLookup = columnDefinitions.ToDictionary(c => c.FieldName, StringComparer.OrdinalIgnoreCase);
_sizeMode = SizeMode.Medium;
if (gridRef != null)
gridRef.LoadLayout(new GridPersistentLayout());
gridLayoutApplied = false;
infoMessage = "Layout zurückgesetzt.";
errorMessage = null;
}
private void CaptureColumnLayoutFromGrid()
{
if (gridRef == null)
return;
var layout = gridRef.SaveLayout();
bandLayout.GridLayout = layout;
bandLayout.SizeMode = _sizeMode;
var orderedColumns = layout.Columns
.Where(c => !string.IsNullOrWhiteSpace(c.FieldName))
.OrderBy(c => c.VisibleIndex)
.ToList();
bandLayout.ColumnOrder = orderedColumns.Select(c => c.FieldName).ToList();
bandLayout.ColumnWidths = orderedColumns
.Where(c => !string.IsNullOrWhiteSpace(c.Width))
.ToDictionary(c => c.FieldName, c => c.Width, StringComparer.OrdinalIgnoreCase);
}
private void ApplyColumnLayoutFromStorage()
{
foreach (var column in columnDefinitions)
{
if (bandLayout.ColumnWidths.TryGetValue(column.FieldName, out var width) && !string.IsNullOrWhiteSpace(width))
column.Width = width;
}
columnLookup = columnDefinitions.ToDictionary(c => c.FieldName, StringComparer.OrdinalIgnoreCase);
}
private void AddBand()
{
bandLayout.Bands.Add(new BandDefinition { Id = Guid.NewGuid().ToString("N"), Caption = "Band" });
UpdateBandOptions();
}
private void RemoveBand(BandDefinition band)
{
bandLayout.Bands.Remove(band);
foreach (var key in columnBandAssignments.Where(p => p.Value == band.Id).Select(p => p.Key).ToList())
columnBandAssignments.Remove(key);
UpdateBandOptions();
SyncBandsFromAssignments();
}
private void UpdateBandCaption(BandDefinition band, string value)
{
band.Caption = value;
UpdateBandOptions();
}
private void UpdateColumnBand(string fieldName, string? bandId)
{
if (string.IsNullOrWhiteSpace(bandId))
columnBandAssignments.Remove(fieldName);
else
columnBandAssignments[fieldName] = bandId;
SyncBandsFromAssignments();
}
private string GetColumnBand(string fieldName)
=> columnBandAssignments.TryGetValue(fieldName, out var bandId) ? bandId : string.Empty;
private void SyncBandsFromAssignments()
{
foreach (var band in bandLayout.Bands)
{
band.Columns = columnDefinitions
.Where(c => columnBandAssignments.TryGetValue(c.FieldName, out var id) && id == band.Id)
.Select(c => c.FieldName)
.ToList();
}
StateHasChanged();
}
private void UpdateBandOptions()
{
bandOptions = new List<BandOption> { new() { Id = string.Empty, Caption = "Ohne Band" } };
bandOptions.AddRange(bandLayout.Bands.Select(b => new BandOption { Id = b.Id, Caption = b.Caption }));
}
private RenderFragment RenderColumns() => builder =>
{
var seq = 0;
builder.OpenComponent<DxGridCommandColumn>(seq++);
builder.AddAttribute(seq++, "Width", "120px");
builder.CloseComponent();
var grouped = bandLayout.Bands.SelectMany(b => b.Columns).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var column in columnDefinitions.Where(c => !grouped.Contains(c.FieldName)))
BuildDataColumn(builder, ref seq, column);
foreach (var band in bandLayout.Bands)
{
if (band.Columns.Count == 0) continue;
builder.OpenComponent<DxGridBandColumn>(seq++);
builder.AddAttribute(seq++, "Caption", band.Caption);
builder.AddAttribute(seq++, "Columns", (RenderFragment)(bandBuilder =>
{
var bandSeq = 0;
foreach (var columnName in band.Columns)
{
if (columnLookup.TryGetValue(columnName, out var column))
BuildDataColumn(bandBuilder, ref bandSeq, column);
}
}));
builder.CloseComponent();
}
};
private void BuildDataColumn(RenderTreeBuilder builder, ref int seq, ColumnDefinition column)
{
builder.OpenComponent<DxGridDataColumn>(seq++);
builder.AddAttribute(seq++, "FieldName", column.FieldName);
builder.AddAttribute(seq++, "Caption", column.Caption);
if (!string.IsNullOrWhiteSpace(column.Width))
builder.AddAttribute(seq++, "Width", column.Width);
if (!string.IsNullOrWhiteSpace(column.DisplayFormat))
builder.AddAttribute(seq++, "DisplayFormat", column.DisplayFormat);
if (column.ReadOnly)
builder.AddAttribute(seq++, "ReadOnly", true);
builder.CloseComponent();
}
private void SetEditContext(EditContext context)
{
if (editContext == context) return;
if (editContext != null)
editContext.OnFieldChanged -= OnEditFieldChanged;
editContext = context;
validationMessageStore = new ValidationMessageStore(editContext);
editContext.OnFieldChanged += OnEditFieldChanged;
}
private void OnEditFieldChanged(object? sender, FieldChangedEventArgs e)
protected override void OnEditFieldChanged(object? sender, FieldChangedEventArgs e)
{
if (validationMessageStore == null || editContext == null) return;
@@ -434,8 +220,6 @@ else
}
}
private void SetPopupHeaderText(bool isNew) => popupHeaderText = isNew ? "Neu" : "Edit";
private void OnCustomizeEditModel(GridCustomizeEditModelEventArgs e)
{
popupHeaderText = e.IsNew ? "Neu" : "Edit";
@@ -475,7 +259,7 @@ else
{
CatTitle = editModel.CatTitle,
CatString = editModel.CatString,
UpdateProcedure = editModel.UpdateProcedure
UpdateProcedure = (CatalogUpdateProcedure)editModel.UpdateProcedure
};
try

View File

@@ -31,12 +31,6 @@
<span class="bi bi-table-nav-menu" aria-hidden="true"></span> MassData
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="clock">
<span class="bi bi-clock-nav-menu" aria-hidden="true"></span> Clock
</NavLink>
</div>
</nav>
</div>

View File

@@ -1,5 +1,5 @@
@inject MassDataApiClient Api
@inject BandLayoutService BandLayoutService
@inherits BandGridBase<MassDataReadDto>
@inject IMassDataApiClient Api
@if (!string.IsNullOrWhiteSpace(errorMessage))
{
@@ -25,44 +25,17 @@ else if (items.Count == 0)
else
{
<div class="band-editor">
<button class="band-editor-toggle" @onclick="() => bandEditorExpanded = !bandEditorExpanded">
<span class="band-editor-toggle-icon @(bandEditorExpanded ? "expanded" : "")">&#9658;</span>
<span>Layout</span>
</button>
@if (bandEditorExpanded)
{
<div class="band-editor-body">
<div class="band-controls">
<DxButton Text="Band hinzufügen" Click="AddBand" />
<DxButton Text="Layout speichern" Click="SaveLayoutAsync" Enabled="@CanSaveBandLayout" />
<DxButton Text="Layout zurücksetzen" Click="ResetLayoutAsync" />
</div>
@foreach (var band in bandLayout.Bands)
{
<div class="band-row">
<DxTextBox Text="@band.Caption" TextChanged="@(value => UpdateBandCaption(band, value))" />
<DxButton Text="Entfernen" Click="@(() => RemoveBand(band))" />
</div>
}
<DxFormLayout CssClass="band-columns" ColCount="2">
@foreach (var column in columnDefinitions)
{
<DxFormLayoutItem Caption="@column.Caption">
<DxComboBox Data="@bandOptions"
TData="BandOption"
TValue="string"
TextFieldName="Caption"
ValueFieldName="Id"
Value="@GetColumnBand(column.FieldName)"
ValueChanged="@(value => UpdateColumnBand(column.FieldName, value))"
Width="100%" />
</DxFormLayoutItem>
}
</DxFormLayout>
</div>
}
</div>
<BandEditor Bands="@bandLayout.Bands"
BandOptions="@bandOptions"
Columns="@ColumnDefinitions"
GetColumnBand="GetColumnBand"
CanSave="@CanSaveBandLayout"
OnAddBand="AddBand"
OnSaveLayout="SaveLayoutWithFeedbackAsync"
OnResetLayout="ResetLayoutWithFeedbackAsync"
OnRemoveBand="RemoveBand"
OnBandCaptionChanged="@(args => UpdateBandCaption(args.Band, args.Value))"
OnColumnBandChanged="@(args => UpdateColumnBand(args.FieldName, args.BandId))" />
<div class="mb-3 page-size-selector">
<span class="page-size-label">Datensätze je Seite:</span>
@@ -78,6 +51,7 @@ else
<div class="grid-section">
<DxGrid Data="@items"
ColumnChooserButtonDisplayMode="GridColumnChooserButtonDisplayMode.Always"
TItem="MassDataReadDto"
KeyFieldName="@nameof(MassDataReadDto.Id)"
SizeMode="@_sizeMode"
@@ -98,9 +72,42 @@ else
DataItemDeleting="OnDataItemDeleting"
FocusedRowEnabled="true"
@bind-FocusedRowKey="focusedRowKey"
RowClick="@(args => _focusedVisibleIndex = args.VisibleIndex)"
@ref="gridRef">
<ToolbarTemplate>
<DxToolbar>
<DxToolbarItem Alignment="ToolbarItemAlignment.Left">
<Template Context="_">
<DxButton IconCssClass="bi bi-plus-lg"
RenderStyle="ButtonRenderStyle.Secondary"
RenderStyleMode="ButtonRenderStyleMode.Text"
Click="@(() => gridRef!.StartEditNewRowAsync())" />
</Template>
</DxToolbarItem>
<DxToolbarItem Alignment="ToolbarItemAlignment.Left">
<Template Context="_">
<DxButton IconCssClass="bi bi-pencil"
RenderStyle="ButtonRenderStyle.Secondary"
RenderStyleMode="ButtonRenderStyleMode.Text"
Click="EditFocusedRow" />
</Template>
</DxToolbarItem>
<DxToolbarItem Alignment="ToolbarItemAlignment.Left">
<Template Context="_">
<DxButton IconCssClass="bi bi-trash"
RenderStyle="ButtonRenderStyle.Secondary"
RenderStyleMode="ButtonRenderStyleMode.Text"
Click="DeleteFocusedRow" />
</Template>
</DxToolbarItem>
<DxToolbarItem Alignment="ToolbarItemAlignment.Right">
<Template Context="_">
<DxButton Text="Spalten"
RenderStyle="ButtonRenderStyle.Secondary"
RenderStyleMode="ButtonRenderStyleMode.Text"
Click="@(() => gridRef!.ShowColumnChooser())" />
</Template>
</DxToolbarItem>
<DxToolbarItem Alignment="ToolbarItemAlignment.Right">
<Template Context="_">
<DxDropDownButton Text="@FormatSizeText(_sizeMode)"
@@ -168,38 +175,24 @@ else
@code {
private List<MassDataReadDto> items = new();
private bool isLoading;
private bool hasLoaded;
private string? errorMessage;
private string? infoMessage;
private int pageIndex;
private int pageCount = 1;
private int? pageSize = 100;
private string popupHeaderText = "Edit";
private EditContext? editContext;
private ValidationMessageStore? validationMessageStore;
private IGrid? gridRef;
private int? focusedRowKey;
private const string LayoutType = "GRID_BANDS";
private const string LayoutKey = "MassDataGrid";
private string? layoutUser;
private BandLayout bandLayout = new();
private Dictionary<string, string> columnBandAssignments = new();
private List<BandOption> bandOptions = new();
private Dictionary<string, ColumnDefinition> columnLookup = new();
private bool gridLayoutApplied;
private bool bandEditorExpanded;
private List<ColumnDefinition> columnDefinitions = new()
{
new() { FieldName = nameof(MassDataReadDto.Id), Caption = "Id", Width = "90px", ReadOnly = true, FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(MassDataReadDto.CustomerName), Caption = "CustomerName", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(MassDataReadDto.Amount), Caption = "Amount", DisplayFormat = "c2", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(MassDataReadDto.Category), Caption = "Category", ReadOnly = true, FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(MassDataReadDto.StatusFlag), Caption = "Status", ReadOnly = true, FilterType = ColumnFilterType.Bool },
new() { FieldName = nameof(MassDataReadDto.AddedWhen), Caption = "Added", ReadOnly = true, FilterType = ColumnFilterType.Date },
new() { FieldName = nameof(MassDataReadDto.ChangedWhen), Caption = "Changed", ReadOnly = true, FilterType = ColumnFilterType.Date }
};
protected override string LayoutKey => "MassDataGrid";
protected override bool ShowCommandColumn => false;
protected override List<ColumnDefinition> ColumnDefinitions { get; } = new()
{
new() { FieldName = nameof(MassDataReadDto.Id), Caption = "Id", Width = "90px", ReadOnly = true, FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(MassDataReadDto.CustomerName), Caption = "CustomerName", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(MassDataReadDto.Amount), Caption = "Amount", DisplayFormat = "c2", FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(MassDataReadDto.Category), Caption = "Category", ReadOnly = true, FilterType = ColumnFilterType.Text },
new() { FieldName = nameof(MassDataReadDto.StatusFlag), Caption = "Status", ReadOnly = true, FilterType = ColumnFilterType.Bool },
new() { FieldName = nameof(MassDataReadDto.AddedWhen), Caption = "Added", ReadOnly = true, FilterType = ColumnFilterType.Date },
new() { FieldName = nameof(MassDataReadDto.ChangedWhen), Caption = "Changed", ReadOnly = true, FilterType = ColumnFilterType.Date }
};
private readonly List<PageSizeOption> pageSizeOptions = new()
{
@@ -215,44 +208,15 @@ else
new() { Value = 0, Text = "PRMassdata_UpsertByCustomerName" }
};
private bool CanSaveBandLayout => !string.IsNullOrWhiteSpace(layoutUser);
private SizeMode _sizeMode = SizeMode.Medium;
private static readonly List<SizeMode> _sizeModes = Enum.GetValues<SizeMode>().ToList();
private string FormatSizeText(SizeMode size) => size switch
{
SizeMode.Small => "Klein",
SizeMode.Medium => "Mittel",
SizeMode.Large => "Groß",
_ => size.ToString()
};
private void OnSizeChange(DropDownButtonItemClickEventArgs args)
{
_sizeMode = Enum.Parse<SizeMode>(args.ItemInfo.Id);
}
protected override async Task OnInitializedAsync()
{
columnLookup = columnDefinitions.ToDictionary(c => c.FieldName, StringComparer.OrdinalIgnoreCase);
layoutUser = await BandLayoutService.EnsureLayoutUserAsync();
bandLayout = await BandLayoutService.LoadBandLayoutAsync(LayoutType, LayoutKey, layoutUser, columnLookup);
columnBandAssignments = BandLayoutService.BuildAssignmentsFromLayout(bandLayout);
ApplyColumnLayoutFromStorage();
_sizeMode = bandLayout.SizeMode;
UpdateBandOptions();
await InitializeBandLayoutAsync();
await LoadPage(0);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!gridLayoutApplied && gridRef != null && bandLayout.GridLayout != null)
{
gridRef.LoadLayout(bandLayout.GridLayout);
gridLayoutApplied = true;
await InvokeAsync(StateHasChanged);
}
await ApplyGridLayoutAfterRenderAsync();
}
private async Task LoadPage(int page)
@@ -288,171 +252,7 @@ else
await LoadPage(0);
}
private async Task SaveLayoutAsync()
{
if (string.IsNullOrWhiteSpace(layoutUser))
return;
try
{
CaptureColumnLayoutFromGrid();
await BandLayoutService.SaveBandLayoutAsync(LayoutType, LayoutKey, layoutUser, bandLayout);
infoMessage = "Layout gespeichert.";
errorMessage = null;
}
catch (Exception ex)
{
errorMessage = $"Layout konnte nicht gespeichert werden: {ex.Message}";
}
}
private async Task ResetLayoutAsync()
{
if (string.IsNullOrWhiteSpace(layoutUser))
return;
await BandLayoutService.ResetBandLayoutAsync(LayoutType, LayoutKey, layoutUser);
bandLayout = new BandLayout();
columnBandAssignments.Clear();
UpdateBandOptions();
foreach (var column in columnDefinitions)
column.Width = null;
columnLookup = columnDefinitions.ToDictionary(c => c.FieldName, StringComparer.OrdinalIgnoreCase);
_sizeMode = SizeMode.Medium;
if (gridRef != null)
gridRef.LoadLayout(new GridPersistentLayout());
gridLayoutApplied = false;
infoMessage = "Layout zurückgesetzt.";
errorMessage = null;
}
private void CaptureColumnLayoutFromGrid()
{
if (gridRef == null) return;
var layout = gridRef.SaveLayout();
bandLayout.GridLayout = layout;
bandLayout.SizeMode = _sizeMode;
var orderedColumns = layout.Columns
.Where(c => !string.IsNullOrWhiteSpace(c.FieldName))
.OrderBy(c => c.VisibleIndex)
.ToList();
bandLayout.ColumnOrder = orderedColumns.Select(c => c.FieldName).ToList();
bandLayout.ColumnWidths = orderedColumns
.Where(c => !string.IsNullOrWhiteSpace(c.Width))
.ToDictionary(c => c.FieldName, c => c.Width, StringComparer.OrdinalIgnoreCase);
}
private void ApplyColumnLayoutFromStorage()
{
foreach (var column in columnDefinitions)
{
if (bandLayout.ColumnWidths.TryGetValue(column.FieldName, out var width) && !string.IsNullOrWhiteSpace(width))
column.Width = width;
}
columnLookup = columnDefinitions.ToDictionary(c => c.FieldName, StringComparer.OrdinalIgnoreCase);
}
private void AddBand()
{
bandLayout.Bands.Add(new BandDefinition { Id = Guid.NewGuid().ToString("N"), Caption = "Band" });
UpdateBandOptions();
}
private void RemoveBand(BandDefinition band)
{
bandLayout.Bands.Remove(band);
foreach (var key in columnBandAssignments.Where(p => p.Value == band.Id).Select(p => p.Key).ToList())
columnBandAssignments.Remove(key);
UpdateBandOptions();
SyncBandsFromAssignments();
}
private void UpdateBandCaption(BandDefinition band, string value)
{
band.Caption = value;
UpdateBandOptions();
}
private void UpdateColumnBand(string fieldName, string? bandId)
{
if (string.IsNullOrWhiteSpace(bandId))
columnBandAssignments.Remove(fieldName);
else
columnBandAssignments[fieldName] = bandId;
SyncBandsFromAssignments();
}
private string GetColumnBand(string fieldName)
=> columnBandAssignments.TryGetValue(fieldName, out var bandId) ? bandId : string.Empty;
private void SyncBandsFromAssignments()
{
foreach (var band in bandLayout.Bands)
{
band.Columns = columnDefinitions
.Where(c => columnBandAssignments.TryGetValue(c.FieldName, out var id) && id == band.Id)
.Select(c => c.FieldName)
.ToList();
}
StateHasChanged();
}
private void UpdateBandOptions()
{
bandOptions = new List<BandOption> { new() { Id = string.Empty, Caption = "Ohne Band" } };
bandOptions.AddRange(bandLayout.Bands.Select(b => new BandOption { Id = b.Id, Caption = b.Caption }));
}
private RenderFragment RenderColumns() => builder =>
{
var seq = 0;
builder.OpenComponent<DxGridCommandColumn>(seq++);
builder.AddAttribute(seq++, "Width", "120px");
builder.CloseComponent();
var grouped = bandLayout.Bands.SelectMany(b => b.Columns).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var column in columnDefinitions.Where(c => !grouped.Contains(c.FieldName)))
BuildDataColumn(builder, ref seq, column);
foreach (var band in bandLayout.Bands)
{
if (band.Columns.Count == 0) continue;
builder.OpenComponent<DxGridBandColumn>(seq++);
builder.AddAttribute(seq++, "Caption", band.Caption);
builder.AddAttribute(seq++, "Columns", (RenderFragment)(bandBuilder =>
{
var bandSeq = 0;
foreach (var columnName in band.Columns)
{
if (columnLookup.TryGetValue(columnName, out var column))
BuildDataColumn(bandBuilder, ref bandSeq, column);
}
}));
builder.CloseComponent();
}
};
private void BuildDataColumn(RenderTreeBuilder builder, ref int seq, ColumnDefinition column)
{
builder.OpenComponent<DxGridDataColumn>(seq++);
builder.AddAttribute(seq++, "FieldName", column.FieldName);
builder.AddAttribute(seq++, "Caption", column.Caption);
if (!string.IsNullOrWhiteSpace(column.Width))
builder.AddAttribute(seq++, "Width", column.Width);
if (!string.IsNullOrWhiteSpace(column.DisplayFormat))
builder.AddAttribute(seq++, "DisplayFormat", column.DisplayFormat);
if (column.ReadOnly)
builder.AddAttribute(seq++, "ReadOnly", true);
builder.CloseComponent();
}
private void SetEditContext(EditContext context)
{
if (editContext == context) return;
if (editContext != null)
editContext.OnFieldChanged -= OnEditFieldChanged;
editContext = context;
validationMessageStore = new ValidationMessageStore(editContext);
editContext.OnFieldChanged += OnEditFieldChanged;
}
private void OnEditFieldChanged(object? sender, FieldChangedEventArgs e)
protected override void OnEditFieldChanged(object? sender, FieldChangedEventArgs e)
{
if (validationMessageStore == null || editContext == null) return;
if (e.FieldIdentifier.FieldName == nameof(MassDataEditModel.UpdateProcedure))
@@ -468,9 +268,7 @@ else
}
}
private void SetPopupHeaderText(bool isNew) => popupHeaderText = isNew ? "Neu" : "Edit";
private async Task OnCustomizeEditModel(GridCustomizeEditModelEventArgs e)
private void OnCustomizeEditModel(GridCustomizeEditModelEventArgs e)
{
if (e.IsNew)
{
@@ -523,18 +321,17 @@ else
Category = editModel.Category,
StatusFlag = editModel.StatusFlag
};
try
var result = await Api.UpsertAsync(dto);
if (!result.Success)
{
var saved = await Api.UpsertAsync(dto);
infoMessage = editModel.IsNew ? "MassData angelegt." : "MassData aktualisiert.";
focusedRowKey = saved.Id;
await LoadPage(pageIndex);
}
catch (Exception ex)
{
errorMessage = $"Fehler beim Speichern: {ex.Message}";
errorMessage = result.Error ?? "Speichern fehlgeschlagen.";
e.Cancel = true;
return;
}
infoMessage = editModel.IsNew ? "MassData angelegt." : "MassData aktualisiert.";
focusedRowKey = result.Value?.Id;
await LoadPage(pageIndex);
}
private void AddValidationError(MassDataEditModel editModel, string fieldName, string message)

View File

@@ -1,100 +0,0 @@
@rendermode InteractiveServer
@page "/clock"
@inject TimeApiClient TimeApi
@implements IAsyncDisposable
<PageTitle>Clock</PageTitle>
<h3>DB Server Clock</h3>
<div class="clock-wrapper">
<div class="clock-display @(_error != null ? "clock-error" : "")">
@if (_dbTime.HasValue)
{
<span class="clock-time">@_dbTime.Value.ToString("HH:mm:ss")</span>
<span class="clock-date">@_dbTime.Value.ToString("dd.MM.yyyy")</span>
}
else if (_error != null)
{
<span class="clock-time">--:--:--</span>
<span class="clock-date text-danger">@_error</span>
}
else
{
<span class="clock-time">...</span>
}
</div>
</div>
<style>
.clock-wrapper {
display: flex;
justify-content: center;
align-items: center;
height: 40vh;
}
.clock-display {
display: flex;
flex-direction: column;
align-items: center;
background: var(--bs-body-bg, #1e1e2e);
border: 2px solid var(--bs-border-color, #444);
border-radius: 1rem;
padding: 2rem 4rem;
box-shadow: 0 4px 24px rgba(0,0,0,0.3);
}
.clock-time {
font-size: 5rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
letter-spacing: 0.1em;
color: var(--bs-primary, #0d6efd);
}
.clock-date {
font-size: 1.4rem;
margin-top: 0.5rem;
opacity: 0.75;
}
.clock-error .clock-time {
color: var(--bs-danger, #dc3545);
}
</style>
@code {
private DateTime? _dbTime;
private string? _error;
private Timer? _timer;
protected override async Task OnInitializedAsync()
{
await TickAsync();
_timer = new Timer(async _ =>
{
await TickAsync();
await InvokeAsync(StateHasChanged);
}, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
private async Task TickAsync()
{
try
{
_dbTime = await TimeApi.InsertAndGetLastAsync();
_error = null;
}
catch (Exception ex)
{
_error = ex.Message;
}
}
public async ValueTask DisposeAsync()
{
if (_timer != null)
await _timer.DisposeAsync();
}
}

View File

@@ -1,9 +1,9 @@
@page "/dashboard"
@page "/dashboards/{DashboardId?}"
@implements IAsyncDisposable
@inject Microsoft.Extensions.Configuration.IConfiguration Configuration
@inject IOptions<AppSettings> AppSettingsOptions
@inject NavigationManager Navigation
@inject DashboardApiClient DashboardApi
@inject IDashboardApiClient DashboardApi
<PageTitle>Dashboards</PageTitle>
@@ -45,12 +45,17 @@
private string SelectedDashboardId { get; set; } = string.Empty;
private string DashboardKey => $"{SelectedDashboardId}-{(IsDesigner ? "designer" : "viewer")}";
private string DashboardEndpoint => $"{Configuration["ApiBaseUrl"]?.TrimEnd('/')}/api/dashboard";
private string HubEndpoint => $"{Configuration["ApiBaseUrl"]?.TrimEnd('/')}/hubs/dashboards";
private string DashboardEndpoint => $"{AppSettingsOptions.Value.ApiBaseUrl.TrimEnd('/')}/api/dashboard";
private string HubEndpoint => $"{AppSettingsOptions.Value.ApiBaseUrl.TrimEnd('/')}/hubs/dashboards";
protected override async Task OnInitializedAsync()
{
await RefreshDashboards();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
_hubConnection = new HubConnectionBuilder()
.WithUrl(HubEndpoint)
@@ -67,11 +72,6 @@
protected override async Task OnParametersSetAsync()
{
if (dashboards.Count == 0)
{
await RefreshDashboards();
}
var requestedId = string.IsNullOrWhiteSpace(DashboardId) || string.Equals(DashboardId, "default", StringComparison.OrdinalIgnoreCase)
? null
: DashboardId;

View File

@@ -31,8 +31,8 @@
public class CarouselData
{
public string Source { get; set; }
public string AlternateText { get; set; }
public string Source { get; set; } = string.Empty;
public string AlternateText { get; set; } = string.Empty;
public CarouselData(string source, string alt)
{

View File

@@ -1,19 +1,27 @@
@using System.Net.Http
@using System.Net.Http.Json
@using System.Text.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Rendering
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using Microsoft.AspNetCore.SignalR.Client
@using Microsoft.JSInterop
@using Microsoft.Extensions.Options
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using DbFirst.BlazorWebApp
@using DbFirst.BlazorWebApp.Components
@using DbFirst.BlazorWebApp.Models
@using DbFirst.BlazorWebApp.Models.Grid
@using DbFirst.BlazorWebApp.Services
@using DbFirst.Contracts.Catalogs
@using DbFirst.Contracts.Dashboards
@using DbFirst.Contracts.MassData
@using DbFirst.Contracts.Layouts
@using DbFirst.Domain
@using DevExpress.Blazor
@using DevExpress.DashboardBlazor
@using DevExpress.DashboardWeb

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
@@ -18,4 +18,8 @@
<Folder Include="wwwroot\images\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DbFirst.Contracts\DbFirst.Contracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,7 @@
namespace DbFirst.BlazorWebApp.Models;
public record ApiResult<T>(bool Success, T? Value, string? Error)
{
public static ApiResult<T> Ok(T? value) => new(true, value, null);
public static ApiResult<T> Fail(string? error) => new(false, default, error);
}

View File

@@ -1,12 +0,0 @@
namespace DbFirst.BlazorWebApp.Models;
public class CatalogReadDto
{
public int Guid { get; set; }
public string CatTitle { get; set; } = null!;
public string CatString { get; set; } = null!;
public string AddedWho { get; set; } = null!;
public DateTime AddedWhen { get; set; }
public string? ChangedWho { get; set; }
public DateTime? ChangedWhen { get; set; }
}

View File

@@ -1,8 +0,0 @@
namespace DbFirst.BlazorWebApp.Models;
public class CatalogWriteDto
{
public string CatTitle { get; set; } = string.Empty;
public string CatString { get; set; } = string.Empty;
public int UpdateProcedure { get; set; }
}

View File

@@ -4,8 +4,8 @@ namespace DbFirst.BlazorWebApp.Models.Grid
{
public class BandLayout
{
public List<BandDefinition> Bands { get; set; } = new();
public List<string> ColumnOrder { get; set; } = new();
public List<BandDefinition> Bands { get; set; } = [];
public List<string> ColumnOrder { get; set; } = [];
public Dictionary<string, string?> ColumnWidths { get; set; } = new(StringComparer.OrdinalIgnoreCase);
public GridPersistentLayout? GridLayout { get; set; }
public SizeMode SizeMode { get; set; } = SizeMode.Medium;
@@ -15,7 +15,7 @@ namespace DbFirst.BlazorWebApp.Models.Grid
{
public string Id { get; set; } = string.Empty;
public string Caption { get; set; } = string.Empty;
public List<string> Columns { get; set; } = new();
public List<string> Columns { get; set; } = [];
}
public class BandOption

View File

@@ -1,9 +0,0 @@
namespace DbFirst.BlazorWebApp.Models;
public class MassDataWriteDto
{
public string CustomerName { get; set; } = string.Empty;
public decimal Amount { get; set; }
public string Category { get; set; } = string.Empty;
public bool StatusFlag { get; set; }
}

View File

@@ -1,3 +1,4 @@
using DbFirst.BlazorWebApp;
using DbFirst.BlazorWebApp.Components;
using DbFirst.BlazorWebApp.Services;
using DevExpress.Blazor;
@@ -13,38 +14,18 @@ builder.Services.AddScoped<ThemeState>();
builder.Services.AddScoped<BandLayoutService>();
var apiBaseUrl = builder.Configuration["ApiBaseUrl"];
if (!string.IsNullOrWhiteSpace(apiBaseUrl))
builder.Services.Configure<AppSettings>(builder.Configuration);
void ConfigureClient(HttpClient client)
{
builder.Services.AddHttpClient<CatalogApiClient>(client =>
{
if (!string.IsNullOrWhiteSpace(apiBaseUrl))
client.BaseAddress = new Uri(apiBaseUrl);
});
builder.Services.AddHttpClient<DashboardApiClient>(client =>
{
client.BaseAddress = new Uri(apiBaseUrl);
});
builder.Services.AddHttpClient<MassDataApiClient>(client =>
{
client.BaseAddress = new Uri(apiBaseUrl);
});
builder.Services.AddHttpClient<LayoutApiClient>(client =>
{
client.BaseAddress = new Uri(apiBaseUrl);
});
builder.Services.AddHttpClient<TimeApiClient>(client =>
{
client.BaseAddress = new Uri(apiBaseUrl);
});
}
else
{
builder.Services.AddHttpClient<CatalogApiClient>();
builder.Services.AddHttpClient<DashboardApiClient>();
builder.Services.AddHttpClient<MassDataApiClient>();
builder.Services.AddHttpClient<LayoutApiClient>();
builder.Services.AddHttpClient<TimeApiClient>();
}
builder.Services.AddHttpClient<ICatalogApiClient, CatalogApiClient>(ConfigureClient);
builder.Services.AddHttpClient<IDashboardApiClient, DashboardApiClient>(ConfigureClient);
builder.Services.AddHttpClient<IMassDataApiClient, MassDataApiClient>(ConfigureClient);
builder.Services.AddHttpClient<ILayoutApiClient, LayoutApiClient>(ConfigureClient);
var app = builder.Build();
// Configure the HTTP request pipeline.

View File

@@ -0,0 +1,59 @@
using System.Net;
namespace DbFirst.BlazorWebApp.Services;
internal sealed class ProblemDetailsDto
{
public string? Type { get; set; }
public string? Title { get; set; }
public string? Detail { get; set; }
}
internal static class ApiClientHelper
{
public static async Task<string> ReadErrorAsync(HttpResponseMessage response)
{
string? problemTitle = null;
string? problemDetail = null;
try
{
var problem = await response.Content.ReadFromJsonAsync<ProblemDetailsDto>();
if (problem != null)
{
problemTitle = problem.Title;
problemDetail = problem.Detail ?? problem.Type;
}
}
catch { }
var status = response.StatusCode;
var reason = response.ReasonPhrase;
var body = await response.Content.ReadAsStringAsync();
string? detail = problemDetail;
if (string.IsNullOrWhiteSpace(detail) && !string.IsNullOrWhiteSpace(body))
detail = body;
return status switch
{
HttpStatusCode.BadRequest => $"Eingabe ungültig{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.NotFound => $"Nicht gefunden{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.Conflict => $"Konflikt{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.Unauthorized => $"Nicht autorisiert{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.Forbidden => $"Nicht erlaubt{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.InternalServerError => $"Serverfehler{FormatSuffix(problemTitle, detail, reason)}",
_ => $"Fehler {(int)status} {reason ?? string.Empty}{FormatSuffix(problemTitle, detail, reason)}"
};
}
private static string FormatSuffix(string? title, string? detail, string? reason)
{
var parts = new List<string>();
if (!string.IsNullOrWhiteSpace(title)) parts.Add(title);
if (!string.IsNullOrWhiteSpace(detail)) parts.Add(detail);
if (parts.Count == 0 && !string.IsNullOrWhiteSpace(reason)) parts.Add(reason);
if (parts.Count == 0) return string.Empty;
return ": " + string.Join(" | ", parts);
}
}

View File

@@ -1,24 +1,30 @@
using DbFirst.BlazorWebApp.Models;
using DbFirst.BlazorWebApp.Models.Grid;
using DbFirst.BlazorWebApp.Models.Grid;
using DbFirst.Contracts.Layouts;
using Microsoft.JSInterop;
using System.Text.Json;
namespace DbFirst.BlazorWebApp.Services
{
public class BandLayoutService(LayoutApiClient layoutApi, IJSRuntime jsRuntime)
public class BandLayoutService(ILayoutApiClient layoutApi, IJSRuntime jsRuntime)
{
private const string LayoutUserStorageKey = "layoutUser";
private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
private string? _cachedLayoutUser;
public async Task<string> EnsureLayoutUserAsync()
{
if (!string.IsNullOrWhiteSpace(_cachedLayoutUser))
return _cachedLayoutUser;
var layoutUser = await jsRuntime.InvokeAsync<string?>("localStorage.getItem", LayoutUserStorageKey);
if (string.IsNullOrWhiteSpace(layoutUser))
{
layoutUser = Guid.NewGuid().ToString("N");
await jsRuntime.InvokeVoidAsync("localStorage.setItem", LayoutUserStorageKey, layoutUser);
}
return layoutUser;
_cachedLayoutUser = layoutUser;
return _cachedLayoutUser;
}
public async Task<BandLayout> LoadBandLayoutAsync(
@@ -82,9 +88,9 @@ namespace DbFirst.BlazorWebApp.Services
Dictionary<string, ColumnDefinition> columnLookup)
{
layout ??= new BandLayout();
layout.Bands ??= new List<BandDefinition>();
layout.ColumnOrder ??= new List<string>();
layout.ColumnWidths ??= new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
layout.Bands ??= [];
layout.ColumnOrder ??= [];
layout.ColumnWidths ??= [];
foreach (var band in layout.Bands)
{

View File

@@ -1,10 +1,9 @@
using System.Net;
using System.Net.Http.Json;
using DbFirst.BlazorWebApp.Models;
using DbFirst.Contracts.Catalogs;
namespace DbFirst.BlazorWebApp.Services;
public class CatalogApiClient
public class CatalogApiClient : ICatalogApiClient
{
private readonly HttpClient _httpClient;
private const string Endpoint = "api/catalogs";
@@ -14,123 +13,51 @@ public class CatalogApiClient
_httpClient = httpClient;
}
public async Task<List<CatalogReadDto>> GetAllAsync()
public async Task<List<CatalogReadDto>> GetAllAsync(CancellationToken ct = default)
{
var result = await _httpClient.GetFromJsonAsync<List<CatalogReadDto>>(Endpoint);
return result ?? new List<CatalogReadDto>();
var result = await _httpClient.GetFromJsonAsync<List<CatalogReadDto>>(Endpoint, ct);
return result ?? [];
}
public async Task<CatalogReadDto?> GetByIdAsync(int id)
public async Task<CatalogReadDto?> GetByIdAsync(int id, CancellationToken ct = default)
{
return await _httpClient.GetFromJsonAsync<CatalogReadDto>($"{Endpoint}/{id}");
return await _httpClient.GetFromJsonAsync<CatalogReadDto>($"{Endpoint}/{id}", ct);
}
public async Task<ApiResult<CatalogReadDto?>> CreateAsync(CatalogWriteDto dto)
public async Task<ApiResult<CatalogReadDto?>> CreateAsync(CatalogWriteDto dto, CancellationToken ct = default)
{
var response = await _httpClient.PostAsJsonAsync(Endpoint, dto);
var response = await _httpClient.PostAsJsonAsync(Endpoint, dto, ct);
if (response.IsSuccessStatusCode)
{
var payload = await response.Content.ReadFromJsonAsync<CatalogReadDto>();
return ApiResult<CatalogReadDto?>.Ok(payload);
}
var error = await ReadErrorAsync(response);
var error = await ApiClientHelper.ReadErrorAsync(response);
return ApiResult<CatalogReadDto?>.Fail(error);
}
public async Task<ApiResult<bool>> UpdateAsync(int id, CatalogWriteDto dto)
public async Task<ApiResult<bool>> UpdateAsync(int id, CatalogWriteDto dto, CancellationToken ct = default)
{
var response = await _httpClient.PutAsJsonAsync($"{Endpoint}/{id}", dto);
var response = await _httpClient.PutAsJsonAsync($"{Endpoint}/{id}", dto, ct);
if (response.IsSuccessStatusCode)
{
return ApiResult<bool>.Ok(true);
}
var error = await ReadErrorAsync(response);
var error = await ApiClientHelper.ReadErrorAsync(response);
return ApiResult<bool>.Fail(error);
}
public async Task<ApiResult<bool>> DeleteAsync(int id)
public async Task<ApiResult<bool>> DeleteAsync(int id, CancellationToken ct = default)
{
var response = await _httpClient.DeleteAsync($"{Endpoint}/{id}");
var response = await _httpClient.DeleteAsync($"{Endpoint}/{id}", ct);
if (response.IsSuccessStatusCode)
{
return ApiResult<bool>.Ok(true);
}
var error = await ReadErrorAsync(response);
var error = await ApiClientHelper.ReadErrorAsync(response);
return ApiResult<bool>.Fail(error);
}
private static async Task<string> ReadErrorAsync(HttpResponseMessage response)
{
string? problemTitle = null;
string? problemDetail = null;
try
{
var problem = await response.Content.ReadFromJsonAsync<ProblemDetailsDto>();
if (problem != null)
{
problemTitle = problem.Title;
problemDetail = problem.Detail ?? problem.Type;
}
}
catch
{
}
var status = response.StatusCode;
var reason = response.ReasonPhrase;
var body = await response.Content.ReadAsStringAsync();
string? detail = problemDetail;
if (string.IsNullOrWhiteSpace(detail) && !string.IsNullOrWhiteSpace(body))
{
detail = body;
}
if (status == HttpStatusCode.Conflict)
{
return "Datensatz existiert bereits. Bitte wählen Sie einen anderen Titel.";
}
if (status == HttpStatusCode.BadRequest && (detail?.Contains("CatTitle cannot be changed", StringComparison.OrdinalIgnoreCase) ?? false))
{
return "Titel kann nicht geändert werden.";
}
return status switch
{
HttpStatusCode.BadRequest => $"Eingabe ungültig{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.NotFound => $"Nicht gefunden{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.Conflict => $"Konflikt{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.Unauthorized => $"Nicht autorisiert{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.Forbidden => $"Nicht erlaubt{FormatSuffix(problemTitle, detail, reason)}",
HttpStatusCode.InternalServerError => $"Serverfehler{FormatSuffix(problemTitle, detail, reason)}",
_ => $"Fehler {(int)status} {reason ?? string.Empty}{FormatSuffix(problemTitle, detail, reason)}"
};
}
private static string FormatSuffix(string? title, string? detail, string? reason)
{
var parts = new List<string>();
if (!string.IsNullOrWhiteSpace(title)) parts.Add(title);
if (!string.IsNullOrWhiteSpace(detail)) parts.Add(detail);
if (parts.Count == 0 && !string.IsNullOrWhiteSpace(reason)) parts.Add(reason);
if (parts.Count == 0) return string.Empty;
return ": " + string.Join(" | ", parts);
}
}
public record ApiResult<T>(bool Success, T? Value, string? Error)
{
public static ApiResult<T> Ok(T? value) => new(true, value, null);
public static ApiResult<T> Fail(string? error) => new(false, default, error);
}
internal sealed class ProblemDetailsDto
{
public string? Type { get; set; }
public string? Title { get; set; }
public string? Detail { get; set; }
}

View File

@@ -1,9 +1,8 @@
using System.Net.Http.Json;
using DbFirst.BlazorWebApp.Models;
using DbFirst.Contracts.Dashboards;
namespace DbFirst.BlazorWebApp.Services;
public class DashboardApiClient
public class DashboardApiClient : IDashboardApiClient
{
private readonly HttpClient _httpClient;
private const string Endpoint = "api/dashboard/dashboards";
@@ -13,9 +12,9 @@ public class DashboardApiClient
_httpClient = httpClient;
}
public async Task<List<DashboardInfoDto>> GetAllAsync()
public async Task<List<DashboardInfoDto>> GetAllAsync(CancellationToken ct = default)
{
var result = await _httpClient.GetFromJsonAsync<List<DashboardInfoDto>>(Endpoint);
return result ?? new List<DashboardInfoDto>();
var result = await _httpClient.GetFromJsonAsync<List<DashboardInfoDto>>(Endpoint, ct);
return result ?? [];
}
}

View File

@@ -0,0 +1,13 @@
using DbFirst.BlazorWebApp.Models;
using DbFirst.Contracts.Catalogs;
namespace DbFirst.BlazorWebApp.Services;
public interface ICatalogApiClient
{
Task<List<CatalogReadDto>> GetAllAsync(CancellationToken ct = default);
Task<CatalogReadDto?> GetByIdAsync(int id, CancellationToken ct = default);
Task<ApiResult<CatalogReadDto?>> CreateAsync(CatalogWriteDto dto, CancellationToken ct = default);
Task<ApiResult<bool>> UpdateAsync(int id, CatalogWriteDto dto, CancellationToken ct = default);
Task<ApiResult<bool>> DeleteAsync(int id, CancellationToken ct = default);
}

View File

@@ -0,0 +1,9 @@
using DbFirst.Contracts.Dashboards;
namespace DbFirst.BlazorWebApp.Services
{
public interface IDashboardApiClient
{
Task<List<DashboardInfoDto>> GetAllAsync(CancellationToken ct = default);
}
}

View File

@@ -0,0 +1,11 @@
using DbFirst.Contracts.Layouts;
namespace DbFirst.BlazorWebApp.Services
{
public interface ILayoutApiClient
{
Task<LayoutDto?> GetAsync(string layoutType, string layoutKey, string userName, CancellationToken ct = default);
Task<LayoutDto> UpsertAsync(LayoutDto dto, CancellationToken ct = default);
Task DeleteAsync(string layoutType, string layoutKey, string userName, CancellationToken ct = default);
}
}

View File

@@ -0,0 +1,13 @@
using DbFirst.BlazorWebApp.Models;
using DbFirst.Contracts.MassData;
namespace DbFirst.BlazorWebApp.Services
{
public interface IMassDataApiClient
{
Task<int> GetCountAsync(CancellationToken ct = default);
Task<List<MassDataReadDto>> GetAllAsync(int? skip, int? take, CancellationToken ct = default);
Task<ApiResult<MassDataReadDto?>> UpsertAsync(MassDataWriteDto dto, CancellationToken ct = default);
Task<MassDataReadDto?> GetByCustomerNameAsync(string customerName, CancellationToken ct = default);
}
}

View File

@@ -1,9 +1,8 @@
using System.Net.Http.Json;
using DbFirst.BlazorWebApp.Models;
using DbFirst.Contracts.Layouts;
namespace DbFirst.BlazorWebApp.Services;
public class LayoutApiClient
public class LayoutApiClient : ILayoutApiClient
{
private readonly HttpClient _httpClient;
private const string Endpoint = "api/layouts";
@@ -13,10 +12,10 @@ public class LayoutApiClient
_httpClient = httpClient;
}
public async Task<LayoutDto?> GetAsync(string layoutType, string layoutKey, string userName)
public async Task<LayoutDto?> GetAsync(string layoutType, string layoutKey, string userName, CancellationToken ct = default)
{
var url = $"{Endpoint}?layoutType={Uri.EscapeDataString(layoutType)}&layoutKey={Uri.EscapeDataString(layoutKey)}&userName={Uri.EscapeDataString(userName)}";
var response = await _httpClient.GetAsync(url);
var response = await _httpClient.GetAsync(url, ct);
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
@@ -26,12 +25,12 @@ public class LayoutApiClient
return await response.Content.ReadFromJsonAsync<LayoutDto>();
}
public async Task<LayoutDto> UpsertAsync(LayoutDto dto)
public async Task<LayoutDto> UpsertAsync(LayoutDto dto, CancellationToken ct = default)
{
var response = await _httpClient.PostAsJsonAsync(Endpoint, dto);
var response = await _httpClient.PostAsJsonAsync(Endpoint, dto, ct);
if (!response.IsSuccessStatusCode)
{
var detail = await ReadErrorAsync(response);
var detail = await ApiClientHelper.ReadErrorAsync(response);
throw new InvalidOperationException(detail);
}
@@ -39,21 +38,10 @@ public class LayoutApiClient
return payload ?? dto;
}
private static async Task<string> ReadErrorAsync(HttpResponseMessage response)
{
var body = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrWhiteSpace(body))
{
return body;
}
return $"{(int)response.StatusCode} {response.ReasonPhrase}".Trim();
}
public async Task DeleteAsync(string layoutType, string layoutKey, string userName)
public async Task DeleteAsync(string layoutType, string layoutKey, string userName, CancellationToken ct = default)
{
var url = $"{Endpoint}?layoutType={Uri.EscapeDataString(layoutType)}&layoutKey={Uri.EscapeDataString(layoutKey)}&userName={Uri.EscapeDataString(userName)}";
var response = await _httpClient.DeleteAsync(url);
var response = await _httpClient.DeleteAsync(url, ct);
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return;

View File

@@ -1,9 +1,9 @@
using System.Net.Http.Json;
using DbFirst.BlazorWebApp.Models;
using DbFirst.Contracts.MassData;
namespace DbFirst.BlazorWebApp.Services;
public class MassDataApiClient
public class MassDataApiClient : IMassDataApiClient
{
private readonly HttpClient _httpClient;
private const string Endpoint = "api/massdata";
@@ -13,13 +13,13 @@ public class MassDataApiClient
_httpClient = httpClient;
}
public async Task<int> GetCountAsync()
public async Task<int> GetCountAsync(CancellationToken ct = default)
{
var result = await _httpClient.GetFromJsonAsync<int?>("api/massdata/count");
var result = await _httpClient.GetFromJsonAsync<int?>("api/massdata/count", ct);
return result ?? 0;
}
public async Task<List<MassDataReadDto>> GetAllAsync(int? skip, int? take)
public async Task<List<MassDataReadDto>> GetAllAsync(int? skip, int? take, CancellationToken ct = default)
{
var query = new List<string>();
if (skip.HasValue)
@@ -32,26 +32,31 @@ public class MassDataApiClient
}
var url = query.Count == 0 ? Endpoint : $"{Endpoint}?{string.Join("&", query)}";
var result = await _httpClient.GetFromJsonAsync<List<MassDataReadDto>>(url);
return result ?? new List<MassDataReadDto>();
var result = await _httpClient.GetFromJsonAsync<List<MassDataReadDto>>(url, ct);
return result ?? [];
}
public async Task<MassDataReadDto> UpsertAsync(MassDataWriteDto dto)
public async Task<ApiResult<MassDataReadDto?>> UpsertAsync(MassDataWriteDto dto, CancellationToken ct = default)
{
var response = await _httpClient.PostAsJsonAsync($"{Endpoint}/upsert", dto);
response.EnsureSuccessStatusCode();
var payload = await response.Content.ReadFromJsonAsync<MassDataReadDto>();
return payload ?? new MassDataReadDto();
var response = await _httpClient.PostAsJsonAsync($"{Endpoint}/upsert", dto, ct);
if (response.IsSuccessStatusCode)
{
var payload = await response.Content.ReadFromJsonAsync<MassDataReadDto>();
return ApiResult<MassDataReadDto?>.Ok(payload);
}
var error = await ApiClientHelper.ReadErrorAsync(response);
return ApiResult<MassDataReadDto?>.Fail(error);
}
public async Task<MassDataReadDto?> GetByCustomerNameAsync(string customerName)
public async Task<MassDataReadDto?> GetByCustomerNameAsync(string customerName, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(customerName))
{
return null;
}
var response = await _httpClient.GetAsync($"{Endpoint}/{Uri.EscapeDataString(customerName)}");
var response = await _httpClient.GetAsync($"{Endpoint}/{Uri.EscapeDataString(customerName)}", ct);
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;

View File

@@ -1,27 +0,0 @@
using System.Net.Http.Json;
namespace DbFirst.BlazorWebApp.Services;
public class TimeApiClient
{
private readonly HttpClient _httpClient;
private const string Endpoint = "api/time";
public TimeApiClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<DateTime?> InsertAndGetLastAsync()
{
var response = await _httpClient.PostAsync(Endpoint, null);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<TimeResponse>();
return result?.Now;
}
private sealed class TimeResponse
{
public DateTime? Now { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
namespace DbFirst.Contracts.Catalogs;
public class CatalogReadDto
{
public int Guid { get; set; }
public string CatTitle { get; set; } = string.Empty;
public string CatString { get; set; } = string.Empty;
public string AddedWho { get; set; } = string.Empty;
public DateTime AddedWhen { get; set; }
public string? ChangedWho { get; set; }
public DateTime? ChangedWhen { get; set; }
}

View File

@@ -0,0 +1,10 @@
using DbFirst.Domain;
namespace DbFirst.Contracts.Catalogs;
public class CatalogWriteDto
{
public string CatTitle { get; set; } = string.Empty;
public string CatString { get; set; } = string.Empty;
public CatalogUpdateProcedure UpdateProcedure { get; set; } = CatalogUpdateProcedure.Update;
}

View File

@@ -1,4 +1,4 @@
namespace DbFirst.BlazorWebApp.Models;
namespace DbFirst.Contracts.Dashboards;
public class DashboardInfoDto
{

View File

@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DbFirst.Domain\DbFirst.Domain.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,4 +1,4 @@
namespace DbFirst.BlazorWebApp.Models;
namespace DbFirst.Contracts.Layouts;
public class LayoutDto
{

View File

@@ -1,4 +1,4 @@
namespace DbFirst.BlazorWebApp.Models;
namespace DbFirst.Contracts.MassData;
public class MassDataReadDto
{

View File

@@ -1,4 +1,4 @@
namespace DbFirst.Application.MassData;
namespace DbFirst.Contracts.MassData;
public class MassDataWriteDto
{

View File

@@ -1,6 +0,0 @@
namespace DbFirst.Domain.Entities;
public class TimeRecord
{
public DateTime? Now { get; set; }
}

View File

@@ -4,11 +4,11 @@ public partial class VwmyCatalog
{
public int Guid { get; set; }
public string CatTitle { get; set; } = null!;
public string CatTitle { get; set; } = string.Empty;
public string CatString { get; set; } = null!;
public string CatString { get; set; } = string.Empty;
public string AddedWho { get; set; } = null!;
public string AddedWho { get; set; } = string.Empty;
public DateTime AddedWhen { get; set; }

View File

@@ -16,7 +16,6 @@ public partial class ApplicationDbContext : DbContext
public virtual DbSet<VwmyCatalog> VwmyCatalogs { get; set; }
public virtual DbSet<SmfLayout> SmfLayouts { get; set; }
public virtual DbSet<TimeRecord> Times { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -84,16 +83,6 @@ public partial class ApplicationDbContext : DbContext
.HasColumnName("CHANGED_WHEN");
});
modelBuilder.Entity<TimeRecord>(entity =>
{
entity.HasNoKey();
entity.ToTable("TIME");
entity.Property(e => e.Now)
.HasColumnType("datetime")
.HasColumnName("NOW");
});
OnModelCreatingPartial(modelBuilder);
}

View File

@@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.22" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.22" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.22">
@@ -15,7 +15,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
</ItemGroup>

View File

@@ -1,3 +1,5 @@
using DbFirst.Application.Repositories;
using DbFirst.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -15,6 +17,10 @@ public static class DependencyInjection
services.AddDbContext<MassDataDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("MassDataConnection")));
services.AddScoped<ICatalogRepository, CatalogRepository>();
services.AddScoped<IMassDataRepository, MassDataRepository>();
services.AddScoped<ILayoutRepository, LayoutRepository>();
return services;
}
}

View File

@@ -1,6 +1,6 @@
using DbFirst.Application.Repositories;
using DbFirst.Domain;
using DbFirst.Domain.Entities;
using DbFirst.Application.Repositories;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Data;

View File

@@ -34,7 +34,7 @@ public class LayoutRepository : ILayoutRepository
UserName = userName,
LayoutData = layoutData,
AddedWho = userName,
AddedWhen = DateTime.Now
AddedWhen = DateTime.UtcNow
};
_db.SmfLayouts.Add(entity);
}

View File

@@ -1,8 +1,8 @@
using System.Data;
using DbFirst.Application.Repositories;
using DbFirst.Domain.Entities;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Data;
namespace DbFirst.Infrastructure.Repositories;
@@ -20,11 +20,6 @@ public class MassDataRepository : IMassDataRepository
return await _db.Massdata.AsNoTracking().CountAsync(cancellationToken);
}
public async Task<List<Massdata>> GetAllAsync(CancellationToken cancellationToken = default)
{
return await _db.Massdata.AsNoTracking().ToListAsync(cancellationToken);
}
public async Task<Massdata?> GetByCustomerNameAsync(string customerName, CancellationToken cancellationToken = default)
{
return await _db.Massdata.AsNoTracking()

View File

@@ -1,28 +0,0 @@
using DbFirst.Application.Repositories;
using DbFirst.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace DbFirst.Infrastructure.Repositories;
public class TimeRepository : ITimeRepository
{
private readonly ApplicationDbContext _db;
public TimeRepository(ApplicationDbContext db)
{
_db = db;
}
public async Task InsertAsync(CancellationToken cancellationToken = default)
{
await _db.Database.ExecuteSqlRawAsync("INSERT INTO [TIME] (NOW) VALUES (GETDATE())", cancellationToken);
}
public async Task<TimeRecord?> GetLastAsync(CancellationToken cancellationToken = default)
{
return await _db.Times
.AsNoTracking()
.OrderByDescending(t => t.Now)
.FirstOrDefaultAsync(cancellationToken);
}
}

View File

@@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbFirst.Domain", "DbFirst.D
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbFirst.BlazorWebApp", "DbFirst.BlazorWebApp\DbFirst.BlazorWebApp.csproj", "{FF1D77C4-A13D-43E0-BCE1-C18C01F1767C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbFirst.Contracts", "DbFirst.Contracts\DbFirst.Contracts.csproj", "{94FFCA01-9476-49B3-B7D0-5706514E42E4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -83,6 +85,18 @@ Global
{FF1D77C4-A13D-43E0-BCE1-C18C01F1767C}.Release|x64.Build.0 = Release|Any CPU
{FF1D77C4-A13D-43E0-BCE1-C18C01F1767C}.Release|x86.ActiveCfg = Release|Any CPU
{FF1D77C4-A13D-43E0-BCE1-C18C01F1767C}.Release|x86.Build.0 = Release|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Debug|x64.ActiveCfg = Debug|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Debug|x64.Build.0 = Debug|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Debug|x86.ActiveCfg = Debug|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Debug|x86.Build.0 = Debug|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Release|Any CPU.Build.0 = Release|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Release|x64.ActiveCfg = Release|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Release|x64.Build.0 = Release|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Release|x86.ActiveCfg = Release|Any CPU
{94FFCA01-9476-49B3-B7D0-5706514E42E4}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

1157
docs/PROJEKTDOKUMENTATION.md Normal file

File diff suppressed because it is too large Load Diff