Friday, 22 June 2018

Dotnet Core console app with NLOG in Visual Studio Code

In this post I am going to create simple minimalistic dotnet core console application and integrate it with nlog.

Let's create a folder for our project. I am going to name it nlog_console.

$mkdir nlog_console
$cd nlog_console

Now we create dotnet core console app project and if you have Visual Studio Code installed run the second command below.

$dotnet new console
$code . &

Now lets add nlog package to a project.

$dotnet add package nlog

This will add the following code to our project file.

    <PackageReference Include="nlog" Version="4.5.6" />

Nlog framework requires configuration file 'nlog.config' to specify logger tagerts and rules. We can copy paste the sample nlog.config file from this github page or use one below.

xml version="1.0" encoding="utf-8" ?>

<nlog xmlns="" 
      xsi:schemaLocation="NLog NLog.xsd"
      internalLogLevel="Info" >

    <target xsi:type="File" name="file" 
        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}" />

    <logger name="*" minlevel="Trace" writeTo="file,console" />


'nlog.config' file need to be copied to destination directory during project build. To achieve it add the code below to a project file.

    <None Include="nlog.config" CopyToOutputDirectory="Always" />

Now we need to add actual logging code to a program. Copy paste the Program class code below.

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

To build and run our console app run code below or add launch.json config to Visual Studio Code.

$dotnet build
$dotnet run

You should see the following output and log file created in the same directory as our console app.

2018/06/19 18:48:13.130|TRACE|Loggin trace. |nlog_console.Program|


Monday, 14 August 2017

Displaying assemblies used by the application process

Today I am going to show how to print out assemblies used by the running application. This information may be useful for logs and can be collected on application/service start.

Below is a snippet of the console application that prints out information to console.

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 ) );

Friday, 31 March 2017

VB.NET - Validating InputBox

If you are working with the system that still uses InputBox control from Microsoft.VisualBasic then you may get a situation where the input needs to be validated. InputBox control does not allow any validation checks and in ideal case needs to be replaced with custom WinForms dialog box. This post will show a simple way of validating InputBox by creating InputBoxValidated function and using IStringValidator interface.

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

As you can see InputBoxValidated function uses IStringValidator interface that can implement any kind of string validations and criteria.

Public Interface IStringValidator
    Function Validate(value As String) As Boolean
End Interface

Below is an example of StringValidator class that implements IStringValidator interface and makes use of StringValidator from System.Configuration.

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

            Dim stringValidator As _
                New System.Configuration.StringValidator _
                    (0, MaxLength, InvalidCharacters)
            If stringValidator.CanValidate(value.GetType()) Then
                valid = False
            End If
        Catch ex As ArgumentException
            valid = False
        End Try

        Return valid
    End Function
End Class


Monday, 30 January 2017

Creating self extracting zip EXE under Linux for windows

Recently, I had a need to create a self extracting zip archive, which will open on any windows machine. Because, I am using Linux, I did not want to go through the process of installing the windows with 7z on it just for a sake of creating that archive. I was expecting that the process will be not trivial, as some of internet resources show, but all turned out very simple. Peazip archiver available for Windows as well as Linux, which is able to create self extracting exe archive. I downloaded portable version for 64 bit machine and when creating a new archive you get an option to create self extracting file in a single volume or split by chosen size.

What I found, peazip creates small archives that extract under windows machine just fine. If you need to zip large amount of files say > 1 GB, I would suggest to create normal archive, which can span several files of set size and then use 7zip on windows computer to extract them.


Monday, 5 December 2016

Reading appsettings.json in .Net Core Console Application under Linux

Recently I was looking at how to load and use appsettings.json file in .Net Core Console application. Many resources on .Net forums and sites were descripting use of appsettings.json file in ASP.NET Core web App, but very little described appsettings with .Net Core Console app. I managed to created sample .Net Core app with the minimum required libraries. Creation of this sample program I am going to describe here. Let's call our App "appsettings".
$mkdir appsettings
$cd appsettings
$dotnet new
$dotnet restore
Now create appsettings.json file:
    "AppSettings": {
        "Date": "1900-01-01"
Date is the setting I am interested in loading from AppSettings section.

Edit project.json file to include "Microsoft.Extensions.Configuration.UserSecrets": "1.1.0" in dependencies section. This is the only extra library we need in order to use ConfigurationBuilder functions.
    "version": "1.0.0-*",
    "buildOptions": {
        "debugType": "portable",
        "emitEntryPoint": true,
        "outputName": "AppSettings"
    "dependencies": {},
    "frameworks": {
        "netcoreapp1.0": {
            "dependencies": {
                "Microsoft.NETCore.App": {
                    "type": "platform",
                    "version": "1.1.0"
                "Microsoft.Extensions.Configuration.UserSecrets": "1.1.0"
            "imports": "dnxcore50"
Now lets edit the Program.cs file. We are going to load the Date setting and display it in Console. Don't forget to include "using Microsoft.Extensions.Configuration;"
using System;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace ConsoleApplication
    public class Program
        public static string AppSettingsFile = "appsettings.json";
        public static string AppSettingsSection = "AppSettings";
        public static string DateSetting = "Date";

        public static void Main(string[] args)
            var builder = new ConfigurationBuilder()
                .AddJsonFile(Program.AppSettingsFile, optional: true, 
                             reloadOnChange: true);
            var config = builder.Build();
            var appSettings = config.GetSection(Program.AppSettingsSection);
            string dateString = appSettings[Program.DateSetting];
            Console.WriteLine("Date:" + dateString);
That is pretty much all. Now let's build and run it.
$dotnet build
$dotnet run