@using System.Text.Json
@using MudBlazor
@using Microsoft.AspNetCore.Components.Forms
Import Order JSON
@if (ShowWarning)
{
Only valid VDA 5050 Order JSON is accepted.
Invalid structure will be rejected.
}
@if (!string.IsNullOrEmpty(ErrorMessage))
{
@ErrorMessage
}
Cancel
Import
@code {
[CascadingParameter]
public IMudDialogInstance MudDialog { get; set; } = default!;
public string JsonText { get; set; } = "";
public string? ErrorMessage;
public bool ShowWarning { get; set; }
private void Cancel() => MudDialog.Cancel();
// ================= FILE HANDLER =================
private async Task OnFileSelected(InputFileChangeEventArgs e)
{
ErrorMessage = null;
ShowWarning = false;
var file = e.File;
if (file == null)
return;
if (!file.Name.EndsWith(".json", StringComparison.OrdinalIgnoreCase) &&
!file.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
{
ShowWarning = true;
ErrorMessage = "Only .json or .txt files are supported.";
return;
}
try
{
using var stream = file.OpenReadStream(maxAllowedSize: 1_048_576);
using var reader = new StreamReader(stream);
JsonText = await reader.ReadToEndAsync();
StateHasChanged();
}
catch (Exception ex)
{
ShowWarning = true;
ErrorMessage = $"Failed to read file: {ex.Message}";
}
}
// ================= VALIDATE & IMPORT =================
private void ValidateAndImport()
{
ErrorMessage = null;
ShowWarning = false;
if (string.IsNullOrWhiteSpace(JsonText))
{
ShowWarning = true;
ErrorMessage = "JSON content is empty.";
return;
}
try
{
var order = JsonSerializer.Deserialize(JsonText, new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
});
if(order is null)
{
ShowWarning = true;
ErrorMessage = "Can not convert file to Order message";
return;
}
ValidateOrder(order);
MudDialog.Close(DialogResult.Ok(order));
}
catch (JsonException)
{
ShowWarning = true;
ErrorMessage = "Invalid JSON format.";
}
catch (Exception ex)
{
ShowWarning = true;
ErrorMessage = ex.Message;
}
}
// ================= DOMAIN VALIDATION =================
private void ValidateOrder(OrderMsg order)
{
if (order.Nodes.Length == 0)
throw new Exception("Order must contain at least one node.");
if (order.Nodes.Length != order.Edges.Length + 1)
throw new Exception(
$"Invalid path structure: Nodes count ({order.Nodes.Length}) " +
$"must equal Edges count + 1 ({order.Edges.Length + 1})."
);
var nodeIds = order.Nodes
.Select(n => n.NodeId)
.ToHashSet(StringComparer.Ordinal);
foreach (var e in order.Edges)
{
if (string.IsNullOrWhiteSpace(e.StartNodeId) ||
string.IsNullOrWhiteSpace(e.EndNodeId))
{
throw new Exception(
$"Edge '{e.EdgeId}' must define both StartNodeId and EndNodeId."
);
}
if (!nodeIds.Contains(e.StartNodeId))
throw new Exception(
$"Edge '{e.EdgeId}' references unknown StartNodeId '{e.StartNodeId}'."
);
if (!nodeIds.Contains(e.EndNodeId))
throw new Exception(
$"Edge '{e.EdgeId}' references unknown EndNodeId '{e.EndNodeId}'."
);
}
}
}