Removed unused programs

This commit is contained in:
Iker Larraona Sancho
2025-07-18 13:39:32 +02:00
parent 0ba33dc592
commit d5af90bb02
20 changed files with 204 additions and 363 deletions

View File

@@ -5,10 +5,6 @@ VisualStudioVersion = 17.10.34916.146
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleServiceManager", "SimpleServiceManager\SimpleServiceManager.csproj", "{DC6A5EB5-3439-43DD-8D01-76D04687D5A8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestAPI", "TestAPI\TestAPI.csproj", "{CCA1171F-87EC-49E2-A0D9-27D1D4D1A568}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestConsoleApp", "TestConsoleApp\TestConsoleApp.csproj", "{7E84B7CD-D293-45F0-943C-27226450B217}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -19,14 +15,6 @@ Global
{DC6A5EB5-3439-43DD-8D01-76D04687D5A8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC6A5EB5-3439-43DD-8D01-76D04687D5A8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DC6A5EB5-3439-43DD-8D01-76D04687D5A8}.Release|Any CPU.Build.0 = Release|Any CPU
{CCA1171F-87EC-49E2-A0D9-27D1D4D1A568}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CCA1171F-87EC-49E2-A0D9-27D1D4D1A568}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CCA1171F-87EC-49E2-A0D9-27D1D4D1A568}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CCA1171F-87EC-49E2-A0D9-27D1D4D1A568}.Release|Any CPU.Build.0 = Release|Any CPU
{7E84B7CD-D293-45F0-943C-27226450B217}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7E84B7CD-D293-45F0-943C-27226450B217}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7E84B7CD-D293-45F0-943C-27226450B217}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7E84B7CD-D293-45F0-943C-27226450B217}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -0,0 +1,37 @@
using System.Text.Json.Serialization;
namespace SimpleServiceManager
{
/// <summary>
/// Represents the overall structure of the configuration file, acting as the root wrapper.
/// This class is necessary to map the top-level "Configuration" key in your JSON.
/// </summary>
public class ServiceConfigurationWrapper
{
[JsonPropertyName("Configuration")] // Maps the JSON key "Configuration" to this property
public Configuration Configuration { get; set; }
}
/// <summary>
/// Represents the 'Configuration' section of the configuration, now acting as the root.
/// </summary>
public class Configuration
{
public string AppPath { get; set; }
public string WorkingDir { get; set; }
public string AppParams { get; set; }
public bool RestartAppAutomatically { get; set; }
public int RestartDelay { get; set; }
public List<EnvironmentVariableItem> EnvironmentVariables { get; set; }
}
/// <summary>
/// Represents an individual environment variable item within the 'EnvironmentVariables' array.
/// </summary>
public class EnvironmentVariableItem
{
public string Name { get; set; }
public string Value { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
{
"Configuration": {
"AppPath": "notepad.exe",
"WorkingDir": "",
"AppParams": "",
"RestartAppAutomatically": true,
"RestartDelay": 5000,
"EnvironmentVariables": [
{
"Name": "PATH",
"Value": "c:\\Ruby31-x64\\bin"
},
{
"Name": "RAILS_RELATIVE_URL_ROOT",
"Value": "/redmine"
}
]
}
}

View File

@@ -1,11 +0,0 @@
namespace ServiceWrapper
{
public class Logging
{
private ILoggerFactory loggerFactory;
private ILogger logger;
public IConfigurationRoot configuration { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
using System.Diagnostics;
using System.Management;
public static class ProcessExtensions
{
public static IEnumerable<Process> GetChildProcesses(this Process process)
{
List<Process> children = new List<Process>();
var mos = new ManagementObjectSearcher(string.Format("Select * From Win32_Process Where ParentProcessID={0}", process.Id));
foreach (ManagementObject mo in mos.Get())
{
children.Add(Process.GetProcessById(Convert.ToInt32(mo["ProcessID"])));
}
return children;
}
}

View File

@@ -1,16 +1,53 @@
using ServiceWrapper;
using Newtonsoft.Json;
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSystemd()
.ConfigureAppConfiguration(conf =>
namespace SimpleServiceManager
{
public class Program
{
conf.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
})
.ConfigureServices(services =>
{
services.AddHostedService<ServiceManager>();
})
.ConfigureLogging((hostingContext, logging) => logging.AddLog4Net("log4net.config"))
.Build();
await host.RunAsync(Token.MyToken.Token);
public static async Task Main(string[] args)
{
using CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken cancellationToken = cts.Token;
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSystemd()
.ConfigureAppConfiguration(conf =>
{
conf.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
})
.ConfigureServices(services =>
{
var config = BuildConfig();
services.AddSingleton(config);
services.AddHostedService<ServiceManager>();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
logging.AddLog4Net("log4net.config");
})
.Build();
await host.RunAsync(cancellationToken);
}
public static Configuration BuildConfig()
{
var currentPath = Path.GetDirectoryName(Environment.ProcessPath) ?? AppDomain.CurrentDomain.BaseDirectory;
var config = JsonConvert.DeserializeObject<ServiceConfigurationWrapper>(
File.ReadAllText(Path.Combine(currentPath, "Configuration.json"))
);
if (config == null || config.Configuration == null)
{
throw new InvalidOperationException("Configuration is missing or invalid in Configuration.json");
}
return config.Configuration;
}
}
}

View File

@@ -1,106 +1,77 @@
using Newtonsoft.Json;
using System.Collections.Specialized;
using System.Diagnostics;
namespace ServiceWrapper
namespace SimpleServiceManager
{
public class ServiceManager : BackgroundService
{
private Process? _innerProcess;
private readonly ILogger<ServiceManager> _logger;
public IConfigurationRoot Configuration { get; set; }
private readonly Configuration _configuration;
public ServiceManager(ILogger<ServiceManager> logger, IConfiguration config)
public ServiceManager(ILogger<ServiceManager> logger, Configuration config)
{
ArgumentNullException.ThrowIfNull(logger, nameof(logger));
ArgumentNullException.ThrowIfNull(config, nameof(config));
_logger = logger;
Configuration = (IConfigurationRoot)config;
}
private string GetAppParams()
{
string retval = null;
string tempath = Configuration.GetSection("Configs:AppParams").Value.ToString();
if (!String.IsNullOrEmpty(tempath))
{
retval = tempath;
}
else
{
_logger.LogInformation("no AppParams : {time}", DateTimeOffset.Now);
}
return retval;
_configuration = config;
CheckConfig(config);
}
private string GetPath()
public void CheckConfig(Configuration config)
{
string retval = null;
string tempath = Configuration.GetSection("Configs:AppPath").Value.ToString();
if (!String.IsNullOrEmpty(tempath))
if (config.RestartDelay < 1000)
{
if (CheckPath(tempath))
{
retval = Path.GetFullPath(tempath);
}
_logger.LogCritical($"Restart Delay cannot be lower than 1000. Currently configuration is {config.RestartDelay}");
config.RestartDelay = 1000;
}
else
if (string.IsNullOrEmpty(config.AppPath))
{
_logger.LogInformation("Simple Service Manager Exception Wrong APP path : {time}", DateTimeOffset.Now);
_logger.LogError($"AppPath is null or empty, service will end now");
throw new ArgumentNullException(nameof(config.AppPath), "AppPath cannot be null or empty.");
}
return retval;
_logger.LogDebug(JsonConvert.SerializeObject(config));
}
public string GetFileName(string path)
private Process? StartProcess()
{
if (CheckPath(path))
var processInfo = new ProcessStartInfo
{
return Path.GetFileName(path);
}
else
WorkingDirectory = _configuration.WorkingDir,
FileName = _configuration.AppPath,
Arguments = _configuration.AppParams,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
_configuration.EnvironmentVariables.ForEach(envVar =>
{
if (!string.IsNullOrEmpty(envVar.Name) && !string.IsNullOrEmpty(envVar.Value))
{
processInfo.EnvironmentVariables[envVar.Name] = envVar.Value;
}
});
string fileExtension = Path.GetExtension(_configuration.AppPath);
var process = Process.Start(processInfo);
if (process == null)
{
_logger.LogError("Failed to start process: {appPath}", _configuration.AppPath);
return null;
}
}
private bool CheckPath(string path)
{
return File.Exists(path);
}
private void StartProcess(string filePath, string appParams, string workingDir)
{
_logger.LogInformation("Starting process with filePath: {filePath}, appParams: {appParams}, " +
"workingDir: {workingDir}", filePath, appParams, workingDir);
string fileExtension = Path.GetExtension(filePath);
if (fileExtension.ToLower() == ".ps1")
{
var processInfo = new ProcessStartInfo
{
WorkingDirectory = workingDir,
FileName = "powershell.exe",
Arguments = $"-File \"{filePath}\" {appParams}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = new Process { StartInfo = processInfo })
{
process.Start();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
}
}
else
{
var processInfo = new ProcessStartInfo
{
WorkingDirectory = workingDir,
FileName = filePath,
Arguments = appParams,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
Process.Start(processInfo);
process.ErrorDataReceived += TraceOutput;
}
return process;
}
private void TraceOutput(object sender, DataReceivedEventArgs e)
@@ -108,72 +79,54 @@ namespace ServiceWrapper
_logger.LogError("Error: {error}", e.Data ?? "");
}
// Executes the service asynchronously, starting a process defined by the file path obtained from GetPath.
// The process is monitored by checking if it is running every second.
// If the process stops, the service is also stopped.
// Logs the start, running status, and stop of the service along with any errors encountered.
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
public override void Dispose()
{
#if (DEBUG)
System.Diagnostics.Debugger.Launch();
#endif
Process? myProc;
string filePath = GetPath();
string appParams = GetAppParams();
//string fileName = GetFileName(filePath);
string fileName = Path.GetFileNameWithoutExtension(filePath);
bool restartAppAutomatically = bool.Parse(Configuration.GetSection("Configs:RestartAppAutomatically").Value.ToString());
int restartDelay = int.Parse(Configuration.GetSection("Configs:RestartDelay").Value.ToString());
string workingDir = Configuration.GetSection("Configs:WorkingDir").Value ?? ".";
// Add null check for filePath and fileName
if (filePath == null || fileName == null)
_logger.LogInformation("Simple Service Manager killed at: {time}", DateTimeOffset.Now);
if (_innerProcess != null)
{
return;
var children = _innerProcess.GetChildProcesses();
_innerProcess.Kill();
foreach(var child in children)
{
child?.Kill();
}
_logger.LogInformation("Simple Service Manager killed server at: {time}", DateTimeOffset.Now);
}
base.Dispose();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Simple Service Manager starting");
try
{
StartProcess(filePath, appParams, workingDir);
await Task.Delay(1000, stoppingToken);//1 sec delay before looping
_innerProcess = StartProcess();
_logger.LogInformation("Simple Service Manager started running at: {time}", DateTimeOffset.Now);
bool isProcessRunning = false;
while (!stoppingToken.IsCancellationRequested)
{
myProc = Process.GetProcessesByName(fileName).FirstOrDefault();
if (myProc != null) //check if "fileName" is running every 1 sec
if (_innerProcess != null && !_innerProcess.HasExited)
{
await Task.Delay(TimeSpan.FromSeconds(1));
if (!isProcessRunning)
{
_logger.LogInformation("Process is running");
isProcessRunning = true;
}
_logger.LogDebug($"Process is running with PID {_innerProcess.Id}");
}
else
{
if (restartAppAutomatically)
if (_configuration.RestartAppAutomatically)
{
_logger.LogInformation("Process stopped, restarting in {delay} milliseconds", restartDelay);
await Task.Delay(TimeSpan.FromMilliseconds(restartDelay));
StartProcess(filePath, appParams, workingDir);
_logger.LogInformation("Process stopped, restarting in {delay} milliseconds", _configuration.RestartDelay);
await Task.Delay(TimeSpan.FromMilliseconds(_configuration.RestartDelay));
_innerProcess = StartProcess();
continue;
}
Token.MyToken.Cancel();
_logger.LogInformation("Process stopped");
break; //"fileName" process stopped so service is also stopped
break;
}
}
_logger.LogInformation("Simple Service Manager killed at: {time}", DateTimeOffset.Now);
myProc = Process.GetProcessesByName(fileName).FirstOrDefault();
if (myProc != null)
{
myProc.Kill();//Kill "fileName" If service is stopping.
_logger.LogInformation("Simple Service Manager killed server at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken); // Wait for 1 second before checking again
}
}
catch (Exception ex)
@@ -182,7 +135,5 @@ namespace ServiceWrapper
throw;
}
}
}
}

View File

@@ -16,11 +16,13 @@
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="8.0.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="8.0.0" />
<PackageReference Include="System.Management" Version="9.0.7" />
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<Content Update="Configuration.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>

View File

@@ -1,4 +0,0 @@
public class Token
{
public static CancellationTokenSource MyToken { get; private set; } = new CancellationTokenSource();
}

View File

@@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@@ -1,9 +0,0 @@
{
"Configs": {
"AppPath": "<Filepath>\\TestAPI.exe",
"WorkingDir": "<WorkingDir>",
"AppParams": "", //"param1 param2 param3 param4 \"param with quotes\" param5",
"RestartAppAutomatically": false,
"RestartDelay": 5000
}
}

View File

@@ -1,33 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace TestAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

View File

@@ -1,35 +0,0 @@
namespace TestAPI
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}

View File

@@ -1,31 +0,0 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:35224",
"sslPort": 44371
}
},
"profiles": {
"TestAPI": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7036;http://localhost:5013",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project>

View File

@@ -1,13 +0,0 @@
namespace TestAPI
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}

View File

@@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -1,9 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@@ -1,27 +0,0 @@
// See https://aka.ms/new-console-template for more information
#if (DEBUG)
System.Diagnostics.Debugger.Launch();
#endif
string logFilePath = "C:\\test\\log.txt";
if (args.Length > 0)
{
using (StreamWriter writer = new StreamWriter(logFilePath, true))
{
foreach (string parameter in args)
{
writer.WriteLine("Parameter: " + parameter);
}
}
//Console.WriteLine("Parameters written to log file.");
}
else
{
using (StreamWriter writer = new StreamWriter(logFilePath, true))
{
writer.WriteLine("No parameters provided.");
}
//Console.WriteLine("No parameters provided. Logged to log file.");
}

View File

@@ -1,10 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>