public IntegrationTests( IConfigurationLoader configurationLoader, ILogger <IntegrationTests> logger) { _configurationLoader = configurationLoader; _logger = logger; }
/// <summary> /// Initializes a new instance of the <see cref="BeyovaConfigurationLoaderAttribute" /> class. /// </summary> /// <param name="loaderType">Type of the loader. Type need to has non-parameter constructor and inherited from <see cref="IConfigurationLoader"/></param> /// <param name="loaderParameter">The loader parameter.</param> public BeyovaConfigurationLoaderAttribute(Type loaderType, string loaderParameter) { if (loaderType != null && typeof(IConfigurationLoader).IsAssignableFrom(loaderType)) { Loader = (loaderType.TryCreateInstanceViaParameterlessConstructor() as IConfigurationLoader) ?? (loaderType.TryCreateInstanceViaSingleParameterConstructor(loaderParameter) as IConfigurationLoader); } }
/// <summary> /// Initializes a new instance of the <see cref="BeyovaConfigurationLoaderAttribute" /> class. This is a shortcut way to add <see cref="LocalJsonConfigurationLoader" />, to instead <see cref="BeyovaConfigurationAttribute" /> /// </summary> /// <param name="configurationName">Name of the configuration.</param> /// <param name="configurationDirectory">The configuration directory.</param> public BeyovaConfigurationLoaderAttribute(string configurationName, string configurationDirectory = null) { if (!string.IsNullOrWhiteSpace(configurationName)) { Loader = new LocalJsonConfigurationLoader(new BeyovaLocalConfigurationOptions(configurationName, configurationDirectory)); } }
public LiteEngine( IUtil util, IProfileManager profileManager, IScriptService scriptService, IProfileWriter profileWriter, IConnectionManagerFactory connectionManagerFactory, ICloudProfileLoaderService cloudProfileLoaderService, ILITETask liteTaskManager, IProfileStorage profileStorage, IConnectionFinder connectionFinder, ILitePurgeService litePurgeService, IConfigurationLoader configurationLoader, IProfileConnectionsInitializer connectionsInitializer, ILogger <LiteEngine> logger) { Throw.IfNull(util); _profileManager = profileManager; _profileWriter = profileWriter; _connectionManagerFactory = connectionManagerFactory; _cloudProfileLoaderService = cloudProfileLoaderService; _scriptService = scriptService; _taskManager = liteTaskManager; _profileStorage = profileStorage; _connectionFinder = connectionFinder; _litePurgeService = litePurgeService; _configurationLoader = configurationLoader; _connectionsInitializer = connectionsInitializer; _logger = logger; }
/// <summary> /// Creates the instance of a MailProvider using the given configuration. /// </summary> /// <param name="configurationLoader">The configuration to be supplied to the MailProvider. The configuration key value pairs are specific to providers.</param> /// <param name="mapper">The object mapper, used for mapping between E-Mail domain models and models used by third-party provider libraries.</param> /// <returns>The instantiated MailProvider.</returns> public IMailProvider GetProvider(IConfigurationLoader configurationLoader, IMapper mapper) { if (configurationLoader == null) { throw new ArgumentNullException(nameof(configurationLoader)); } IMailProvider mailProvider = null; var config = configurationLoader.GetConfiguration(); if (config.TryGetValue("MailProvider", out string provider)) { if (!string.IsNullOrWhiteSpace(provider)) { switch (provider) { case nameof(Provider.SendGrid): mailProvider = new SendGridProvider(configurationLoader); break; default: throw new ArgumentException("Unknown provider."); } } } else { throw new InvalidOperationException("Configuration is missing MailProvider."); } return(mailProvider); }
public ContentFetcher( HttpClient httpClient, IConfigurationLoader configurationLoader) { this.httpClient = httpClient; this.configurationLoader = configurationLoader; }
public CommonConfig(IConfigurationLoader configurationLoader) { // Load all configuration keys/values var configuration = configurationLoader.LoadConfigurationValues(); // Build the CommonConfig object SystemType = configuration.GetRequiredEnum <SystemTypeEnum>("SYSTEM_TYPE"); }
/// <summary> /// The context constructor should only be called once. After the context has been created call GetContext for specific copies /// </summary> /// <param name="loader">The loader used to load classes.</param> /// <param name="datas">Custom data handlers.</param> public Context(IConfigurationLoader loader, IEnumerable <AbstractSitecoreDataHandler> datas) { //the setup must only run if the context has not been setup //second attempts to setup a context should throw an error if (!_contextLoaded) { lock (_lock) { if (!_contextLoaded) { //load all classes var classes = loader.Load().ToDictionary(); datas = LoadDefaultDataHandlers(datas); InstanceContext instance = new InstanceContext(classes, datas); StaticContext = instance; //now assign a data handler to each property foreach (var cls in classes) { IList <AbstractSitecoreDataHandler> handlers = new List <AbstractSitecoreDataHandler>(); foreach (var prop in cls.Value.Properties) { var handler = instance.GetDataHandler(prop); //set the ID property of the class //the ID property is needed later for writing and page editing, //saves time having to look it if (prop.Attribute is SitecoreIdAttribute) { cls.Value.IdProperty = prop; } else if (prop.Attribute is SitecoreInfoAttribute && prop.Attribute.CastTo <SitecoreInfoAttribute>().Type == SitecoreInfoType.Language) { cls.Value.LanguageProperty = prop; } else if (prop.Attribute is SitecoreInfoAttribute && prop.Attribute.CastTo <SitecoreInfoAttribute>().Type == SitecoreInfoType.Version) { cls.Value.VersionProperty = prop; } handlers.Add(handler); } cls.Value.DataHandlers = handlers; } } } } else { throw new MapperException("Context already loaded"); } }
public AppSettingsProvider( IConfigurationLoader configurationLoader, IConfigurationSaver configurationSaver) { _configurationLoader = configurationLoader; _configurationSaver = configurationSaver; AppSettings = new AppSettings(); this.Load(); }
public AutoRenewal( IConfigurationLoader configurationLoader, IRenewalService renewalService, ILogger <AutoRenewal> logger) { _configurationLoader = configurationLoader; _renewalService = renewalService; _logger = logger; }
protected virtual IObjectContainer CreateGlobalContainer(IConfigurationLoader configurationLoader, Assembly testAssembly) { var globalContainer = new ContainerBuilder(CreateDefaultDependencyProvider()).CreateGlobalContainer( testAssembly, new DefaultRuntimeConfigurationProvider(configurationLoader)); return(globalContainer); }
/// <summary> /// The context constructor should only be called once. After the context has been created call GetContext for specific copies /// </summary> /// <param name="loader">The loader used to load classes.</param> /// <param name="datas">Custom data handlers.</param> public Context(IConfigurationLoader loader, IEnumerable<AbstractSitecoreDataHandler> datas) { //the setup must only run if the context has not been setup //second attempts to setup a context should throw an error if (!_contextLoaded) { lock (_lock) { if (!_contextLoaded) { //load all classes var classes = loader.Load().ToDictionary(); datas = LoadDefaultDataHandlers(datas); InstanceContext instance = new InstanceContext(classes, datas); StaticContext = instance; //now assign a data handler to each property foreach (var cls in classes) { IList<AbstractSitecoreDataHandler> handlers = new List<AbstractSitecoreDataHandler>(); foreach (var prop in cls.Value.Properties) { var handler = instance.GetDataHandler(prop); //set the ID property of the class //the ID property is needed later for writing and page editing, //saves time having to look it if (prop.Attribute is SitecoreIdAttribute) cls.Value.IdProperty = prop; else if (prop.Attribute is SitecoreInfoAttribute && prop.Attribute.CastTo<SitecoreInfoAttribute>().Type == SitecoreInfoType.Language) cls.Value.LanguageProperty = prop; else if (prop.Attribute is SitecoreInfoAttribute && prop.Attribute.CastTo<SitecoreInfoAttribute>().Type == SitecoreInfoType.Version) cls.Value.VersionProperty = prop; handlers.Add(handler); } cls.Value.DataHandlers = handlers; } } } } else throw new MapperException ("Context already loaded"); }
public SendGridProvider(IConfigurationLoader configuration) { _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _configuration.GetConfiguration(); if (configuration.GetConfiguration().TryGetValue("SendGridApiKey", out string apiKey)) { _client = new SendGridClient(apiKey); } }
public RadarrCommand( ILogger logger, LoggingLevelSwitch loggingLevelSwitch, IConfigurationLoader <RadarrConfiguration> configLoader, Func <RadarrQualityDefinitionUpdater> qualityUpdaterFactory) : base(logger, loggingLevelSwitch) { _configLoader = configLoader; _qualityUpdaterFactory = qualityUpdaterFactory; }
public Startup(IConfiguration configuration, IConfigurationLoader configurationLoader, IModuleLoader moduleLoader, ILogger <Startup> logger) { this.configuration = configuration; this.configurationLoader = configurationLoader; this.moduleLoader = moduleLoader; this.logger = logger; }
public SonarrCommand( ILogger logger, LoggingLevelSwitch loggingLevelSwitch, IConfigurationLoader <SonarrConfiguration> configLoader, Func <ReleaseProfileUpdater> profileUpdaterFactory, Func <SonarrQualityDefinitionUpdater> qualityUpdaterFactory) : base(logger, loggingLevelSwitch) { _configLoader = configLoader; _profileUpdaterFactory = profileUpdaterFactory; _qualityUpdaterFactory = qualityUpdaterFactory; }
public static void Initialize(IConfigurationLoader loader) { Section applicationSection = GetApplicationSection(loader.Context); loader.AddValidator(GetApplicationSectionValidator(applicationSection)); _handler = new ConfigurationHandler(loader, new SectionList { applicationSection }); _handler.LoadSettings(); _handler.SettingsChanged += HandleSettingsChanged; _isInitialized = true; }
/// <summary> /// Reloads system configuration from configuration sources. /// </summary> public void ReloadConfiguration() { // If system settings is null, // attempt to reload system settings if ((object)m_systemSettings == null) { ReloadSystemSettings(); } // If system settings is still null, give up if ((object)m_systemSettings == null) { return; } using (AdoDataConnection connection = CreateDbConnection(m_systemSettings)) { TableOperations <ConfigurationLoader> configurationLoaderTable = new TableOperations <ConfigurationLoader>(connection); List <ConfigurationLoader> configurationLoaderDefinitions = configurationLoaderTable .QueryRecords("LoadOrder") .ToList(); string connectionString = LoadSystemSettings(connection); foreach (ConfigurationLoader configurationLoaderDefinition in configurationLoaderDefinitions) { try { OnStatusMessage("[{0}] Loading configuration...", configurationLoaderDefinition.UnqualifiedTypeName); using (ConfigurationLoaderWrapper wrapper = Wrap(configurationLoaderDefinition)) { IConfigurationLoader configurationLoader = wrapper.DataObject; // Use the connection string parser to load system settings into the configuration loader ConnectionStringParser.ParseConnectionString(connectionString, configurationLoader); // Update configuration by calling the configuration loader's UpdateConfiguration method configurationLoader.UpdateConfiguration(connection); } OnStatusMessage("[{0}] Done loading configuration.", configurationLoaderDefinition.UnqualifiedTypeName); } catch (Exception ex) { string message = string.Format("[{0}] Unable to update configuration due to exception: {1}", configurationLoaderDefinition.UnqualifiedTypeName, ex.Message); OnProcessException(new InvalidOperationException(message, ex)); } } } }
/// <summary> /// Initializes a new instance of the ConfigurationHandler class. /// </summary> /// <param name="loader"></param> public ConfigurationHandler(IConfigurationLoader loader, SectionList predefinedSections, List <ISettingParser> settingParsers, List <ISettingsProcessor> processors) { _loader = loader; _predefinedSections.AddRange(predefinedSections); RegisterParsers(settingParsers); RegisterProcessors(processors); RegisterForLoaderSettingsChanged(); }
protected virtual object CreateGlobalContainer(IConfigurationLoader configurationLoader, Assembly testAssembly) { var containerBuilder = new ContainerBuilder(new NoInvokeDependencyProvider()); var configurationProvider = new DefaultRuntimeConfigurationProvider(configurationLoader); //var globalContainer = containerBuilder.CreateGlobalContainer( // testAssembly, // new DefaultRuntimeConfigurationProvider(configurationLoader)); var globalContainer = containerBuilder.ReflectionCallMethod <object>(nameof(ContainerBuilder.CreateGlobalContainer), testAssembly, configurationProvider); return(globalContainer); }
public RadarrCommand( ILogger logger, LoggingLevelSwitch loggingLevelSwitch, ILogJanitor logJanitor, IConfigurationLoader <RadarrConfiguration> configLoader, Func <IRadarrQualityDefinitionUpdater> qualityUpdaterFactory, Func <ICustomFormatUpdater> customFormatUpdaterFactory) : base(logger, loggingLevelSwitch, logJanitor) { _configLoader = configLoader; _qualityUpdaterFactory = qualityUpdaterFactory; _customFormatUpdaterFactory = customFormatUpdaterFactory; }
protected override IObjectContainer CreateGlobalContainer(IConfigurationLoader configurationLoader, Assembly testAssembly) { // We need to call the CreateGlobalContainer through reflection because the interface has been changed in V3.0.220. var containerBuilder = new ContainerBuilder(new NoInvokeDependencyProvider()); var configurationProvider = new DefaultRuntimeConfigurationProvider(configurationLoader); //var globalContainer = containerBuilder.CreateGlobalContainer( // new DefaultRuntimeConfigurationProvider(configurationLoader)); var globalContainer = containerBuilder.ReflectionCallMethod <object>(nameof(ContainerBuilder.CreateGlobalContainer), configurationProvider); return((IObjectContainer)globalContainer); }
public static IConfigurationLoader[] GlassLoaders() { /* USE THIS AREA TO ADD FLUENT CONFIGURATION LOADERS * * If you are using Attribute Configuration or automapping/on-demand mapping you don't need to do anything! * */ var config = new IConfigurationLoader[] { new AttributeConfigurationLoader("Informa.Models", "Jabberwocky.Glass", "Velir.Search.Models"), new SitecoreFluentConfigurationLoader() }; return(config); }
public InspectCommand( IConfigurationLoader configurationLoader, IRuleAssemblyLoader ruleAssemblyLoader, ISolutionLoader solutionLoader, IRuleCollectionBuilder ruleCollectionBuilder, IViolationReporterFactory violationReporterFactory) : base("inspect", "Inspects a given solution for rule violations.") { _configurationLoader = configurationLoader; _ruleAssemblyLoader = ruleAssemblyLoader; _solutionLoader = solutionLoader; _ruleCollectionBuilder = ruleCollectionBuilder; _violationReporterFactory = violationReporterFactory; }
/// <summary> /// /// </summary> /// <param name="filePath">Excel文件路径</param> /// <param name="configLoader">类型映射配置加载器</param> public ExcelDataReader(string filePath, IConfigurationLoader configLoader) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException(nameof(filePath)); } if (configLoader == null) { throw new ArgumentNullException(nameof(configLoader)); } this.filePath = filePath; this.configLoader = configLoader; }
/// <summary> /// Creates the instance of a MailProvider using the given configuration and provider type. /// </summary> /// <param name="configurationLoader">The configuration to be supplied to the MailProvider. The configuration key value pairs are specific to providers.</param> /// <param name="mapper">The object mapper, used for mapping between E-Mail domain models and models used by third-party provider libraries.</param> /// <param name="provider">The type of MailProvider to instantiate.</param> /// <returns>The instantiated MailProvider.</returns> public IMailProvider GetProvider(IConfigurationLoader configurationLoader, IMapper mapper, Provider provider) { if (configurationLoader == null) { throw new ArgumentNullException(nameof(configurationLoader)); } switch (provider) { case Provider.SendGrid: return(new SendGridProvider(configurationLoader)); default: throw new ArgumentOutOfRangeException("Unknown provider."); } }
protected AbstractConfigurationRepository( string configKey, IConfigurationLoader <TConfigurationSource> configLoader, Func <TConfigurationSource, TConfigurationStore> configurationPreprocessor, ILogger log) { Guard.DebugAssertArgumentNotNull(configLoader, nameof(configLoader)); Guard.DebugAssertArgumentNotNull(configurationPreprocessor, nameof(configurationPreprocessor)); Guard.DebugAssertArgumentNotNull(configKey, nameof(configKey)); Guard.DebugAssertArgumentNotNull(log, nameof(log)); _configKey = configKey; _configLoader = configLoader; _configurationPreprocessor = configurationPreprocessor; _log = log; }
public SonarrCommand( ILogger log, LoggingLevelSwitch loggingLevelSwitch, ILogJanitor logJanitor, ISettingsPersister settingsPersister, ISettingsProvider settingsProvider, IConfigurationLoader <SonarrConfiguration> configLoader, Func <IReleaseProfileUpdater> profileUpdaterFactory, Func <ISonarrQualityDefinitionUpdater> qualityUpdaterFactory) : base(log, loggingLevelSwitch, logJanitor, settingsPersister, settingsProvider) { _log = log; _configLoader = configLoader; _profileUpdaterFactory = profileUpdaterFactory; _qualityUpdaterFactory = qualityUpdaterFactory; }
/// <summary> /// Internal method to read and parse the properties from the given loader /// </summary> /// <param name="loader">the loader to read data from</param> private void LoadProperties(IConfigurationLoader loader) { var configurationData = loader.LoadData(); foreach (var data in configurationData) { string rawStringData = data.Data; if (rawStringData != null) { using (var sourceReader = new StringReader(rawStringData)) { string line; int lineCounter = 0; do { lineCounter++; line = sourceReader.ReadLine(); //Filter comments if (line != null && line.Trim() != String.Empty && !line.StartsWith(CharComment.ToString(), StringComparison.Ordinal)) { var splits = line.Split(CharAssign); if (splits.Length == 2) { var property = splits[0].Trim(); var value = splits[1].Trim(); properties[property] = value; } else { logging.Error( String.Format("Failed to load value {0} from {1} at line {2}. Could not split line.", line, data.Name, lineCounter )); } } } while (line != null); } } } logging.Debug(String.Format("{0} properties loaded from configuration", properties.Count)); }
public MusicFileCop(IFileSystemLoader fileSystemLoader, IConfigurationLoader configurationLoader, IMetadataLoader metadataLoader, IConsistencyChecker consistencyChecker, IDefaultConfigurationNode defaultConfiguration, IConfigurationWriter configWriter, ITextOutputWriter outputWriter, IRuleSet ruleSet) { if (fileSystemLoader == null) { throw new ArgumentNullException(nameof(fileSystemLoader)); } if (configurationLoader == null) { throw new ArgumentNullException(nameof(configurationLoader)); } if (metadataLoader == null) { throw new ArgumentNullException(nameof(metadataLoader)); } if (consistencyChecker == null) { throw new ArgumentNullException(nameof(consistencyChecker)); } if (defaultConfiguration == null) { throw new ArgumentNullException(nameof(defaultConfiguration)); } if (configWriter == null) { throw new ArgumentNullException(nameof(configWriter)); } if (outputWriter == null) { throw new ArgumentNullException(nameof(outputWriter)); } if (ruleSet == null) { throw new ArgumentNullException(nameof(ruleSet)); } this.m_FileSystemLoader = fileSystemLoader; this.m_ConfigLoader = configurationLoader; this.m_MetadataLoader = metadataLoader; this.m_ConsistencyChecker = consistencyChecker; this.m_DefaultConfiguration = defaultConfiguration; m_ConfigWriter = configWriter; m_OutputWriter = outputWriter; m_RuleSet = ruleSet; }
public Runner( IConfigurationLoader configurationLoader, IBootstrapperFactory bootstrapperFactory, IBridgeFactory bridgeFactory, string configurationName, string runName) { this.configurationLoader = configurationLoader; this.bootstrapperFactory = bootstrapperFactory; this.bridgeFactory = bridgeFactory; this.configurationName = configurationName; this.runName = runName; this.runData = new Dictionary <string, object>(); this.configuration = new Lazy <ConfigurationWrapper>(this.LoadConfiguration); this.contextFactory = null; }
public RadarrCommand( ILogger log, LoggingLevelSwitch loggingLevelSwitch, ILogJanitor logJanitor, ISettingsPersister settingsPersister, ISettingsProvider settingsProvider, IRepoUpdater repoUpdater, IConfigurationLoader <RadarrConfiguration> configLoader, Func <IRadarrQualityDefinitionUpdater> qualityUpdaterFactory, Func <ICustomFormatUpdater> customFormatUpdaterFactory) : base(log, loggingLevelSwitch, logJanitor, settingsPersister, settingsProvider, repoUpdater) { _log = log; _configLoader = configLoader; _qualityUpdaterFactory = qualityUpdaterFactory; _customFormatUpdaterFactory = customFormatUpdaterFactory; }
/// <summary> /// 現在のプロジェクト用のIConfigurationLoaderを取得する /// </summary> /// <returns>取得されたIConfigurationLoader</returns> public static IConfigurationLoader GetConfigurationLoader() { return _loader ?? (_loader = new CloudConfigurationLoader()); }
public ScheduledJobsWorkerConfiguration(IConfigurationLoader loader, string[] args) { var parameters = new DictionaryParameters(); if(null != args) { for(var c = 0; c < args.Count(); c++) { var arg = args[c]; parameters.Add(string.Format("args{0}", c), arg); } } loader.Initialise(this, parameters); return; }
public void Load(IConfigurationLoader loader) { properties.Clear(); LoadProperties(loader); }
/// <summary> /// Event handler for service starting operations. /// </summary> /// <param name="sender">Event source.</param> /// <param name="e">Event arguments containing command line arguments passed into service at startup.</param> /// <remarks> /// Time-series framework uses this handler to load settings from configuration file as service is starting. /// </remarks> protected virtual void ServiceStartingHandler(object sender, EventArgs<string[]> e) { ShutdownHandler.Initialize(); // Define a run-time log m_runTimeLog = new RunTimeLog(); m_runTimeLog.FileName = "RunTimeLog.txt"; m_runTimeLog.ProcessException += ProcessExceptionHandler; m_runTimeLog.Initialize(); // Initialize Iaon session m_iaonSession = new IaonSession(); m_iaonSession.StatusMessage += StatusMessageHandler; m_iaonSession.ProcessException += ProcessExceptionHandler; m_iaonSession.ConfigurationChanged += ConfigurationChangedHandler; // Create a handler for unobserved task exceptions TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; // Make sure default service settings exist ConfigurationFile configFile = ConfigurationFile.Current; string servicePath = FilePath.GetAbsolutePath(""); string cachePath = string.Format("{0}{1}ConfigurationCache{1}", servicePath, Path.DirectorySeparatorChar); string defaultLogPath = string.Format("{0}{1}Logs{1}", servicePath, Path.DirectorySeparatorChar); // System settings CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"]; systemSettings.Add("ConfigurationType", "Database", "Specifies type of configuration: Database, WebService, BinaryFile or XmlFile"); systemSettings.Add("ConnectionString", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=IaonHost.mdb", "Configuration database connection string"); systemSettings.Add("DataProviderString", "AssemblyName={System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089};ConnectionType=System.Data.OleDb.OleDbConnection;AdapterType=System.Data.OleDb.OleDbDataAdapter", "Configuration database ADO.NET data provider assembly type creation string"); systemSettings.Add("ConfigurationCachePath", cachePath, "Defines the path used to cache serialized configurations"); systemSettings.Add("LogPath", defaultLogPath, "Defines the path used to archive log files"); systemSettings.Add("MaxLogFiles", DefaultMaxLogFiles, "Defines the maximum number of log files to keep"); systemSettings.Add("CachedConfigurationFile", "SystemConfiguration.xml", "File name for last known good system configuration (only cached for a Database or WebService connection)"); systemSettings.Add("UniqueAdaptersIDs", "True", "Set to true if all runtime adapter ID's will be unique to allow for easier adapter specification"); systemSettings.Add("ProcessPriority", "High", "Sets desired process priority: Normal, AboveNormal, High, RealTime"); systemSettings.Add("AllowRemoteRestart", "True", "Controls ability to remotely restart the host service."); systemSettings.Add("MinThreadPoolWorkerThreads", DefaultMinThreadPoolSize, "Defines the minimum number of allowed thread pool worker threads."); systemSettings.Add("MaxThreadPoolWorkerThreads", DefaultMaxThreadPoolSize, "Defines the maximum number of allowed thread pool worker threads."); systemSettings.Add("MinThreadPoolIOPortThreads", DefaultMinThreadPoolSize, "Defines the minimum number of allowed thread pool I/O completion port threads (used by socket layer)."); systemSettings.Add("MaxThreadPoolIOPortThreads", DefaultMaxThreadPoolSize, "Defines the maximum number of allowed thread pool I/O completion port threads (used by socket layer)."); systemSettings.Add("ConfigurationBackups", DefaultConfigurationBackups, "Defines the total number of older backup configurations to maintain."); systemSettings.Add("PreferCachedConfiguration", "False", "Set to true to try the cached configuration first, before loading database configuration - typically used when cache is updated by external process."); systemSettings.Add("LocalCertificate", $"{ServiceName}.cer", "Path to the local certificate used by this server for authentication."); systemSettings.Add("RemoteCertificatesPath", @"Certs\Remotes", "Path to the directory where remote certificates are stored."); systemSettings.Add("DefaultCulture", "en-US", "Default culture to use for language, country/region and calendar formats."); // Example connection settings CategorizedSettingsElementCollection exampleSettings = configFile.Settings["exampleConnectionSettings"]; exampleSettings.Add("SqlServer.ConnectionString", "Data Source=serverName; Initial Catalog=databaseName; User ID=userName; Password=password", "Example SQL Server database connection string"); exampleSettings.Add("SqlServer.DataProviderString", "AssemblyName={System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089}; ConnectionType=System.Data.SqlClient.SqlConnection; AdapterType=System.Data.SqlClient.SqlDataAdapter", "Example SQL Server database .NET provider string"); exampleSettings.Add("MySQL.ConnectionString", "Server=serverName;Database=databaseName; Uid=root; Pwd=password; allow user variables = true;", "Example MySQL database connection string"); exampleSettings.Add("MySQL.DataProviderString", "AssemblyName={MySql.Data, Version=6.3.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d}; ConnectionType=MySql.Data.MySqlClient.MySqlConnection; AdapterType=MySql.Data.MySqlClient.MySqlDataAdapter", "Example MySQL database .NET provider string"); exampleSettings.Add("Oracle.ConnectionString", "Data Source=tnsName; User ID=schemaUserName; Password=schemaPassword", "Example Oracle database connection string"); exampleSettings.Add("Oracle.DataProviderString", "AssemblyName={Oracle.DataAccess, Version=2.112.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342}; ConnectionType=Oracle.DataAccess.Client.OracleConnection; AdapterType=Oracle.DataAccess.Client.OracleDataAdapter", "Example Oracle database .NET provider string"); exampleSettings.Add("SQLite.ConnectionString", "Data Source=databaseName.db; Version=3; Foreign Keys=True; FailIfMissing=True", "Example SQLite database connection string"); exampleSettings.Add("SQLite.DataProviderString", "AssemblyName={System.Data.SQLite, Version=1.0.99.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139}; ConnectionType=System.Data.SQLite.SQLiteConnection; AdapterType=System.Data.SQLite.SQLiteDataAdapter", "Example SQLite database .NET provider string"); exampleSettings.Add("OleDB.ConnectionString", "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=databaseName.mdb", "Example Microsoft Access (via OleDb) database connection string"); exampleSettings.Add("OleDB.DataProviderString", "AssemblyName={System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089}; ConnectionType=System.Data.OleDb.OleDbConnection; AdapterType=System.Data.OleDb.OleDbDataAdapter", "Example OleDb database .NET provider string"); exampleSettings.Add("Odbc.ConnectionString", "Driver={SQL Server Native Client 10.0}; Server=serverName; Database=databaseName; Uid=userName; Pwd=password;", "Example ODBC database connection string"); exampleSettings.Add("Odbc.DataProviderString", "AssemblyName={System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089}; ConnectionType=System.Data.Odbc.OdbcConnection; AdapterType=System.Data.Odbc.OdbcDataAdapter", "Example ODBC database .NET provider string"); exampleSettings.Add("WebService.ConnectionString", "http://localhost/ConfigSource/SystemConfiguration.xml", "Example web service connection string"); exampleSettings.Add("XmlFile.ConnectionString", "SystemConfiguration.xml", "Example XML configuration file connection string"); // Attempt to set default culture try { string defaultCulture = systemSettings["DefaultCulture"].ValueAs("en-US"); CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture(defaultCulture); // Defaults for date formatting, etc. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture(defaultCulture); // Culture for resource strings, etc. } catch (Exception ex) { DisplayStatusMessage("Failed to set default culture due to exception, defaulting to \"{1}\": {0}", UpdateType.Alarm, ex.Message, CultureInfo.CurrentCulture.Name.ToNonNullNorEmptyString("Undetermined")); LogException(ex); } // Retrieve application log path as defined in the config file string logPath = FilePath.GetAbsolutePath(systemSettings["LogPath"].Value); // Make sure log directory exists try { if (!Directory.Exists(logPath)) Directory.CreateDirectory(logPath); } catch (Exception ex) { // Attempt to default back to common log file path if (!Directory.Exists(defaultLogPath)) { try { Directory.CreateDirectory(defaultLogPath); } catch { defaultLogPath = servicePath; } } DisplayStatusMessage("Failed to create logging directory \"{0}\" due to exception, defaulting to \"{1}\": {2}", UpdateType.Alarm, logPath, defaultLogPath, ex.Message); LogException(ex); logPath = defaultLogPath; } int maxLogFiles = systemSettings["MaxLogFiles"].ValueAs(DefaultMaxLogFiles); try { Logger.FileWriter.SetPath(logPath); Logger.FileWriter.SetLoggingFileCount(maxLogFiles); } catch (Exception ex) { DisplayStatusMessage("Failed to set logging path \"{0}\" or max file count \"{1}\" due to exception: {2}", UpdateType.Alarm, logPath, maxLogFiles, ex.Message); LogException(ex); } // Retrieve configuration cache directory as defined in the config file cachePath = FilePath.GetAbsolutePath(systemSettings["ConfigurationCachePath"].Value); // Make sure configuration cache directory exists try { if (!Directory.Exists(cachePath)) Directory.CreateDirectory(cachePath); } catch (Exception ex) { DisplayStatusMessage("Failed to create configuration cache directory \"{0}\" due to exception: {1}", UpdateType.Alarm, cachePath, ex.Message); LogException(ex); } try { Directory.SetCurrentDirectory(servicePath); } catch (Exception ex) { DisplayStatusMessage("Failed to set current directory to execution path \"{0}\" due to exception: {1}", UpdateType.Alarm, servicePath, ex.Message); LogException(ex); } // Initialize system settings m_configurationType = systemSettings["ConfigurationType"].ValueAs<ConfigurationType>(); m_cachedXmlConfigurationFile = FilePath.AddPathSuffix(cachePath) + systemSettings["CachedConfigurationFile"].Value; m_cachedBinaryConfigurationFile = FilePath.AddPathSuffix(cachePath) + FilePath.GetFileNameWithoutExtension(m_cachedXmlConfigurationFile) + ".bin"; m_configurationBackups = systemSettings["ConfigurationBackups"].ValueAs(DefaultConfigurationBackups); m_uniqueAdapterIDs = systemSettings["UniqueAdaptersIDs"].ValueAsBoolean(true); m_allowRemoteRestart = systemSettings["AllowRemoteRestart"].ValueAsBoolean(true); m_preferCachedConfiguration = systemSettings["PreferCachedConfiguration"].ValueAsBoolean(false); m_reloadConfigQueue = ProcessQueue<Tuple<string, Action<bool>>>.CreateSynchronousQueue(ExecuteReloadConfig, 500.0D, Timeout.Infinite, false, false); m_reloadConfigQueue.ProcessException += m_iaonSession.ProcessExceptionHandler; m_configurationCacheOperation = new LongSynchronizedOperation(ExecuteConfigurationCache) { IsBackground = true }; // Setup default thread pool size try { ThreadPool.SetMinThreads(systemSettings["MinThreadPoolWorkerThreads"].ValueAs(DefaultMinThreadPoolSize), systemSettings["MinThreadPoolIOPortThreads"].ValueAs(DefaultMinThreadPoolSize)); ThreadPool.SetMaxThreads(systemSettings["MaxThreadPoolWorkerThreads"].ValueAs(DefaultMaxThreadPoolSize), systemSettings["MaxThreadPoolIOPortThreads"].ValueAs(DefaultMaxThreadPoolSize)); } catch (Exception ex) { DisplayStatusMessage("Failed to set desired thread pool size due to exception: {0}", UpdateType.Alarm, ex.Message); LogException(ex); } // Define guid with query string delimiters according to database needs if (string.IsNullOrWhiteSpace(m_nodeIDQueryString)) m_nodeIDQueryString = "'" + m_iaonSession.NodeID + "'"; // Set up the configuration loader switch (m_configurationType) { case ConfigurationType.Database: m_configurationLoader = new DatabaseConfigurationLoader { ConnectionString = systemSettings["ConnectionString"].Value, DataProviderString = systemSettings["DataProviderString"].Value, NodeIDQueryString = m_nodeIDQueryString }; break; case ConfigurationType.WebService: m_configurationLoader = new WebServiceConfigurationLoader { URI = systemSettings["ConnectionString"].Value }; break; case ConfigurationType.BinaryFile: m_configurationLoader = new BinaryFileConfigurationLoader { FilePath = systemSettings["ConnectionString"].Value }; break; case ConfigurationType.XmlFile: m_configurationLoader = new XMLConfigurationLoader { FilePath = systemSettings["ConnectionString"].Value }; break; } m_binaryCacheConfigurationLoader = new BinaryFileConfigurationLoader { FilePath = m_cachedBinaryConfigurationFile }; m_xmlCacheConfigurationLoader = new XMLConfigurationLoader { FilePath = m_cachedXmlConfigurationFile }; m_configurationLoader.StatusMessage += (o, args) => DisplayStatusMessage(args.Argument, UpdateType.Information); m_binaryCacheConfigurationLoader.StatusMessage += (o, args) => DisplayStatusMessage(args.Argument, UpdateType.Information); m_xmlCacheConfigurationLoader.StatusMessage += (o, args) => DisplayStatusMessage(args.Argument, UpdateType.Information); m_configurationLoader.ProcessException += ConfigurationLoader_ProcessException; m_binaryCacheConfigurationLoader.ProcessException += ConfigurationLoader_ProcessException; m_xmlCacheConfigurationLoader.ProcessException += ConfigurationLoader_ProcessException; m_reloadConfigQueue.Start(); #if !MONO try { // Attempt to assign desired process priority. Note that process will require SeIncreaseBasePriorityPrivilege or // Administrative privileges to make this change Process.GetCurrentProcess().PriorityClass = systemSettings["ProcessPriority"].ValueAs<ProcessPriorityClass>(); } catch (Exception ex) { LogException(ex); } #endif }