First code upload

This commit is contained in:
Iker Larraona Sancho
2025-07-15 10:46:04 +02:00
commit b59a08ba3c
22 changed files with 977 additions and 0 deletions

398
.gitignore vendored Normal file
View File

@@ -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

21
LICENSE Normal file
View File

@@ -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.

48
README.md Normal file
View File

@@ -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": "<Filepath>\\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
```

37
SimpleServiceManager.sln Normal file
View File

@@ -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

View File

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

View File

@@ -0,0 +1,16 @@
using ServiceWrapper;
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSystemd()
.ConfigureAppConfiguration(conf =>
{
conf.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
})
.ConfigureServices(services =>
{
services.AddHostedService<ServiceManager>();
})
.ConfigureLogging((hostingContext, logging) => logging.AddLog4Net("log4net.config"))
.Build();
await host.RunAsync(Token.MyToken.Token);

View File

@@ -0,0 +1,11 @@
{
"profiles": {
"ServiceWrapper": {
"commandName": "Project",
"dotnetRunMessages": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,188 @@
using System.Diagnostics;
namespace ServiceWrapper
{
public class ServiceManager : BackgroundService
{
private readonly ILogger<ServiceManager> _logger;
public IConfigurationRoot Configuration { get; set; }
public ServiceManager(ILogger<ServiceManager> 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;
}
}
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dotnet-WorkerService1-92015219-54f2-40dc-85bf-115948b467e8</UserSecretsId>
<PublishSingleFile>true</PublishSingleFile>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="log4net" Version="2.0.17" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="8.0.0" />
<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="System.Configuration.ConfigurationManager" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="Logs/log_%date{yyyyMMdd}.txt" />
<rollingStyle value="Date" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10000KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %utcdate{yyyy-MM-dd HH:mm:ss.fff} UTC %logger [%thread] - [%property{activityid}] %message %exception%newline" />
</layout>
</appender>
<root>
<appender-ref ref="RollingFileAppender" />
<level value="Error" />
</root>
</log4net>

View File

@@ -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<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();
}
}
}

35
TestAPI/Program.cs Normal file
View File

@@ -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();
}
}
}

View File

@@ -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"
}
}
}
}

13
TestAPI/TestAPI.csproj Normal file
View File

@@ -0,0 +1,13 @@
<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

@@ -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; }
}
}

View File

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

9
TestAPI/appsettings.json Normal file
View File

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

27
TestConsoleApp/Program.cs Normal file
View File

@@ -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.");
}

View File

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