Skip to content

Instantly share code, notes, and snippets.

@vsetchinfc
Last active August 27, 2019 10:11
Sample code for blog posts
<pre class="code-font" style="background-color: #f5f6f7; border: 1px solid rgb(210, 211, 215); font-size: 13px; font-weight: normal; line-height: 2em; overflow: auto; padding: 1em; vertical-align: baseline; word-wrap: break-word;">
</pre>
<ItemGroup>
<None Include="nlog.config" CopyToOutputDirectory="Always" />
<ItemGroup>
using System;
using System.Diagnostics;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Process oProcess = Process.GetCurrentProcess( );
Console.WriteLine( string.Format( "Process: {0} ({1})",
oProcess.ProcessName, oProcess.Id ) );
Console.WriteLine( );
Console.WriteLine( "MODULES:" );
Console.WriteLine( "________" );
foreach ( ProcessModule oModule in oProcess.Modules )
{
Console.WriteLine( string.Format( "{0} ({1})",
oModule.ModuleName, oModule.FileName ) );
}
}
}
}
using System;
namespace dotnetcore_nlog
{
class Program
{
private static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
log.Trace("Loggin trace.");
}
}
}
namespace VSC
{
internal class HostedService
{
}
}
<script src="https://gist.github.com/[you_github_username]/[paste name from script tag].js?file=FileName">
</script>
<ItemGroup>
<PackageReference Include="nlog" Version="4.5.6" />
</ItemGroup>
<xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogFile="console-example-internal.log"
internalLogLevel="Info" >
<targets>
<target xsi:type="File" name="file"
fileName="console-example.log"
layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
<target xsi:type="Console" name="console"
layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file,console" />
</rules>
</nlog>
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info">
<extensions>
<add assembly="Google.Cloud.Logging.NLog"/>
</extensions>
<!-- the targets to write to -->
<targets>
<target name="asyncConsole" xsi:type="AsyncWrapper">
<target name="console"
xsi:type="ColoredConsole"
layout="${date} ${threadname:whenEmpty=${threadid}} ${level:uppercase=true} ${logger} ${message} ${onexception:${exception}}" />
</target>
<target name="asyncStackDriver" xsi:type="AsyncWrapper">
<target name="stackDriver"
xsi:type="GoogleStackdriver"
logId="Default"
layout="${longdate}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
</target>
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs-->
<logger name="*" minlevel="Trace" writeTo="asyncConsole" />
<logger name="*" minlevel="Trace" writeTo="asyncStackDriver" />
<logger name="Microsoft.*" maxLevel="Info" final="true" /> <!-- BlackHole without writeTo -->
</rules>
</nlog>
static void Main(string[] args)
{
Logger logger = LogManager.GetCurrentClassLogger();
// Log some information. This log entry will be sent to Google Stackdriver Logging.
logger.Info("An exciting log entry for Google Cloud!");
// Flush buffered log entries before program exit; then shutdown the logger before program exit.
LogManager.Flush(TimeSpan.FromSeconds(15));
LogManager.Shutdown();
}
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace VSC.Services
{
public class SampleService : IHostedService, IDisposable
{
public void Dispose()
{
// TODO: Do service clean up here
}
public Task StartAsync(CancellationToken cancellationToken)
{
// TODO: Do work here
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
// stop service processes here
return Task.CompletedTask;
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Information"
}
}
}
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Hosting;
namespace VSC
{
class Program
{
static async Task Main(string[] args)
{
IHostBuilder hostBuilder = CreateHostBuilder(args);
if(hostBuilder != null)
{
IHost host = hostBuilder.Build();
await host.RunAsync();
}
}
private static IHostBuilder CreateHostBuilder(string[] args)
{
try
{
var builder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: true);
config.AddJsonFile(
$"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json",
optional: true);
config.AddCommandLine(args);
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Services.SampleService>();
services.Configure<HostOptions>(option =>
{
option.ShutdownTimeout = System.TimeSpan.FromSeconds(20);
});
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
});
return builder;
}
catch { }
return null;
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target name="asyncLogFile" xsi:type="AsyncWrapper">
<target
xsi:type="File"
name="logfile"
fileName="log/log-${shortdate}.txt"
archiveFileName="log/archive/log-${shortdate}.txt"
keepFileOpen="true"
archiveAboveSize="20000000"
concurrentWrites="false"
archiveEvery="Day"
layout="${longdate}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
</target>
<target name="asyncConsole" xsi:type="AsyncWrapper">
<target name="console" xsi:type="ColoredConsole"
layout="${date} ${threadname:whenEmpty=${threadid}} ${level:uppercase=true} ${logger} ${message} ${onexception:${exception}}" />
</target>
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs-->
<logger name="*" minlevel="Trace" writeTo="asyncLogFile" />
<logger name="*" minlevel="Info" writeTo="asyncConsole" />
<logger name="Microsoft.*" maxLevel="Info" final="true" /> <!-- BlackHole without writeTo -->
</rules>
</nlog>
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
<add assembly="Google.Cloud.Logging.NLog"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target name="asyncLogFile" xsi:type="AsyncWrapper">
<target
xsi:type="File"
name="logfile"
fileName="log/log-${shortdate}.txt"
archiveFileName="log/archive/log-${shortdate}.txt"
keepFileOpen="true"
archiveAboveSize="20000000"
concurrentWrites="false"
archiveEvery="Day"
layout="${longdate}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
</target>
<target name="asyncConsole" xsi:type="AsyncWrapper">
<target name="console" xsi:type="ColoredConsole"
layout="${date} ${threadname:whenEmpty=${threadid}} ${level:uppercase=true} ${logger} ${message} ${onexception:${exception}}" />
</target>
<target name="asyncStackDriver" xsi:type="AsyncWrapper">
<target name="stackDriver"
xsi:type="GoogleStackdriver"
logId="Default"
layout="${longdate}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
</target>
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs-->
<logger name="*" minlevel="Trace" writeTo="asyncLogFile" />
<logger name="*" minlevel="Info" writeTo="asyncConsole" />
<logger name="*" minlevel="Trace" writeTo="asyncStackDriver" />
<logger name="Microsoft.*" maxLevel="Info" final="true" /> <!-- BlackHole without writeTo -->
</rules>
</nlog>
<ItemGroup>
<PackageReference Include="Google.Cloud.Logging.NLog" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
<PackageReference Include="nlog" Version="4.6.6" />
<PackageReference Include="NLog.Extensions.Hosting" Version="1.5.2" />
</ItemGroup>
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace VSC.Services
{
public class SampleService : IHostedService, IDisposable
{
private CancellationTokenSource _cancellationTokenSource;
private Task _executingTask;
ILogger<SampleService> _logger;
public SampleService(
ILogger<SampleService> logger
)
{
_logger = logger;
}
public void Dispose()
{
// TODO: Do service clean up here
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogTrace("SampleService StartAsync method called.");
_cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_executingTask = Run(_cancellationTokenSource.Token);
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogTrace("SampleService StopAsync method called.");
// Stop called without start
if (_executingTask == null)
{
return;
}
// stop service processes here
_cancellationTokenSource.Cancel();
_logger.LogInformation("Sample Service stopped.");
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken));
}
private async Task Run(CancellationToken cancellationToken)
{
_logger.LogTrace("Starting iteration count Run");
await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken);
int iterationCount = 0;
while (!cancellationToken.IsCancellationRequested)
{
iterationCount++;
_logger.LogInformation(string.Format("Running round {0}", iterationCount));
await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);
}
}
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace VSC.Services
{
public class SampleService : IHostedService, IDisposable
{
private CancellationTokenSource _cancellationTokenSource;
private Task _executingTask;
IApplicationLifetime _appLifetime;
ILogger<SampleService> _logger;
public SampleService(
ILogger<SampleService> logger,
IApplicationLifetime appLifetime
)
{
_logger = logger;
_appLifetime = appLifetime;
}
public void Dispose()
{
// TODO: Do service clean up here
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogTrace("SampleService StartAsync method called.");
_appLifetime.ApplicationStarted.Register(OnStarted);
_appLifetime.ApplicationStopping.Register(OnStopping);
_appLifetime.ApplicationStopped.Register(OnStopped);
_cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_executingTask = Run(_cancellationTokenSource.Token);
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogTrace("SampleService StopAsync method called.");
// Stop called without start
if (_executingTask == null)
{
return;
}
// stop service processes here
_cancellationTokenSource.Cancel();
_logger.LogInformation("Sample Service stopped.");
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken));
}
private void OnStarted()
{
_logger.LogTrace("SampleService OnStarted method called.");
// Post-startup code goes here
}
private void OnStopping()
{
_logger.LogTrace("SampleService OnStopping method called.");
// On-stopping code goes here
}
private void OnStopped()
{
_logger.LogTrace("SampleService OnStopped method called.");
// Post-stopped code goes here
}
private async Task Run(CancellationToken cancellationToken)
{
_logger.LogTrace("Starting iteration count Run");
await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken);
int iterationCount = 0;
while (!cancellationToken.IsCancellationRequested)
{
iterationCount++;
_logger.LogInformation(string.Format("Running round {0}", iterationCount));
await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);
}
}
}
}
Public Class InputBoxValidated
Public Function InputBoxValidated _
(
prompt As String,
title As String,
Optional stringValidator As IStringValidator = Nothing,
Optional validationMessage As String = ""
) As String
Dim value As String _
= Microsoft.VisualBasic.Interaction.InputBox(prompt, title)
' If the cancel button wasn't pressed
' And IStringValidator is passed with validation message
If Not value = String.Empty AndAlso stringValidator IsNot Nothing _
AndAlso Not String.IsNullOrEmpty(validationMessage) Then
If Not stringValidator.Validate(value) Then
MessageBox.Show(validationMessage, Application.ProductName)
value = InputBoxValidated(
prompt, title, stringValidator, validationMessage)
End If
End If
Return value
End Function
End Class
Public Interface IStringValidator
Function Validate(value As String) As Boolean
End Interface
Public Class StringValidator
Implements IStringValidator
Public Sub New(maxLength As Integer, invalidCharacters As String)
Me.MaxLength = maxLength
Me.InvalidCharacters = invalidCharacters
End Sub
Public Property MaxLength As Integer
Public Property InvalidCharacters As String
Public Function Validate(value As String) _
As Boolean Implements IStringValidator.Validate
Dim valid As Boolean = True
Try
Dim stringValidator As _
New System.Configuration.StringValidator _
(0, MaxLength, InvalidCharacters)
If stringValidator.CanValidate(value.GetType()) Then
stringValidator.Validate(value)
Else
valid = False
End If
Catch ex As ArgumentException
valid = False
End Try
Return valid
End Function
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment