HardDev.CoreUtils 2.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package HardDev.CoreUtils --version 2.1.0                
NuGet\Install-Package HardDev.CoreUtils -Version 2.1.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="HardDev.CoreUtils" Version="2.1.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add HardDev.CoreUtils --version 2.1.0                
#r "nuget: HardDev.CoreUtils, 2.1.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install HardDev.CoreUtils as a Cake Addin
#addin nuget:?package=HardDev.CoreUtils&version=2.1.0

// Install HardDev.CoreUtils as a Cake Tool
#tool nuget:?package=HardDev.CoreUtils&version=2.1.0                

HardDev.CoreUtils

NuGet

HardDev.CoreUtils is a utility library providing core functionality for .NET applications. It includes advanced configuration handling, logging, and more. This library is designed to simplify common tasks and help developers create cleaner and more efficient code.

Features

  • Advanced configuration handling with support for JSON files and built-in default values and validation.
  • Easy-to-use logging setup built on top of the Serilog library.
  • Highly customizable logger configuration with adjustable log levels, output format, and more.
  • Supports .NET Standard 2.0, .NET Standard 2.1 and .NET 8.0 target frameworks

Getting Started

Install the latest version of the HardDev.CoreUtils library from NuGet.

dotnet add package HardDev.CoreUtils

Usage

Configuration

The HardDev.CoreUtils configuration system treats configurations as singletons, providing consistently updated values across your application.

Creating a Configuration file:

using System.ComponentModel.DataAnnotations;
using HardDev.CoreUtils.Config;

namespace HardDev.ConfigExamples;

/// <summary>
/// A sample configuration to show how to derive from BaseConfiguration and use default values and validations.
/// </summary>
public class SampleConfig() : BaseConfiguration<SampleConfig>("Configs/SampleConfig.json")
{
    /// <summary>
    /// Gets or sets an integer value.
    /// </summary>
    [Range(1, 100)]
    public int IntegerValue { get; set; } = 42;

    /// <summary>
    /// Gets or sets a double value.
    /// </summary>
    public double DoubleValue { get; set; } = 3.14;

    /// <summary>
    /// Gets or sets a float value.
    /// </summary>
    public float FloatValue { get; set; } = 123.456f;

    /// <summary>
    /// Gets or sets a boolean value.
    /// </summary>
    public bool BooleanValue { get; set; } = true;

    /// <summary>
    /// Gets or sets a URL as a string.
    /// </summary>
    [Url(ErrorMessage = "Invalid URL format")]
    public string Url { get; set; } = "http://default_url.com";

    /// <summary>
    /// Gets or sets a read-only list of strings representing accounts.
    /// </summary>
    [Required(ErrorMessage = "Accounts cannot be null"),
     MinLength(1, ErrorMessage = "Accounts cannot be empty")]
    public IReadOnlyList<string> Accounts { get; set; } = new List<string> { "Account1", "Account2", "Account3" };

    /// <summary>
    /// Gets or sets a read-only list of integers representing numbers.
    /// </summary>
    [Required(ErrorMessage = "Numbers cannot be null"),
     MinLength(1, ErrorMessage = "Numbers cannot be empty")]
    public IReadOnlyList<int> Numbers { get; set; } = new List<int> { 1, 2, 3 };

    /// <summary>
    /// Gets or sets a dictionary with string keys and integer values.
    /// </summary>
    [Required(ErrorMessage = "Example dictionary cannot be null"), MinLength(1, ErrorMessage = "ExampleDictionary cannot be empty")]
    public IDictionary<string, int> ExampleDictionary { get; set; } = new Dictionary<string, int> { { "Key1", 1 }, { "Key2", 2 } };
}

Using a Configuration in your application:

using HardDev.CoreUtils.Config;
using HardDev.CoreUtils.Logging;
using Serilog;

namespace HardDev.ConfigExamples;

public static class Program
{
    // Configure the logger for the example class
    private static readonly ILogger Logger = AppLogger.Build(new LoggerConfig { EnableFile = false });

    public static void Main()
    {
        // Get or load a SampleConfig instance
        var sampleConfig = AppConfig.GetOrLoad<SampleConfig>();

        Logger.Information("Loaded values from SampleConfig:");
        Logger.Information("IntegerValue: {IntegerValue}", sampleConfig.IntegerValue);
        Logger.Information("DoubleValue: {DoubleValue}", sampleConfig.DoubleValue);
        Logger.Information("FloatValue: {FloatValue}", sampleConfig.FloatValue);
        Logger.Information("BooleanValue: {BooleanValue}", sampleConfig.BooleanValue);
        Logger.Information("Url: {Url}", sampleConfig.Url);
        Logger.Information("Accounts: {Accounts}", string.Join(", ", sampleConfig.Accounts));
        Logger.Information("Numbers: {Numbers}", string.Join(", ", sampleConfig.Numbers));
        Logger.Information("ExampleDictionary: {ExampleDictionary}", string.Join(", ", sampleConfig.ExampleDictionary));

        Logger.Information("Changing some values in SampleConfig");
        sampleConfig.IntegerValue = 999;
        sampleConfig.DoubleValue = 6.28;

        Logger.Information("Validating SampleConfig");
        sampleConfig.EnsureValidProperties();

        Logger.Information("Changed values in SampleConfig:");
        Logger.Information("IntegerValue: {IntegerValue}", sampleConfig.IntegerValue);
        Logger.Information("DoubleValue: {DoubleValue}", sampleConfig.DoubleValue);

        Logger.Information("Saving SampleConfig...");
        sampleConfig.Save();

        Logger.Information("Press any key to exit...");
        Console.ReadKey();
    }
}

Logging

HardDev.CoreUtils.Logging provides an easy-to-use logger configuration and management built on top of the Serilog library.

Here's an example of setting up the logger and logging a message:

using HardDev.CoreUtils.Logging;
using Serilog.Events;

// Configure the logger
var cfg = new LoggerConfig
{
    LogPath = "Logs",
    EnableConsole = true,
    EnableFile = true,
    ConsoleLogLevel = LogEventLevel.Debug,
    FileLogLevel = LogEventLevel.Verbose,
};
var logger = AppLogger.Build(cfg);

// Log a message
logger.Information("Hello, World!");

More examples of using the logger:

  1. Log an error message with exception:
try
{
    // Some code that might throw an exception
}
catch (Exception ex)
{
    AppLogger.Instance.Error(ex, "An error occurred");
}
  1. Log a warning message with properties:
int currentUsers = 50;
int maxUsers = 100;
AppLogger.Instance.Warning("Current users reached {CurrentUsers} out of {MaxUsers}", currentUsers, maxUsers);
  1. Scoped logger with context:
var scopedLogger = AppLogger.ForName("ScopedContext");
scopedLogger.Information("This message has a custom context.");

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.2.7 143 3/25/2024
2.2.6 110 3/24/2024
2.2.5 99 3/24/2024
2.2.4 109 3/24/2024
2.2.3 122 3/24/2024
2.2.2 109 3/23/2024
2.2.1 116 3/22/2024
2.2.0 109 3/22/2024
2.1.2 124 3/21/2024
2.1.1 105 3/21/2024
2.1.0 109 3/21/2024
2.0.2 132 3/13/2024
1.2.2 114 3/11/2024
1.2.1 111 3/11/2024
1.2.0 106 3/11/2024
1.1.0 107 3/10/2024
1.0.1 186 6/17/2023

Initial release of the CoreUtils library