From b59a08ba3c9fbaa318e736e6b26d81f607fe57e3 Mon Sep 17 00:00:00 2001 From: Iker Larraona Sancho Date: Tue, 15 Jul 2025 10:46:04 +0200 Subject: [PATCH] First code upload --- .gitignore | 398 ++++++++++++++++++ LICENSE | 21 + README.md | 48 +++ SimpleServiceManager.sln | 37 ++ SimpleServiceManager/Logging.cs | 11 + SimpleServiceManager/Program.cs | 16 + .../Properties/launchSettings.json | 11 + SimpleServiceManager/SimpleServiceManager.cs | 188 +++++++++ .../SimpleServiceManager.csproj | 27 ++ SimpleServiceManager/Token.cs | 4 + .../appsettings.Development.json | 8 + SimpleServiceManager/appsettings.json | 9 + SimpleServiceManager/log4net.config | 20 + .../Controllers/WeatherForecastController.cs | 33 ++ TestAPI/Program.cs | 35 ++ TestAPI/Properties/launchSettings.json | 31 ++ TestAPI/TestAPI.csproj | 13 + TestAPI/WeatherForecast.cs | 13 + TestAPI/appsettings.Development.json | 8 + TestAPI/appsettings.json | 9 + TestConsoleApp/Program.cs | 27 ++ TestConsoleApp/TestConsoleApp.csproj | 10 + 22 files changed, 977 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 SimpleServiceManager.sln create mode 100644 SimpleServiceManager/Logging.cs create mode 100644 SimpleServiceManager/Program.cs create mode 100644 SimpleServiceManager/Properties/launchSettings.json create mode 100644 SimpleServiceManager/SimpleServiceManager.cs create mode 100644 SimpleServiceManager/SimpleServiceManager.csproj create mode 100644 SimpleServiceManager/Token.cs create mode 100644 SimpleServiceManager/appsettings.Development.json create mode 100644 SimpleServiceManager/appsettings.json create mode 100644 SimpleServiceManager/log4net.config create mode 100644 TestAPI/Controllers/WeatherForecastController.cs create mode 100644 TestAPI/Program.cs create mode 100644 TestAPI/Properties/launchSettings.json create mode 100644 TestAPI/TestAPI.csproj create mode 100644 TestAPI/WeatherForecast.cs create mode 100644 TestAPI/appsettings.Development.json create mode 100644 TestAPI/appsettings.json create mode 100644 TestConsoleApp/Program.cs create mode 100644 TestConsoleApp/TestConsoleApp.csproj diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8a30d25 --- /dev/null +++ b/.gitignore @@ -0,0 +1,398 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c6e6311 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Koleys + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d572683 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ + + +# SSM: Simple Service Manager : Run any Windows application as a Service an NSSM alternative + +## Features: +* .NET 8 alternative of NSSM (the Non-Sucking Service Manager), srvany and other service helper programs. +* Automatically handles failure of the application running as a service. +* Continuously monitors the Windows application status. +* If says it's running, it really is. +* Service automatically stops if the launched application exits. +* Service Logs all errors in log files to help torubleshoot the issues. + +## Added new features in v1.1.0 + +- **Additional parameters** "AppParams". +- **Restart App Automatically** "RestartAppAutomatically". +- **Restart Delay** "RestartDelay". +- Apart form .exe files can run both .bat and .ps1 fiels as well. +## Download +- Download from the link [Release V1.1.0](https://github.com/koleys/SimpleServiceManager/releases/download/v1.1.0/SimpleServiceManager1.1.0.zip) + +## Installation +- Extract **SimpleServiceManager.zip** in an accessible folder on your system. + +- Modify the **appsettings.json file** with the path to your Application.exe which you want to run as service +```json +{ + "Configs": { + "AppPath": "\\TestAPI.exe", //can not be null + "AppParams": "", //"param1 param2 param3 param4 param5", + "RestartAppAutomatically": false, //can not be null + "RestartDelay": 5000 //can not be null. Min 1000 ms + } +} +``` +- Install it as a service from an **Elevated (Administrator) Command Prompt**: +```winbatch +sc create "MyServiceName" start= auto binPath= "C:\Path\To\SimpleServiceManager.exe" +sc description MyServiceName "My services description" +sc start MyServiceName +``` +Note the spaces between `start=`, `binPath=` and their parameters. This is intended. + +## Uninstallation +```winbatch +sc stop MyServiceName +sc delete MyServiceName +``` diff --git a/SimpleServiceManager.sln b/SimpleServiceManager.sln new file mode 100644 index 0000000..7af6836 --- /dev/null +++ b/SimpleServiceManager.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +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 + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DC6A5EB5-3439-43DD-8D01-76D04687D5A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {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 + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {8870E886-CB95-4581-B6BE-CF0BF514A189} + EndGlobalSection +EndGlobal diff --git a/SimpleServiceManager/Logging.cs b/SimpleServiceManager/Logging.cs new file mode 100644 index 0000000..0f8bc28 --- /dev/null +++ b/SimpleServiceManager/Logging.cs @@ -0,0 +1,11 @@ +namespace ServiceWrapper +{ + public class Logging + { + private ILoggerFactory loggerFactory; + private ILogger logger; + public IConfigurationRoot configuration { get; set; } + + } + +} diff --git a/SimpleServiceManager/Program.cs b/SimpleServiceManager/Program.cs new file mode 100644 index 0000000..d20d023 --- /dev/null +++ b/SimpleServiceManager/Program.cs @@ -0,0 +1,16 @@ +using ServiceWrapper; + +IHost host = Host.CreateDefaultBuilder(args) + .UseWindowsService() + .UseSystemd() + .ConfigureAppConfiguration(conf => + { + conf.SetBasePath(AppDomain.CurrentDomain.BaseDirectory); + }) + .ConfigureServices(services => + { + services.AddHostedService(); + }) + .ConfigureLogging((hostingContext, logging) => logging.AddLog4Net("log4net.config")) + .Build(); +await host.RunAsync(Token.MyToken.Token); diff --git a/SimpleServiceManager/Properties/launchSettings.json b/SimpleServiceManager/Properties/launchSettings.json new file mode 100644 index 0000000..19e33d2 --- /dev/null +++ b/SimpleServiceManager/Properties/launchSettings.json @@ -0,0 +1,11 @@ +{ + "profiles": { + "ServiceWrapper": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Development" + } + } + } +} diff --git a/SimpleServiceManager/SimpleServiceManager.cs b/SimpleServiceManager/SimpleServiceManager.cs new file mode 100644 index 0000000..3510e3a --- /dev/null +++ b/SimpleServiceManager/SimpleServiceManager.cs @@ -0,0 +1,188 @@ +using System.Diagnostics; + +namespace ServiceWrapper +{ + public class ServiceManager : BackgroundService + { + private readonly ILogger _logger; + public IConfigurationRoot Configuration { get; set; } + + public ServiceManager(ILogger logger, IConfiguration 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; + } + + private string GetPath() + { + string retval = null; + string tempath = Configuration.GetSection("Configs:AppPath").Value.ToString(); + if (!String.IsNullOrEmpty(tempath)) + { + if (CheckPath(tempath)) + { + retval = Path.GetFullPath(tempath); + } + } + else + { + _logger.LogInformation("Simple Service Manager Exception Wrong APP path : {time}", DateTimeOffset.Now); + } + return retval; + } + public string GetFileName(string path) + { + if (CheckPath(path)) + { + return Path.GetFileName(path); + } + else + { + 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); + } + } + + private void TraceOutput(object sender, DataReceivedEventArgs e) + { + _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) + { +#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) + { + return; + } + + _logger.LogInformation("Simple Service Manager starting"); + try + { + StartProcess(filePath, appParams, workingDir); + await Task.Delay(1000, stoppingToken);//1 sec delay before looping + _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 + { + await Task.Delay(TimeSpan.FromSeconds(1)); + + if (!isProcessRunning) + { + _logger.LogInformation("Process is running"); + isProcessRunning = true; + } + } + else + { + if (restartAppAutomatically) + { + _logger.LogInformation("Process stopped, restarting in {delay} milliseconds", restartDelay); + await Task.Delay(TimeSpan.FromMilliseconds(restartDelay)); + StartProcess(filePath, appParams, workingDir); + continue; + } + Token.MyToken.Cancel(); + _logger.LogInformation("Process stopped"); + break; //"fileName" process stopped so service is also stopped + } + } + + _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); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "An error occurred in SimpleServiceManager"); + throw; + } + } + + + } +} diff --git a/SimpleServiceManager/SimpleServiceManager.csproj b/SimpleServiceManager/SimpleServiceManager.csproj new file mode 100644 index 0000000..5a0062c --- /dev/null +++ b/SimpleServiceManager/SimpleServiceManager.csproj @@ -0,0 +1,27 @@ + + + + net8.0 + enable + enable + dotnet-WorkerService1-92015219-54f2-40dc-85bf-115948b467e8 + true + win-x64 + + + + + + + + + + + + + + + Always + + + diff --git a/SimpleServiceManager/Token.cs b/SimpleServiceManager/Token.cs new file mode 100644 index 0000000..c88d7a7 --- /dev/null +++ b/SimpleServiceManager/Token.cs @@ -0,0 +1,4 @@ +public class Token +{ + public static CancellationTokenSource MyToken { get; private set; } = new CancellationTokenSource(); +} \ No newline at end of file diff --git a/SimpleServiceManager/appsettings.Development.json b/SimpleServiceManager/appsettings.Development.json new file mode 100644 index 0000000..b2dcdb6 --- /dev/null +++ b/SimpleServiceManager/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/SimpleServiceManager/appsettings.json b/SimpleServiceManager/appsettings.json new file mode 100644 index 0000000..cc12737 --- /dev/null +++ b/SimpleServiceManager/appsettings.json @@ -0,0 +1,9 @@ +{ + "Configs": { + "AppPath": "\\TestAPI.exe", + "WorkingDir": "", + "AppParams": "", //"param1 param2 param3 param4 \"param with quotes\" param5", + "RestartAppAutomatically": false, + "RestartDelay": 5000 + } +} diff --git a/SimpleServiceManager/log4net.config b/SimpleServiceManager/log4net.config new file mode 100644 index 0000000..ac187ff --- /dev/null +++ b/SimpleServiceManager/log4net.config @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/TestAPI/Controllers/WeatherForecastController.cs b/TestAPI/Controllers/WeatherForecastController.cs new file mode 100644 index 0000000..4ea6207 --- /dev/null +++ b/TestAPI/Controllers/WeatherForecastController.cs @@ -0,0 +1,33 @@ +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 _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet(Name = "GetWeatherForecast")] + public IEnumerable 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(); + } + } +} diff --git a/TestAPI/Program.cs b/TestAPI/Program.cs new file mode 100644 index 0000000..68fe01e --- /dev/null +++ b/TestAPI/Program.cs @@ -0,0 +1,35 @@ +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(); + } + } +} diff --git a/TestAPI/Properties/launchSettings.json b/TestAPI/Properties/launchSettings.json new file mode 100644 index 0000000..b55571a --- /dev/null +++ b/TestAPI/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$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" + } + } + } +} diff --git a/TestAPI/TestAPI.csproj b/TestAPI/TestAPI.csproj new file mode 100644 index 0000000..137bb2c --- /dev/null +++ b/TestAPI/TestAPI.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/TestAPI/WeatherForecast.cs b/TestAPI/WeatherForecast.cs new file mode 100644 index 0000000..2eb1767 --- /dev/null +++ b/TestAPI/WeatherForecast.cs @@ -0,0 +1,13 @@ +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; } + } +} diff --git a/TestAPI/appsettings.Development.json b/TestAPI/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/TestAPI/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/TestAPI/appsettings.json b/TestAPI/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/TestAPI/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/TestConsoleApp/Program.cs b/TestConsoleApp/Program.cs new file mode 100644 index 0000000..87bd104 --- /dev/null +++ b/TestConsoleApp/Program.cs @@ -0,0 +1,27 @@ +// 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."); +} \ No newline at end of file diff --git a/TestConsoleApp/TestConsoleApp.csproj b/TestConsoleApp/TestConsoleApp.csproj new file mode 100644 index 0000000..2150e37 --- /dev/null +++ b/TestConsoleApp/TestConsoleApp.csproj @@ -0,0 +1,10 @@ + + + + Exe + net8.0 + enable + enable + + +