void IShellSettingsManager.SaveSettings(ShellSettings shellSettings)
        {
            if (shellSettings == null)
            {
                throw new ArgumentNullException(nameof(shellSettings));
            }
            if (string.IsNullOrWhiteSpace(shellSettings.Name))
            {
                throw new ArgumentException(
                          "The Name property of the supplied ShellSettings object is null or empty; the settings cannot be saved.",
                          nameof(shellSettings.Name));
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saving ShellSettings for tenant '{0}'", shellSettings.Name);
            }
            var tenantPath = _appDataFolder.MapPath(_appDataFolder.Combine("Sites", shellSettings.Name));

            var configurationProvider = new YamlConfigurationProvider(
                _appDataFolder.Combine(tenantPath, string.Format(SettingsFileNameFormat, "txt")), false);

            foreach (var key in shellSettings.RootConfiguration.GetChildren())
            {
                configurationProvider.Set(key.Key, key.Value);
            }

            configurationProvider.Commit();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saved ShellSettings for tenant '{0}'", shellSettings.Name);
            }
        }
Beispiel #2
0
        void IShellSettingsManager.SaveSettings(ShellSettings shellSettings)
        {
            Argument.ThrowIfNull(shellSettings, nameof(shellSettings));
            Argument.ThrowIfNullOrWhiteSpace(shellSettings.Name,
                                             nameof(shellSettings.Name),
                                             "The Name property of the supplied ShellSettings object is null or empty; the settings cannot be saved.");

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saving ShellSettings for tenant '{0}'", shellSettings.Name);
            }
            var tenantPath = _appDataFolder.MapPath(
                _appDataFolder.Combine(
                    _optionsAccessor.Value.Location,
                    shellSettings.Name,
                    string.Format(SettingsFileNameFormat, "txt")));

            var configurationProvider =
                new YamlConfigurationProvider(tenantPath, false);

            foreach (var key in shellSettings.Keys)
            {
                if (!string.IsNullOrEmpty(shellSettings[key]))
                {
                    configurationProvider.Set(key, shellSettings[key]);
                }
            }

            configurationProvider.Commit();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saved ShellSettings for tenant '{0}'", shellSettings.Name);
            }
        }
Beispiel #3
0
        public void Foo()
        {
            var yaml = @"---
name: Default
dataproviders:
    entityframework-sql:
        connectionstring: Foo
        table-prefix: 12345
    entityframework-inmemory:
...";

            File.WriteAllText(_tempFolderName, yaml);

            var yamlConfigPrd = new YamlConfigurationProvider(new YamlConfigurationSource
            {
                Path     = _tempFolderName,
                Optional = false
            });

            var root = new ConfigurationBuilder().Add(yamlConfigPrd.Source).Build();

            //var settings = new ShellSettings(root);

            //Assert.Equal(, settings.DataProviders.First())
        }
Beispiel #4
0
        public void SaveToSource(string name, IDictionary <string, string> configuration)
        {
            var settingsFile = GetSettingsFilePath(Path.Combine(
                                                       _optionsAccessor.Value.ShellsApplicationDataPath,
                                                       _optionsAccessor.Value.ShellsContainerName,
                                                       name));

            var configurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource
            {
                Path     = settingsFile,
                Optional = false
            });

            configurationProvider.Set(name, null);
            configurationProvider.Set($"{name}:RequestUrlHost", ObtainValue(configuration, $"{name}:RequestUrlHost"));
            configurationProvider.Set($"{name}:RequestUrlPrefix", ObtainValue(configuration, $"{name}:RequestUrlPrefix"));
            configurationProvider.Set($"{name}:DatabaseProvider", ObtainValue(configuration, $"{name}:DatabaseProvider"));
            configurationProvider.Set($"{name}:TablePrefix", ObtainValue(configuration, $"{name}:TablePrefix"));
            configurationProvider.Set($"{name}:ConnectionString", ObtainValue(configuration, $"{name}:ConnectionString"));
            configurationProvider.Set($"{name}:State", ObtainValue(configuration, $"{name}:State"));
            configurationProvider.Set($"{name}:Secret", ObtainValue(configuration, $"{name}:Secret"));
            configurationProvider.Set($"{name}:RecipeName", ObtainValue(configuration, $"{name}:RecipeName"));

            configurationProvider.Commit();
        }
Beispiel #5
0
        public void YamlProviderTest()
        {
            YamlConfigurationProvider yamlProvider = LoadProviders();
            string loglevel = string.Empty;

            yamlProvider.TryGet("logging:logLevel:default", out loglevel);

            Assert.Equal("Warning", loglevel);
        }
Beispiel #6
0
        public void LoadMethodCanHandleEmptyValue()
        {
            var yaml          = @"name:";
            var yamlConfigSrc = new YamlConfigurationProvider(TestStreamHelpers.ArbitraryFilePath);

            yamlConfigSrc.Load(TestStreamHelpers.StringToStream(yaml));

            Assert.Equal(string.Empty, yamlConfigSrc.Get("name"));
        }
Beispiel #7
0
        private YamlConfigurationProvider LoadProvider(string Yaml)
        {
            var p = new YamlConfigurationProvider(new YamlConfigurationSource {
                Optional = true
            });

            p.Load(TestStreamHelpers.StringToStream(Yaml));
            return(p);
        }
Beispiel #8
0
        public void NonObjectRootIsInvalid()
        {
            var yaml          = @"test";
            var yamlConfigPrd = new YamlConfigurationProvider("Foo");

            var exception = Assert.Throws <FormatException>(
                () => yamlConfigPrd.Load(TestStreamHelpers.StringToStream(yaml)));

            Assert.NotNull(exception.Message);
        }
Beispiel #9
0
        private YamlConfigurationProvider LoadProviders()
        {
            var provider = new YamlConfigurationProvider(new YamlConfigurationSource()
            {
                Optional = false
            });

            provider.Load(GetYamlStream());
            return(provider);
        }
Beispiel #10
0
        public void FilesWithByteOrderMarkerAreParsedCorrectly()
        {
            var yaml = "setting1: '1'\nsetting2: '2'";

            var yamlConfigSource = new YamlConfigurationProvider(new YamlConfigurationSource());

            yamlConfigSource.Load(TestStreamHelpers.StringToStream(yaml, withBom: true));

            Assert.Equal("1", yamlConfigSource.Get("setting1"));
            Assert.Equal("2", yamlConfigSource.Get("setting2"));
        }
Beispiel #11
0
        public ICommandResult <IThemeDescriptor> UpdateTheme(
            string pathToThemeFolder,
            IThemeDescriptor descriptor)
        {
            if (descriptor == null)
            {
                throw new ArgumentNullException(nameof(descriptor));
            }

            if (string.IsNullOrEmpty(descriptor.Name))
            {
                throw new ArgumentNullException(nameof(descriptor.Name));
            }

            // Path to theme manifest file
            var fileName     = string.Format(ByThemeFileNameFormat, "txt");
            var manifestPath = _platoFileSystem.MapPath(
                _platoFileSystem.Combine(pathToThemeFolder, fileName));

            // Configure YAML configuration
            var configurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource
            {
                Path     = manifestPath,
                Optional = false
            });

            // Build configuration
            foreach (var key in descriptor.Keys)
            {
                if (!string.IsNullOrEmpty(descriptor[key]))
                {
                    configurationProvider.Set(key, descriptor[key]);
                }
            }

            var result = new CommandResult <ThemeDescriptor>();

            try
            {
                configurationProvider.Commit();
            }
            catch (Exception e)
            {
                return(result.Failed(e.Message));
            }

            return(result.Success(descriptor));
        }
Beispiel #12
0
        public void SupportAndIgnoreComments()
        {
            var yaml          = @"# Comments
                # Comments
                name: test #foo
                address:
                    street: Something street # Comments
                    zipcode: 12345";
            var yamlConfigPrd = new YamlConfigurationProvider("Foo");

            yamlConfigPrd.Load(TestStreamHelpers.StringToStream(yaml));

            Assert.Equal("test", yamlConfigPrd.Get("name"));
            Assert.Equal("Something street", yamlConfigPrd.Get("address:street"));
            Assert.Equal("12345", yamlConfigPrd.Get("address:zipcode"));
        }
Beispiel #13
0
        public void ArraysAreConvertedToKeyValuePairs()
        {
            var yaml = @"
                ip:
                    - 1.2.3.4
                    - 7.8.9.10
                    - 11.12.13.14";

            var yamlConfigurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource());

            yamlConfigurationProvider.Load(TestStreamHelpers.StringToStream(yaml));

            Assert.Equal("1.2.3.4", yamlConfigurationProvider.Get("ip:0"));
            Assert.Equal("7.8.9.10", yamlConfigurationProvider.Get("ip:1"));
            Assert.Equal("11.12.13.14", yamlConfigurationProvider.Get("ip:2"));
        }
Beispiel #14
0
        public bool SaveSettings(IShellSettings shellSettings)
        {
            if (shellSettings == null)
            {
                throw new ArgumentNullException(nameof(shellSettings));
            }

            if (string.IsNullOrEmpty(shellSettings.Name))
            {
                throw new ArgumentNullException(nameof(shellSettings.Name));
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saving shell settings for tenant '{0}'", shellSettings.Name);
            }

            var fileName   = string.Format(SettingsFileNameFormat, "txt");
            var tenantPath = _appDataFolder.MapPath(
                _appDataFolder.Combine(
                    _optionsAccessor.Value.Location,
                    shellSettings.Location,
                    fileName));

            var configurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource
            {
                Path     = tenantPath,
                Optional = false
            });

            foreach (var key in shellSettings.Keys)
            {
                if (!string.IsNullOrEmpty(shellSettings[key]))
                {
                    configurationProvider.Set(key, shellSettings[key]);
                }
            }

            configurationProvider.Commit();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saved shell settings for tenant '{0}'", shellSettings.Name);
            }

            return(true);
        }
        public void SequencesAreConvertedToKeyValuePairs()
        {
            var yaml = @"
                ip:
                - '1.2.3.4'
                - '7.8.9.10'
                - '11.12.13.14'
            ";

            var yamlConfigSource = new YamlConfigurationProvider(new YamlConfigurationSource());

            yamlConfigSource.Load(TestStreamHelpers.StringToStream(yaml));

            Assert.Equal("1.2.3.4", yamlConfigSource.Get("ip:0"));
            Assert.Equal("7.8.9.10", yamlConfigSource.Get("ip:1"));
            Assert.Equal("11.12.13.14", yamlConfigSource.Get("ip:2"));
        }
Beispiel #16
0
        public void LoadKeyValuePairsFromValidYaml()
        {
            var yaml          = @"
firstname: test
test.last.name: last.name
residential.address:
    street.name: Something street
    zipcode: 12345";
            var yamlConfigPrd = new YamlConfigurationProvider(TestStreamHelpers.ArbitraryFilePath);

            yamlConfigPrd.Load(TestStreamHelpers.StringToStream(yaml.TrimStart()));

            Assert.Equal("test", yamlConfigPrd.Get("firstname"));
            Assert.Equal("last.name", yamlConfigPrd.Get("test.last.name"));
            Assert.Equal("Something street", yamlConfigPrd.Get("residential.address:STREET.name"));
            Assert.Equal("12345", yamlConfigPrd.Get("residential.address:zipcode"));
        }
Beispiel #17
0
        public void ArrayOfObjects()
        {
            var yaml = @"
                ip:
                    - address: 1.2.3.4
                      hidden: False
                    - address: 5.6.7.8
                      hidden: True";

            var yamlConfigurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource());

            yamlConfigurationProvider.Load(TestStreamHelpers.StringToStream(yaml));

            Assert.Equal("1.2.3.4", yamlConfigurationProvider.Get("ip:0:address"));
            Assert.Equal("False", yamlConfigurationProvider.Get("ip:0:hidden"));
            Assert.Equal("5.6.7.8", yamlConfigurationProvider.Get("ip:1:address"));
            Assert.Equal("True", yamlConfigurationProvider.Get("ip:1:hidden"));
        }
Beispiel #18
0
        public void NestedArrays()
        {
            var yaml = @"
                ip:
                  - - 1.2.3.4
                    - 5.6.7.8
                  - - 9.10.11.12
                    - 13.14.15.16";

            var yamlConfigurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource());

            yamlConfigurationProvider.Load(TestStreamHelpers.StringToStream(yaml));

            Assert.Equal("1.2.3.4", yamlConfigurationProvider.Get("ip:0:0"));
            Assert.Equal("5.6.7.8", yamlConfigurationProvider.Get("ip:0:1"));
            Assert.Equal("9.10.11.12", yamlConfigurationProvider.Get("ip:1:0"));
            Assert.Equal("13.14.15.16", yamlConfigurationProvider.Get("ip:1:1"));
        }
        public void SequenceOfObjects()
        {
            var yaml = @"
                ip:
                - address: '1.2.3.4'
                  hidden: false
                - address: '5.6.7.8'
                  hidden: true
            ";

            var yamlConfigSource = new YamlConfigurationProvider(new YamlConfigurationSource());

            yamlConfigSource.Load(TestStreamHelpers.StringToStream(yaml));

            Assert.Equal("1.2.3.4", yamlConfigSource.Get("ip:0:address"));
            Assert.Equal("false", yamlConfigSource.Get("ip:0:hidden"));
            Assert.Equal("5.6.7.8", yamlConfigSource.Get("ip:1:address"));
            Assert.Equal("true", yamlConfigSource.Get("ip:1:hidden"));
        }
Beispiel #20
0
        void IShellSettingsManager.SaveSettings(ShellSettings shellSettings)
        {
            if (shellSettings == null)
            {
                throw new ArgumentNullException(nameof(shellSettings));
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saving ShellSettings for tenant '{0}'", shellSettings.Name);
            }

            var tenantPath =
                Path.Combine(
                    _hostingEnvironment.ContentRootPath,
                    _optionsAccessor.Value.ShellsRootContainerName,
                    _optionsAccessor.Value.ShellsContainerName,
                    shellSettings.Name,
                    string.Format(SettingsFileNameFormat, "txt"));

            var configurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource
            {
                Path     = tenantPath,
                Optional = false
            });

            foreach (var key in shellSettings.Keys)
            {
                if (!string.IsNullOrEmpty(shellSettings[key]))
                {
                    configurationProvider.Set(key, shellSettings[key]);
                }
            }

            configurationProvider.Commit();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saved ShellSettings for tenant '{0}'", shellSettings.Name);
            }
        }
        void IShellSettingsManager.SaveSettings(ShellSettings shellSettings)
        {
            Argument.ThrowIfNull(shellSettings, nameof(shellSettings));
            Argument.ThrowIfNullOrWhiteSpace(shellSettings.Name,
                                             nameof(shellSettings.Name),
                                             "The Name property of the supplied ShellSettings object is null or empty; the settings cannot be saved.");

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saving ShellSettings for tenant '{0}'", shellSettings.Name);
            }

            var tenantPath =
                Path.Combine(
                    _hostingEnvironment.ContentRootPath,
                    _optionsAccessor.Value.ShellsRootContainerName,
                    _optionsAccessor.Value.ShellsContainerName,
                    shellSettings.Name,
                    string.Format(SettingsFileNameFormat, "txt"));

            var configurationProvider = new YamlConfigurationProvider(new YamlConfigurationSource
            {
                Path     = tenantPath,
                Optional = false
            });

            foreach (var key in shellSettings.Keys)
            {
                if (!string.IsNullOrEmpty(shellSettings[key]))
                {
                    configurationProvider.Set(key, shellSettings[key]);
                }
            }

            configurationProvider.Commit();

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Saved ShellSettings for tenant '{0}'", shellSettings.Name);
            }
        }
Beispiel #22
0
        public void SupportForMultiple()
        {
            var yaml          = @"---
name: test #foo
address:
    home:
        street: Some Home Address
        zipcode: 12345
    work:
        street: Some Work Address
        zipcode: 54321
...";
            var yamlConfigPrd = new YamlConfigurationProvider(TestStreamHelpers.ArbitraryFilePath);

            yamlConfigPrd.Load(TestStreamHelpers.StringToStream(yaml));

            Assert.Equal("Some Home Address", yamlConfigPrd.Get("address:home:street"));
            Assert.Equal("12345", yamlConfigPrd.Get("address:home:zipcode"));
            Assert.Equal("Some Work Address", yamlConfigPrd.Get("address:work:street"));
            Assert.Equal("54321", yamlConfigPrd.Get("address:work:zipcode"));
        }
        public void NestedSequences()
        {
            var yaml = @"
                'ip': 
                - 
                  - '1.2.3.4'
                  - '5.6.7.8'
                - 
                  - '9.10.11.12'
                  - '13.14.15.16'
                   ";

            var yamlConfigSource = new YamlConfigurationProvider(new YamlConfigurationSource());

            yamlConfigSource.Load(TestStreamHelpers.StringToStream(yaml));

            Assert.Equal("1.2.3.4", yamlConfigSource.Get("ip:0:0"));
            Assert.Equal("5.6.7.8", yamlConfigSource.Get("ip:0:1"));
            Assert.Equal("9.10.11.12", yamlConfigSource.Get("ip:1:0"));
            Assert.Equal("13.14.15.16", yamlConfigSource.Get("ip:1:1"));
        }
        /// <summary>
        /// Runs application.
        /// </summary>
        /// <param name="args">CLI arguments.</param>
        /// <param name="cancellationToken">Cancellation token</param>
        public async Task <int> RunAsync(string[] args, CancellationToken cancellationToken = default)
        {
            await Task.Yield();

            // process CLI args
            var arguments = Cli.Parse <TArgs>(args);

            if (arguments.HelpInvoked)
            {
                return(0);
            }
            if (arguments.ShowVersion)
            {
                Console.WriteLine($"App version: {ApplicationHelper.GetAssemblyVersion()}");
                return(CuriosityExitCodes.Success);
            }

            // basic app setup: culture, content root directory
            var customContentRootDirectory = String.Empty;

            if (EnvironmentHelper.IsDevelopmentEnvironment())
            {
                customContentRootDirectory = Directory.GetCurrentDirectory();
            }

            ApplicationHelper.ChangeCurrentDirectoryForDevelopment();

            // get configuration
            var configurationProvider = new YamlConfigurationProvider <TConfiguration>(arguments.ConfigurationDirectory, IsConfigFileOptional, args);
            var configuration         = configurationProvider.GetConfiguration();

            ApplicationHelper.SetDefaultCulture(configuration.Culture);

            // configure logs
            var loggingConfiguration = new CuriosityNLogConfigurator(configuration.Log.LogConfigurationPath, LoadLoggingConfiguration);

            loggingConfiguration.WithLogOutputDirectory(configuration.Log.LogOutputDirectory);

            loggingConfiguration.WithAppName(configuration.AppName);
            // ReSharper disable once SuspiciousTypeConversion.Global
            if (configuration is IConfigurationWithMailLogger configurationWithMailLogger)
            {
                loggingConfiguration.WithMail(configurationWithMailLogger.LoggerMail);
            }
            loggingConfiguration.Configure();

            var logger = LogManager.GetCurrentClassLogger();

            logger.Info($"Using configurations from directory \"{configurationProvider.PathToConfigurationFiles}\"'");

            // print configuration
            var configPrinter = new ConfigurationPrinter();
            var configLog     = configPrinter.GetLog(configuration);

            logger.Info($"Starting app with configuration: \n{configLog ?? "<no config>"}");

            // validate configuration
            var errors = configuration.Validate();

            if (errors.Count == 0)
            {
                logger.Info("Configuration is valid.");
            }
            else
            {
                var errorsBuilder = new StringBuilder();
                foreach (var validationError in errors)
                {
                    errorsBuilder.AppendLine($"- {validationError.FieldName}: {validationError.Error}");
                }

                logger.Error($"Configuration is invalid. Errors: {Environment.NewLine}{errorsBuilder}");

                return(CuriosityExitCodes.IncorrectConfiguration);
            }

            try
            {
                var startEmailLogger = LogManager.GetLogger("appStartEmailLog");
                startEmailLogger.Info($"{configuration.AppName} is started");

                return(await RunInternalAsync(args, arguments, configuration, configurationProvider, customContentRootDirectory, cancellationToken));
            }
            catch (Exception e) when(e is OperationCanceledException || e is TaskCanceledException)
            {
                logger.Warn(e, $"{configuration.AppName} was cancelled.");

                return(CuriosityExitCodes.Cancellation);
            }
            catch (Exception e)
            {
                logger.Fatal(e, $"Critical error on {configuration.AppName} work");

                return(CuriosityExitCodes.UnhandledException);
            }
            finally
            {
                var startEmailLogger = LogManager.GetLogger("appStopEmailLog");
                startEmailLogger.Info($"{configuration.AppName} is stopped");
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                LogManager.Shutdown();
            }
        }