configuration of .net core console application

In this blog post I will be discussing how to have a configurable .NET Core console application that reads values from a config file. First thing I did was create new vanilla .NET Core console application and at the time of writing v5.0 was available so I decided to use that as my target framework. I then had to install some Nuget packages to my solution which are needed to have this application configurable. The Nuget packages are the following;

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.Binder
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.Json

I then created a new appsettings.json file and just added some data which is what I’ll be retrieving. Here’s my sample that has some logging details and allowed CORS methods, which from my experience are common values you would find in a config file.

{
"Logging": {
"Url": "https://www.google.com",
"Username": "TestLoggingUsername"
},
"CorsAllowedMethods": "GET,POST,PUT,PATCH,DELETE,OPTIONS"
}

Once created we need to make sure that whenever the application builds a copy of the JSON file is created in the bin folder, the same directory where the application runs. To do that just right click on the file, click on properties and update as per the following screenshot.

Capture

I then created a couple models that reflect the structure of my appsettings.json file so that when I load my config values I parse them in my models and can be accessed easily.

public class AppConfig
{
public Logging Logging { get; set; }
public string CorsAllowedMethods { get; set; }
}
public class Logging
{
public string Url { get; set; }
public string Username { get; set; }
}

Lastly, I added a couple methods in my main Program class. The idea is to initialise the configuration, load the JSON file, build it (and this where the Nuget packages come into play) and map them to our models.

class Program
{
static void Main(string[] args)
{
var cfg = InitSettings<AppConfig>();
var loggingUrl = cfg.Logging.Url;
var loggingUsername = cfg.Logging.Username;
var corsAllowedMethods = cfg.CorsAllowedMethods;
Console.WriteLine($"{loggingUrl} {loggingUsername} {corsAllowedMethods}");
Console.ReadKey();
}
private static T InitSettings<T>() where T : new()
{
var config = InitConfig();
return config.Get<T>();
}
private static IConfigurationRoot InitConfig()
{
// load setup file name and path from appsettings.json
var builder = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true)
.AddEnvironmentVariables();
return builder.Build();
}
}

That should be enough get you started and be able to apply a configurable approach to your solution. One thing I would like to add is that sensitive data such as passwords or database connection strings should (ideally) not be stored inside these configurable files. In my opinion, a better approach for these values is to have them stored in a more secure location such as Azure’s Key Vaults or else in Azure’s Pipeline Variables. Both are accessed using credentails and therefore only users within your organisation can access them, and the values (or any changes done to them) isn’t tracked by source control like Git.

Thanks for reading,
Bjorn

adding an existing file as a link in visual studio

Testing is an essential phase in the software development life cycle. I almost dare to say that no software or application(web or desktop) was ever released without testing it first. As most .NET software developers I rely on test projects to create my unit tests and test my implementations. I find it practical, efficient, it helps me identify bugs, run dummy tests, evaluate the outcomes; in other words it’s good and you should make use of it if you don’t.

One feature I don’t like in test projects is that certain configurations need to be replicated rather then referenced. Let’s assume that in my solution I have project A(which is my working project) and project B(which is my test project used to test project A). If I had to add my own settings in the configuration file (app.config vs web.config) of project A and then try to run a test from project B, the solution would throw an exception saying that the newly added settings was not found. Therefore to run my test I would need to copy the setting and add it in the configuration file of project B, something I’m not very fond of. A similar exception was thrown when I added a file(an XML file in my case) to project A and then ran a test from project B. Since the implementation depended on the XML file and the file was added in project A, the test failed. I then had to add the same file in project B in order to get the code running. Again, I’m not very fond of this practice and from not very fond it started to become quite frustrating.

I resorted to Google to find a solution. After some quick research I found out that an existing file can be added as a link to another project in the same solution. This is great, just what I wanted because any changes done to the file would be done once. To add an existing file as a link you must;

  1. Right click on the target project, click on Add and from the new menu click on Add Existing Item.
  2. A new directory window should pop on screen. Locate the existing file to add.
  3. Right next to the Add button, click on the arrow and from the drop down menu select, and click, Add As Link.

A new file should now show in the targeted project. Great! I did that happily convinced that all is going to be well in my test but, once again, when I ran my test project the same exception was thrown. It took me a while to realise but when I checked the bin folder of the test project the XML file was not there. Thus, the file was not being included in the build and it all makes sense why the test was still failing.

Again, I resorted to Google to find a solution to add the linked file to the build of the test project. I found a few solutions but none were working for me until I stumbled across Matt Perdeck’s blog post. In order to add the linked file to the project’s build you must find the project’s .csproj file(if it’s a C# project) and open it with an editing software, such as Notepad or Notepad++. At the very bottom, just before the closing node add the following text.


<Target Name="CopyLinkedContentFiles" BeforeTargets="Build">
<Copy SourceFiles="%(Content.Identity)" DestinationFiles="bin\Debug\%(Content.Link)" SkipUnchangedFiles='true' OverwriteReadOnlyFiles='true' Condition="'%(Content.Link)' != ''" />
</Target>

Quick build, located the linked file in the bin folder, ran the test and that’s it job done. From now on I had one file which is referenced in another project and whenever I ran the test it will always work. Hope this helps you guys too and hopefully it takes you less time to solve than it did to me.

See you’s
Bjorn