Skip to content

Commit

Permalink
close #3: Add verbosity option and replace console for logging output
Browse files Browse the repository at this point in the history
  • Loading branch information
mnieto committed Jun 7, 2020
1 parent 3e6c9be commit 7358593
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 17 deletions.
1 change: 1 addition & 0 deletions ConfigSectionCrypt/ConfigSectionCrypt.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.8.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Configuration" />
Expand Down
27 changes: 15 additions & 12 deletions ConfigSectionCrypt/Crypt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
using Serilog;

namespace ConfigSectionCrypt {
public static class Crypt {
Expand All @@ -21,24 +22,25 @@ public static int EncryptSections(Options options) {
Configuration config = OpenConfiguration(options.ConfigFile);

foreach (string sectionName in options.Section) {
Console.WriteLine("Encrypting section '{0}' in '{1}'", sectionName, fileName);
Log.Debug("Encrypting section '{sectionName}' in '{sectionName}'", sectionName, fileName);
ConfigurationSection configSection = config.GetSection(sectionName);
if (configSection != null) {
if (configSection.SectionInformation.IsProtected) {
Console.WriteLine("'{0}' section is already encrypted", sectionName);
Log.Warning("'{sectionName}' section is already encrypted", sectionName);
} else {
configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
}
Console.WriteLine("Successfully encrypted section '{0}' in '{1}'", sectionName, fileName);
Log.Information("Successfully encrypted section '{sectionName}' in '{fileName}'", sectionName, fileName);
} else {
Console.WriteLine("ERROR: cannot load the configuration section '{0}' from file '{1}'", fileName, sectionName);
Log.Error("ERROR: cannot load the configuration section '{fileName}' from file '{sectionName}'. Remember that section names are case sensitive.", fileName, sectionName);
return ExitCodes.SectionNotFound;
}
}
config.Save();
return ExitCodes.NoError;
} catch (Exception ex) {
Console.WriteLine("ERROR: {0}: {1}", ex.GetType().FullName, ex.Message);
string errorType = ex.GetType().FullName;
Log.Error(ex, "ERROR: {errorType}", errorType);
return ExitCodes.UnexpectedError;
}
}
Expand All @@ -50,24 +52,25 @@ public static int DecryptSections(Options options) {
try {
Configuration config = OpenConfiguration(options.ConfigFile);
foreach (string sectionName in options.Section) {
Console.WriteLine("Decrypting section '{0}' in '{1}'", sectionName, fileName);
Log.Debug("Decrypting section '{sectionName}' in '{fileName}'", sectionName, fileName);
ConfigurationSection configSection = config.GetSection(sectionName);
if (configSection != null) {
if (configSection.SectionInformation.IsProtected) {
configSection.SectionInformation.UnprotectSection();
} else {
Console.WriteLine("'{0}' section is already unprotected", sectionName);
Log.Warning("'{sectionName}' section is already unprotected", sectionName);
}
Console.WriteLine("Successfully decrypted section '{0}' in '{1}'", sectionName, fileName);
Log.Information("Successfully decrypted section '{sectionName}' in '{fileName}'", sectionName, fileName);
} else {
Console.WriteLine("ERROR: cannot load the configuration section '{0}' from file '{1}' - section not found or invalid", fileName, sectionName);
Log.Error("ERROR: cannot load the configuration section '{fileName}' from file '{sectionName}'. Remember that section names are case sensitive.", fileName, sectionName);
return ExitCodes.SectionNotFound;
}
}
config.Save();
return ExitCodes.NoError;
} catch (Exception ex) {
Console.WriteLine("ERROR: {0}: {1}", ex.GetType().FullName, ex.Message);
string errorType = ex.GetType().FullName;
Log.Error(ex, "ERROR: {errorType}", errorType);
return ExitCodes.UnexpectedError;
}
}
Expand All @@ -80,13 +83,13 @@ private static void RegisterAssemblies(IEnumerable<string> includes) {
}

private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
Console.WriteLine($"Resolving assembly {args.Name}");
Log.Information($"Resolving assembly {args.Name}");
foreach (string include in Includes) {
string assemblyName = Path.GetFileNameWithoutExtension(include);
string assemblyPath = Path.GetFullPath(include); //Assembly.LoadFile requires absolute path

if (string.Equals(args.Name, assemblyName, StringComparison.OrdinalIgnoreCase)) {
Console.WriteLine($"Resolved: Loading '{assemblyPath}'.");
Log.Debug($"Resolved: Loading '{assemblyPath}'.");
return Assembly.LoadFile(assemblyPath);
}
}
Expand Down
3 changes: 3 additions & 0 deletions ConfigSectionCrypt/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,8 @@ public class Options {
[Option('i', "include", HelpText = "Include reference to neccessary assemblies to read config file", Required = false, Separator = ',')]
public IEnumerable<string> Include { get; set; }

[Option('l', "loglevel", HelpText = "Logging level: Quiet, Normal, Verbose", Default = Verbosity.Normal)]
public Verbosity LogLevel { get; set; }

internal char Operation { get; set; }
}
26 changes: 21 additions & 5 deletions ConfigSectionCrypt/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
using System.Web.Configuration;
using CommandLine;
using CommandLine.Text;
using Serilog;
using Serilog.Sinks.SystemConsole;

namespace ConfigSectionCrypt {
class Program {
Expand All @@ -20,13 +22,27 @@ static int Main(string[] args) {

}

private static void SetupLogger(Verbosity verbosity) {
var logLevel = (Serilog.Events.LogEventLevel)(int)verbosity;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(logLevel, theme: Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme.Literate)
.CreateLogger();
}

private static int RunAndReturnExitCode(Options options) {
string command = options.Operation == 'e' ? "Encrypt" : "Decript";
Console.WriteLine($"{command} {options.ConfigFile} file");
Console.WriteLine($" sections: {string.Join(",", options.Section)}");
Console.WriteLine($" includes: {string.Join(",", options.Include)}");
Console.WriteLine();

SetupLogger(options.LogLevel);

if (Log.IsEnabled(Serilog.Events.LogEventLevel.Debug)) {
StringBuilder sb = new StringBuilder();
string command = options.Operation == 'e' ? "Encrypt" : "Decript";
sb.AppendLine($"{command} {options.ConfigFile} file");
sb.AppendLine($" sections: {string.Join(",", options.Section)}");
sb.AppendLine($" includes: {string.Join(",", options.Include)}");
sb.AppendLine();
Log.Debug(sb.ToString());
}

if (options.Encrypt) {
return Crypt.EncryptSections(options);
Expand Down
19 changes: 19 additions & 0 deletions ConfigSectionCrypt/Verbosity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/// <summary>
/// Logging verbosity level
/// </summary>
public enum Verbosity {
/// <summary>
/// Only unexpected errors are shown
/// </summary>
Quiet = 4,

/// <summary>
/// Normal logging
/// </summary>
Normal = 2,

/// <summary>
/// Verbose logging
/// </summary>
Debug = 1
}

0 comments on commit 7358593

Please sign in to comment.