How to Automate user configurations using codes

How to save hours daily by optimising and automating manual processes?

How to Automate user configurations using codes
Photo by Juanjo Jaramillo / Unsplash

What if instead of copying and pasting the same things over and over again, you could simply write a script that does the job for you automatically on demand?

I’m in the process of creating a new C# Console app for automating the configuration for a particular type of user.

I’m coding the script quickly in the main Program.cs file with the intention of testing whether this application is effective. If it’s too much work or takes too long, I will discontinue it.

The automation script however does work flawlessly. Therefore, now is the time to refactor by using more best practices such as configuration files and breaking the codes into smaller methods. Why not start with the official docs that can help me learn better and save time along the way?

.NET Framework Guidelines and Best Practices

If I have time to spare, I’m also thinking about adding a log provider such as Serilog or using the default one with dotnet.

Configuration

YAML vs JSON

Instead of hard coding values such as URLs right in the codes, I prefer adding them in config files so that they can be easily changed later on.

With a Python and Ruby background, I usually use YAML files. However, XML and JSON are better supported in the dotnet world. I, therefore, prefer choosing recommended practices in the framework I’m currently using - especially with the use of default or standard libraries.

Nevertheless, the use of YAML is still feasible. Here’s documentation on how to do it.

Reading And Writing YAML In C# .NET - .NET Core Tutorials
Let me just start off by saying that YAML itself is not that popular in either C# or .NET. For a long time, under .NET Framework, XML seemed to rein supreme with things like csproj files, solution files and even msbuild configurations all being XML driven. That slowly changed to be more JSON friendl…

Which configuration file?

When working with ASP.NET projects, you get an appsettings.json file by default. In this solution though, I’m using a console-based application. So my question is whether should I create a simple config.json file or the appsettings one?

In this post on Stack Overflow, you can simply use a config.json file.

How to get values from appsettings.json in a console application using .NET Core?
i’m creating a console application using .NET Core 3.1 and i would like to have an appsettings json to load allenvironment, paths, variables,... at the beginning of the execution, and then get val...

How to read JSON file?

This is mostly relevant in a console-based application.

Image
Copy if newer

Note: When using such files, it’s important to copy them to the output directory, otherwise, they won’t be found. You can simply choose the properties and select “copy if newer” option.

I’m using JetBrains’ Rider for this example, nevertheless, this also works in Visual Studio.

To read configuration files, install these two nuget packages:

Microsoft.Extensions.Configuration.Binder
Microsoft.Extensions.Configuration.Json

Add a simple configuration builder:

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("config.json",optional: false);

IConfiguration config = builder.Build();

You can then retrieve your config either directly or using a class, which is recommended. You can also have multiple configuration files.

{
	"DEV": {
		"URL": "some_url_here"
	}
}
var DEV = config.GetSection("DEV");
var URL = DEV.GetSection("URL").Value;
Console.WriteLine(URL);

// some_url_here

Quick Tip when using breakpoints

You don't actually need to modify the codes to add a return button, especially if you are deep in the stack call. You can just stop the application when it hits your breakpoint:

Stop App

Dotenv

For this automation project, right now I have hardcoded third party credentials in the code. One effective solution that I’ve been using in different technologies is dotenv.

You add a .env file and locally store their values that represent environment variables. However, you don’t commit it. In case you did it before adding the file to gitignore, here’s a quick solution:

Now in your server or pipeline, you just need to add the environment variables and dotenv will replace them respectively.

For C#, I find there are two commonly used ones.

GitHub - bolorundurowb/dotenv.net: A library to read .env files in a .NET Core environment
A library to read .env files in a .NET Core environment - GitHub - bolorundurowb/dotenv.net: A library to read .env files in a .NET Core environment

You can easily add it via dotnet cli:

dotnet add package dotenv.net
// declare necessary namespace
using dotenv.net;

// load the .env file if present
DotEnv.Load();

And dotnet-env.

GitHub - tonerdo/dotnet-env: A .NET library to load environment variables from .env files
A .NET library to load environment variables from .env files - GitHub - tonerdo/dotnet-env: A .NET library to load environment variables from .env files

When I try the first one, it doesn’t work.

I attempt the second library, which also doesn’t work.

I read the documentation online all over the place but nothing seems to be effective.

I suspect that dotenv is not reading the file.

As such, I load the env file:

string currentDirectory = Directory.GetCurrentDirectory();
string envFile = Path.Combine(currentDirectory, ".env");
Env.Load(envFile);

Nonetheless, nothing changes.

I then realise that I haven’t copied the .env file to output.

Once done, the code works as expected.

You can get the values like so:

var username = Env.GetString("username");
var value = Environment.GetEnvironmentVariable("username");

Conclusion

You don’t need to be an expert in Software Development to be able to optimise and automate your workflow. Nowadays, there’s plenty of free information readily available on the Internet. If you have any questions, I would be happy to help. Contact me.

“Anything worth automating should be automated” - Abdallah Yashir Ramsing