AaTurpin.ConfigManager
1.1.0
See the version list below for details.
dotnet add package AaTurpin.ConfigManager --version 1.1.0
NuGet\Install-Package AaTurpin.ConfigManager -Version 1.1.0
<PackageReference Include="AaTurpin.ConfigManager" Version="1.1.0" />
<PackageVersion Include="AaTurpin.ConfigManager" Version="1.1.0" />
<PackageReference Include="AaTurpin.ConfigManager" />
paket add AaTurpin.ConfigManager --version 1.1.0
#r "nuget: AaTurpin.ConfigManager, 1.1.0"
#addin nuget:?package=AaTurpin.ConfigManager&version=1.1.0
#tool nuget:?package=AaTurpin.ConfigManager&version=1.1.0
ConfigManager
ConfigManager is a .NET library that provides a convenient way to manage application configuration settings in your .NET Framework applications. It offers a simplified interface for reading and writing configuration values, managing directory entries, and handling drive mappings through your application's config file.
Features
- Type-safe configuration access: Retrieve strongly-typed configuration values
- Default value support: Specify fallback values for missing configuration entries
- Directory management: Add, retrieve, and remove directory entries with optional exclusion patterns
- Drive mapping support: Define and manage network drive mappings with enhanced validation
- Automatic configuration validation: Ensures required configuration sections exist
- Comprehensive logging: Integrated logging for configuration operations with detailed statistics
- Robust error handling: Detailed diagnostics and validation for configuration entries
Requirements
- .NET Framework 4.7.2 or higher
- System.Configuration namespace
Installation
Install the AaTurpin.ConfigManager package from NuGet:
Install-Package AaTurpin.ConfigManager
# or
dotnet add package AaTurpin.ConfigManager
Package URL: NuGet Gallery
Usage
Basic Configuration Access
// Get a string value
string serverName = ConfigHelper.GetValue<string>("ServerName", "localhost");
// Get an integer value with default
int port = ConfigHelper.GetValue<int>("Port", 8080);
// Get a boolean value
bool enableLogging = ConfigHelper.GetValue<bool>("EnableLogging", false);
// Set a configuration value
ConfigHelper.SetValue("MaxConnections", 100);
Working with Directory Entries
// Get all directory entries from config
List<DirectoryConfig> directories = ConfigHelper.GetDirectories();
// Display directory entries
foreach (var dir in directories)
{
Console.WriteLine($"Directory: {dir.Path}");
if (dir.Exclusions.Count > 0)
{
Console.WriteLine("Excluded subdirectories:");
foreach (var exclusion in dir.Exclusions)
{
Console.WriteLine($" - {exclusion}");
}
}
}
// Add a new directory entry with exclusions
var newDir = new DirectoryConfig
{
Path = @"C:\MyApplication\Data",
Exclusions = new List<string> { "temp", @"logs\archive", @"reports\old" }
};
ConfigHelper.AddDirectory(newDir);
// Remove a directory entry
ConfigHelper.RemoveDirectory(@"C:\MyApplication\OldData");
Working with Drive Mappings
// Get all drive mappings from config
List<DriveMapping> mappings = ConfigHelper.GetDriveMappings();
// Display drive mappings
foreach (var mapping in mappings)
{
Console.WriteLine($"Drive mapping: {mapping.DriveLetter} -> {mapping.UncPath}");
}
// Add a new drive mapping
var newMapping = new DriveMapping
{
DriveLetter = "V:",
UncPath = @"\\server\share"
};
ConfigHelper.AddDriveMapping(newMapping);
// Remove a drive mapping
ConfigHelper.RemoveDriveMapping("V:");
Enhanced Validation for Drive Mappings
The library now includes improved validation for drive mappings:
// This will fail validation and log an error due to invalid drive letter format
var invalidMapping1 = new DriveMapping
{
DriveLetter = "VDrive", // Should be "V:"
UncPath = @"\\server\share"
};
// This will fail validation and log an error due to invalid UNC path format
var invalidMapping2 = new DriveMapping
{
DriveLetter = "X:",
UncPath = @"server\share" // Should be "\\server\share"
};
// Both validations will generate detailed error messages in the log
Logging with RunLog
ConfigManager uses the RunLog library for logging operations. RunLog is already integrated with ConfigHelper, and logging is configured automatically when the application starts.
// ConfigHelper uses Log.Logger by default, but you can customize it
// Create a custom logger configuration
var loggerConfig = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File("logs/config.log", rollingInterval: RollingInterval.Day);
// Set the logger instance
Log.Logger = loggerConfig.CreateLogger();
// Optionally set the logger for ConfigHelper specifically
ConfigHelper.SetLogger(Log.Logger);
Example logging output with enhanced diagnostics:
[2025-04-26 10:15:23] [Information] Loaded 5 directories from config (skipped 2 invalid entries)
[2025-04-26 10:15:23] [Warning] Directory entry at index 3 skipped: Missing required 'path' attribute
[2025-04-26 10:15:23] [Warning] Directory entry at index 7 skipped: Empty 'path' attribute
[2025-04-26 10:15:24] [Debug] Added new directory entry: C:\MyApplication\Data
[2025-04-26 10:15:25] [Warning] Directory entry not found: C:\MyApplication\OldData
RunLog provides various log levels (Verbose, Debug, Information, Warning, Error, Fatal) and multiple output destinations including console and file with rolling options.
Configuration File Structure
The configuration file should have the following structure:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="directories" type="DummyType, DummyAssembly" />
<section name="driveMappings" type="DummyType, DummyAssembly" />
</configSections>
<appSettings>
<add key="ServerName" value="myserver" />
<add key="Port" value="8080" />
<add key="EnableLogging" value="true" />
</appSettings>
<directories>
<directory path="C:\MyApp\Data">
<exclude>temp</exclude>
<exclude>logs\archive</exclude>
<exclude>old_files</exclude>
</directory>
<directory path="C:\MyApp\Logs" />
</directories>
<driveMappings>
<mapping driveLetter="V:" uncPath="\\server\share" />
<mapping driveLetter="X:" uncPath="\\server2\archive" />
</driveMappings>
</configuration>
Configuration Validation
ConfigManager automatically validates and creates required configuration sections when initialized. The EnsureConfigSectionsExist()
method is called during static initialization to make sure all necessary sections exist in your config file.
Error Handling and Validation
The library includes comprehensive error handling with detailed logging. Operations that fail will return appropriate values (false for boolean operations, default values for getters) and log the error with specific diagnostic information, including:
- Index of problematic entries in configuration
- Validation failures with detailed reasons
- Statistics on valid vs. skipped entries
- Case-insensitive string comparison for more flexible matching
Best Practices
- Always specify default values when using
GetValue<T>()
to handle missing configuration entries gracefully - Use the strongly-typed methods rather than accessing the configuration values directly
- Ensure drive letter format is correct (single letter followed by colon, e.g., "V:")
- Ensure UNC path format is correct (starts with double backslash, e.g., "\\server\share")
- When defining directory exclusions:
- Use separate
<exclude>
elements for each path to exclude - Use relative paths (e.g., "logs\archive", "temp") that are relative to the main directory path
- Both Windows backslash (
\
) and forward slash (/
) path separators are supported
- Use separate
- Check log output for validation warnings and errors after configuration changes
License
MIT
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET Framework | net472 is compatible. net48 was computed. net481 was computed. |
-
.NETFramework 4.7.2
- RunLog (>= 3.2.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on AaTurpin.ConfigManager:
Package | Downloads |
---|---|
AaTurpin.SnapshotManager
A robust .NET library for managing file snapshots across network locations with high reliability and error recovery. SnapshotManager provides network-aware file operations with automatic retry mechanisms, delta detection between snapshots for efficient synchronization, parallel processing with configurable concurrency limits, and intelligent handling of incomplete snapshots due to network issues. Key features: - Create reliable file and directory snapshots even in unstable network environments - Compare snapshots to identify added, modified, and deleted files - Recover from network issues and timeout conditions automatically - Configure network timeout handling for different environments - Historical tracking to validate snapshot completeness - Optimized for enterprise file synchronization scenarios Particularly useful for maintaining synchronized copies of network shares, creating backup systems, or implementing high-availability file replication. |
|
AaTurpin.DriveManager
A robust .NET Framework utility for managing Windows network drives. Provides methods for mapping, unmapping, and checking network drives with comprehensive error handling and logging. Uses PowerShell commands internally for reliable drive operations. |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version 1.1.0 - ConfigHelper.cs Changes:
- Added enhanced validation for drive letter and UNC path formats
- Improved error handling with detailed warning messages for invalid entries
- Added statistics logging for skipped entries during configuration loading
- Simplified DirectoryEntry class with direct string[] property for exclusions
- Consolidated DirectoryConfig and DirectoryEntry into a single implementation
- Fixed handling of directory entries with missing attributes
- Added case-insensitive string comparison for drive mappings
- Improved regex validation for drive letter format
- Enhanced error reporting with logging of specific entries that fail validation
- Added safeguards against empty or malformed config entries
- Updated RunLog to version 3.2.0 for improved logging capabilities