Skip to content
G.Raf edited this page Oct 29, 2020 · 1 revision

How to use BootstrapLib

First it is necessary to create a new project:

dotnet new console -n MyApp

Open project with VisualStudio or VisualStudio Code or any other editor and in console switch to folder MyApp (cd MyApp) and install the bootstrap library:

dotnet add package RaGae.Bootstrap

After adding the package add a new file with following content:

MyConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace MyApp
{
    public enum ErrorCode
    {
        OK,
        ERROR,
        TEST
    }

    public class MyConfig
    {
        private IEnumerable<MyArrayConfig> array;
        private int value;

        public int Value
        {
            get => this.value;
            set
            {
                if (value < 1)
                    throw new ArgumentException(nameof(MyConfig));
                this.value = value;
            }
        }

        public IEnumerable<MyArrayConfig> Array
        {
            get => this.array;
            set
            {
                value.ToList().ForEach(e =>
                {
                    if (e.Error != ErrorCode.OK)
                        throw new ArgumentException(nameof(MyArrayConfig));
                });

                this.array = value;
            }
        }
    }

    public class MyArrayConfig
    {
        private int value;

        public int Value
        {
            get => this.value;
            set
            {
                this.Error = ErrorCode.OK;

                if (value < 1)
                    this.Error = ErrorCode.ERROR;

                this.value = value;
            }
        }

        public ErrorCode Error { get; private set; }
    }
}

After adding the configuration create 2 JSON files with following content:

appsettings.section.json

{
  "MyConfig": {
    "Value": 1,
    "Array": [
      { "Value": 1 }
    ]
  }
}

appsettings.nosection.json

{
  "Value": 1,
  "Array": [
    { "Value": 1 }
  ]
}

Now adapt the main program:

main.cs

using System;
using System.Linq;
using RaGae.BootstrapLib.Loader;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            MyConfig demo;

            try
            {
                // Appsettings with no configuration section
                //demo = Loader.LoadConfig<MyConfig>("appsettings.nosection.json", false, false);

                // Appsettings with configuration section
                demo = Loader.LoadConfigSection<MyConfig>("appsettings.section.json", nameof(MyConfig), false, false);

                Console.WriteLine(demo.Value);
                Console.WriteLine(demo.Array.ElementAt(0).Value);
            }
            catch(Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}

Run the Program:

dotnet run

1
1
Clone this wiki locally