using System.Text.Json; using Sonex.Data.Records; namespace Sonex.Library.WorkersCore; public static partial class Worker { public static WorkerInfoRecord Registration( bool ensureWindowsServiceInConsole = false, string serviceStartMode = "auto", string? serviceDescription = null) { if (ensureWindowsServiceInConsole) { ServiceRegistrationResult serviceRegistration = EnsureWindowsServiceExistsDetailed( serviceName: Name, displayName: Title, startMode: serviceStartMode, description: serviceDescription); if (!serviceRegistration.Success) { LogError( $"Windows service registration failed for worker '{Name}'. Details={serviceRegistration.Message}", "WorkerServiceRegistration"); } else if (serviceRegistration.IsWarning) { LogInfo( $"Windows service registration warning for worker '{Name}'. Details={serviceRegistration.Message}", "WorkerServiceRegistrationWarning"); } } var workerInfo = new WorkerInfoRecord { Name = Name, Title = Title, Description = Description, AppVersion = ResolveAppVersion(), ExePath = Environment.ProcessPath ?? string.Empty, WorkType = WorkType.ToString(), Status = Status.ToString(), Activity = Activity, Progress = Progress, ProgressInfo = ProgressInfo, Parameters = JsonSerializer.SerializeToElement(Parameters) }; var registrationResult = ExecuteDatabaseSingleWithRetry( ct => WorkerInfoRecord.RegisterAsync(workerInfo, ct), "WorkerRegistration"); if (registrationResult.Success) { ApplyRegisteredParameters(workerInfo.Parameters); } else { LogError($"Worker registration failed: {registrationResult.ErrorMessage}", "WorkerRegistration"); } return workerInfo; } private static void ApplyRegisteredParameters(JsonElement registeredParameters) { if (registeredParameters.ValueKind != JsonValueKind.Array) return; var valuesByKey = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (JsonElement item in registeredParameters.EnumerateArray()) { if (!item.TryGetProperty("Parametr", out JsonElement keyElement)) continue; string key = keyElement.GetString() ?? string.Empty; if (string.IsNullOrWhiteSpace(key)) continue; string? value = null; if (item.TryGetProperty("Value", out JsonElement valueElement) && valueElement.ValueKind != JsonValueKind.Null) { value = valueElement.GetString(); } valuesByKey[key] = value; } foreach (WorkerParameter parameter in Parameters) { if (!valuesByKey.TryGetValue(parameter.Parametr, out string? value)) continue; parameter.Value = value; } } }