internal void Remove(ConfigurationType pConfigurationType) { if (_GeneratorsList.ContainsKey(pConfigurationType)) { _GeneratorsList.Remove(pConfigurationType); } }
protected Configuration(ConfigurationType type, string name, Boolean standard) { Name = name; Type = type; Standard = standard; ID = name; }
public Configuration(ConfigurationType type, string name,Boolean standard) { this.Name = name; this.Type = type; this.Standard = standard; this.ID = name; }
public static void Main(string[] args) { CategorizedSettingsElementCollection systemSettings = ConfigurationFile.Open(GetConfigurationFileName(args)).Settings["systemSettings"]; string cachePath = string.Format("{0}\\ConfigurationCache\\", FilePath.GetAbsolutePath("")); DataSet configuration; systemSettings.Add("NodeID", Guid.NewGuid().ToString(), "Unique Node ID"); 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("CachedConfigurationFile", "SystemConfiguration.xml", "File name for last known good system configuration (only cached for a Database or WebService connection)"); systemSettings.Add("ConfigurationBackups", 5, "Defines the total number of older backup configurations to maintain."); s_nodeID = systemSettings["NodeID"].ValueAs<Guid>(); s_configurationType = systemSettings["ConfigurationType"].ValueAs<ConfigurationType>(); s_connectionString = systemSettings["ConnectionString"].Value; s_dataProviderString = systemSettings["DataProviderString"].Value; s_cachedXmlConfigurationFile = FilePath.AddPathSuffix(cachePath) + systemSettings["CachedConfigurationFile"].Value; s_cachedBinaryConfigurationFile = FilePath.AddPathSuffix(cachePath) + FilePath.GetFileNameWithoutExtension(s_cachedXmlConfigurationFile) + ".bin"; s_configurationBackups = systemSettings["ConfigurationBackups"].ValueAs<int>(5); configuration = GetConfigurationDataSet(); ExecuteConfigurationCache(configuration); Console.WriteLine("Press 'Enter' to exit..."); Console.ReadLine(); }
internal void Add(UserControl frm, ConfigurationType pGeneratorsType) { if (!_GeneratorsList.ContainsKey(pGeneratorsType)) { _GeneratorsList.Add(pGeneratorsType, frm); } }
/// <summary> /// Gets a new configuration reader for the specified configuratin type /// </summary> public IConfigurationReader GetConfigurationReader(ConfigurationType configurationType) { switch (configurationType) { case ConfigurationType.Xml: return new XmlConfigurationReader(); default: throw new ConfigurationException("Unknown configuration type: " + configurationType); } }
public void Configuration(IAppBuilder app) { //if (BuildConfiguration == ConfigurationType.Dev) //{ // webDirectory = new DirectoryInfo(clientRootFolder + @"Sitter.Client\src"); //} //else if (BuildConfiguration == ConfigurationType.Prod) //{ //webDirectory = new DirectoryInfo(clientRootFolder + @"Sitter.Client\build"); //webDirectory = new DirectoryInfo(@"C:\_git\avocado\Main\src\Sitter.Client\src"); //} var config = new HttpConfiguration(); //config.Filters.Add(new AuthenticationFilter()); WebApiConfig.Register(config); IoCConfig.Register(config); app.UseWebApi(config); app.UseCors(CorsOptions.AllowAll); // STEP Map Folder Paths const string clientRootFolder = @"C:\_github\sitter\Main\src\"; DirectoryInfo webDirectory = null; BuildConfiguration = ConfigurationType.Dev; if (BuildConfiguration == ConfigurationType.Dev) { webDirectory = new DirectoryInfo(clientRootFolder + @"Sitter.Client\src"); } else if (BuildConfiguration == ConfigurationType.Prod) { webDirectory = new DirectoryInfo(clientRootFolder + @"Sitter.Client\build"); if (!IsValidateDirectory(webDirectory)) { // TODO JFK: Standardize hosting paths webDirectory = new DirectoryInfo(@"C:\SitterAppDeploy\appclient"); } } var isValid = IsValidateDirectory(webDirectory); if (!isValid) return; // Path to index var fsOptions = new FileServerOptions { EnableDirectoryBrowsing = true, FileSystem = new PhysicalFileSystem(webDirectory.FullName) }; fsOptions.StaticFileOptions.ContentTypeProvider = new TcsTypeProvider(); app.UseFileServer(fsOptions); }
public IConfigBean GetConfigBean(IPayLoad payload, ConfigurationType type) { ConfigurationPayLoad config = payload as ConfigurationPayLoad; if (type == ConfigurationType.File) { string serviceName = string.Format(_FileNameFormat, config.ID); ; return GetFileConfigBean(config, serviceName); } else { BaseAttributeConfigBean att = manager.GetConfigBean(config.ID) as BaseAttributeConfigBean; if (att == null) { return att; } att.Init(config.AppPath); return att; } }
public IConfigurationLoader Create(ConfigurationType configType) { IConfigurationLoader configurationLoader = null; switch (configType) { case ConfigurationType.WebConfig: configurationLoader = new WebConfigConfigurationLoader(); break; case ConfigurationType.DataBase: break; case ConfigurationType.File: throw new NotImplementedException("The are no implementation for file configuration"); break; default: throw new Exception("Incorrect Inversion Of Control Container Type"); } return configurationLoader; }
/// <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 }
private void BackupConfiguration(ConfigurationType configType, string configurationFile) { try { // Create multiple backup configurations, if requested for (int i = m_configurationBackups; i > 0; i--) { string origConfigFile = configurationFile + ".backup" + (i == 1 ? "" : (i - 1).ToString()); if (File.Exists(origConfigFile)) { string nextConfigFile = configurationFile + ".backup" + i; if (File.Exists(nextConfigFile)) File.Delete(nextConfigFile); File.Move(origConfigFile, nextConfigFile); } } } catch (Exception ex) { DisplayStatusMessage("Failed to create extra backup {0} configurations due to exception: {1}", UpdateType.Warning, configType, ex.Message); LogException(ex); } try { if (m_configurationBackups > 0) { // Back up current configuration file, if any if (File.Exists(configurationFile)) { string backupConfigFile = configurationFile + ".backup"; if (File.Exists(backupConfigFile)) File.Delete(backupConfigFile); File.Move(configurationFile, backupConfigFile); } } } catch (Exception ex) { DisplayStatusMessage("Failed to backup last known cached {0} configuration due to exception: {1}", UpdateType.Warning, configType, ex.Message); LogException(ex); } }
/// <inheritdoc /> public void LoadConfiguration(SpellingConfigurationFile configuration) { IEnumerable<string> folders; cboAvailableLanguages.ItemsSource = null; lbAdditionalFolders.Items.Clear(); lbSelectedLanguages.Items.Clear(); var dataSource = new List<PropertyState>(); if(configuration.ConfigurationType != ConfigurationType.Global) dataSource.AddRange(new[] { PropertyState.Inherited, PropertyState.Yes, PropertyState.No }); else dataSource.AddRange(new[] { PropertyState.Yes, PropertyState.No }); cboDetermineResxLang.ItemsSource = dataSource; cboDetermineResxLang.SelectedValue = configuration.ToPropertyState( PropertyNames.DetermineResourceFileLanguageFromName); configType = configuration.ConfigurationType; relatedFilename = Path.GetFileNameWithoutExtension(configuration.Filename); configFilePath = Path.GetDirectoryName(configuration.Filename); isGlobal = configuration.ConfigurationType == ConfigurationType.Global; if(isGlobal) { chkInheritAdditionalFolders.IsChecked = false; chkInheritAdditionalFolders.Visibility = Visibility.Collapsed; } else chkInheritAdditionalFolders.IsChecked = configuration.ToBoolean( PropertyNames.InheritAdditionalDictionaryFolders); if(configuration.HasProperty(PropertyNames.AdditionalDictionaryFolders)) { folders = configuration.ToValues(PropertyNames.AdditionalDictionaryFolders, PropertyNames.AdditionalDictionaryFoldersItem); } else folders = Enumerable.Empty<string>(); foreach(string f in folders) lbAdditionalFolders.Items.Add(f); var sd = new SortDescription { Direction = ListSortDirection.Ascending }; lbAdditionalFolders.Items.SortDescriptions.Add(sd); selectedLanguages.Clear(); selectedLanguages.AddRange(configuration.ToValues(PropertyNames.SelectedLanguages, PropertyNames.SelectedLanguagesItem, true).Distinct(StringComparer.OrdinalIgnoreCase)); this.LoadAvailableLanguages(); }
/// <inheritdoc /> public bool AppliesTo(ConfigurationType configurationType) { return(true); }
public Configuration(string desiredPrefix, ConfigurationType desiredConfigType) { Prefix = desiredPrefix; ConfigType = desiredConfigType; CustomFieldTable = new Hashtable(); AdvertisesPresentationPage = false; }
internal VcProjectConfiguration(XmlElement elem, VcProject parentProject, DirectoryInfo outputDir) : base(elem, parentProject, outputDir) { // determine relative output directory (outdir) XmlAttribute outputDirAttribute = elem.Attributes["OutputDirectory"]; if (outputDirAttribute != null) { _rawRelativeOutputDir = outputDirAttribute.Value; } // get intermediate directory and expand macros XmlAttribute intermidiateDirAttribute = elem.Attributes["IntermediateDirectory"]; if (intermidiateDirAttribute != null) { _rawIntermediateDir = intermidiateDirAttribute.Value; } // get referencespath directory and expand macros XmlAttribute referencesPathAttribute = elem.Attributes["ReferencesPath"]; if (referencesPathAttribute != null) { _rawReferencesPath = StringUtils.ConvertEmptyToNull(referencesPathAttribute.Value); } string managedExtentions = GetXmlAttributeValue(elem, "ManagedExtensions"); if (managedExtentions != null) { switch(managedExtentions.ToLower()) { case "false": case "0": _managedExtensions = false; break; case "true": case "1": _managedExtensions = true; break; default: throw new BuildException(String.Format("ManagedExtensions '{0}' is not supported yet.",managedExtentions)); } } // get configuration type string type = GetXmlAttributeValue(elem, "ConfigurationType"); if (type != null) { _type = (ConfigurationType) Enum.ToObject(typeof(ConfigurationType), int.Parse(type, CultureInfo.InvariantCulture)); } string wholeProgramOptimization = GetXmlAttributeValue(elem, "WholeProgramOptimization"); if (wholeProgramOptimization != null) { _wholeProgramOptimization = string.Compare(wholeProgramOptimization.Trim(), "true", true, CultureInfo.InvariantCulture) == 0; } string characterSet = GetXmlAttributeValue(elem, "CharacterSet"); if (characterSet != null) { _characterSet = (CharacterSet) Enum.ToObject(typeof(CharacterSet), int.Parse(characterSet, CultureInfo.InvariantCulture)); } // get MFC settings string useOfMFC = GetXmlAttributeValue(elem, "UseOfMFC"); if (useOfMFC != null) { _useOfMFC = (UseOfMFC) Enum.ToObject(typeof(UseOfMFC), int.Parse(useOfMFC, CultureInfo.InvariantCulture)); } // get ATL settings string useOfATL = GetXmlAttributeValue(elem, "UseOfATL"); if (useOfATL != null) { _useOfATL = (UseOfATL) Enum.ToObject(typeof(UseOfATL), int.Parse(useOfATL, CultureInfo.InvariantCulture)); } _linkerConfiguration = new LinkerConfig(this); }
public IConfigBean GetConfigBean(IPayLoad payload, ConfigurationType type) { return manager.GetConfigBean(_Id); //return component.GetRenderer().Render(context, component); }
private bool LoadSettings(ConfigurationType configType, object item) { _configType = configType; switch (configType) { case ConfigurationType.AppConfig: return LoadConfig(item); case ConfigurationType.FromFile: string fileName = null != item ? item.ToString() : string.Empty; return LoadFile(File.Exists(fileName) ? fileName : ConfigFileName); default: return false; } }
/// <summary> /// <para> /// Creates a new instance with the given configuration and configuration type. /// </para> /// </summary> /// /// <param name="configuration"> /// The IConfiguration instance that is used as the object source in this class. Can't be null. /// </param> /// <param name="configurationType"> /// The configuration hierarchical structure type of this object source. /// </param> /// /// <exception cref="ArgumentNullException"> /// If the configuration is null. /// </exception> /// <exception cref="ArgumentException"> /// If the value is not a pre-defined ConfigurationType value. /// </exception> public ConfigurationAPIObjectFactory(IConfiguration configuration, ConfigurationType configurationType) { ValidateNotNull(configuration, "configuration"); if (!Enum.IsDefined(typeof(ConfigurationType), configurationType)) { throw new ArgumentException("Configuration type must be Flat or Nested.", "configurationType"); } this.configuration = configuration; this.configurationType = configurationType; }
public ConfigParser(IKatushaDbContext dbContext) { var configurationData = new ConfigurationType(Section.Configuration) { Repository = new ConfigurationDataRepositoryDB(dbContext), MinimumAllowed = 2, MaximumAllowed = 2, LanguageOrder = -1, OrderOrder = -1 }; var resource = new ConfigurationType(Section.Resource) { Repository = new ResourceRepositoryDB(dbContext), MinimumAllowed = 3, MaximumAllowed = 3, LanguageOrder = 0, OrderOrder = -1 }; var resourceLookup = new ConfigurationType(Section.ResourceLookup) { Repository = new ResourceLookupRepositoryDB(dbContext), MinimumAllowed = 6, MaximumAllowed = 6, LanguageOrder = 0, OrderOrder = 4 }; _dependencies = new Dictionary<Section, ConfigurationType> { {Section.Configuration, configurationData}, {Section.Resource, resource}, {Section.ResourceLookup, resourceLookup} }; //_geoTimeZoneRepository = new GeoTimeZoneRepositoryDB(dbContext); //_geoNameRepository = new GeoNameRepositoryDB(dbContext); //_geoCountryRepository = new GeoCountryRepositoryDB(dbContext); //_geoLanguageRepository = new GeoLanguageRepositoryDB(dbContext); }
/// <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) { // Initialize Iaon session m_iaonSession = new IaonSession(); m_iaonSession.StatusMessage += m_iaonSession_StatusMessage; m_iaonSession.ProcessException += m_iaonSession_ProcessException; // Create a handler for unobserved task exceptions TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; // Make sure default service settings exist ConfigurationFile configFile = ConfigurationFile.Current; string cachePath = string.Format("{0}\\ConfigurationCache\\", FilePath.GetAbsolutePath("")); // 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("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("GCGenZeroInterval", DefaultGCGenZeroInterval, "Defines the interval, in milliseconds, over which to force a generation zero garbage collection. Set to -1 to disable."); 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."); // 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", "Example SQLite database connection string"); exampleSettings.Add("SQLite.DataProviderString", "AssemblyName={System.Data.SQLite, Version=1.0.74.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"); // Retrieve configuration cache directory as defined in the config file cachePath = 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 due to exception: {0}", UpdateType.Alarm, ex.Message); m_serviceHelper.ErrorLogger.Log(ex); } // Initialize system settings m_configurationType = systemSettings["ConfigurationType"].ValueAs<ConfigurationType>(); m_connectionString = systemSettings["ConnectionString"].Value; m_dataProviderString = systemSettings["DataProviderString"].Value; m_cachedXmlConfigurationFile = FilePath.AddPathSuffix(cachePath) + systemSettings["CachedConfigurationFile"].Value; m_cachedBinaryConfigurationFile = FilePath.AddPathSuffix(cachePath) + FilePath.GetFileNameWithoutExtension(m_cachedXmlConfigurationFile) + ".bin"; m_configurationBackups = systemSettings["ConfigurationBackups"].ValueAs<int>(DefaultConfigurationBackups); m_uniqueAdapterIDs = systemSettings["UniqueAdaptersIDs"].ValueAsBoolean(true); m_allowRemoteRestart = systemSettings["AllowRemoteRestart"].ValueAsBoolean(true); m_preferCachedConfiguration = systemSettings["PreferCachedConfiguration"].ValueAsBoolean(false); m_configurationCacheComplete = new AutoResetEvent(true); m_queuedConfigurationCachePending = new object(); // Setup default thread pool size try { ThreadPool.SetMinThreads(systemSettings["MinThreadPoolWorkerThreads"].ValueAs<int>(DefaultMinThreadPoolSize), systemSettings["MinThreadPoolIOPortThreads"].ValueAs<int>(DefaultMinThreadPoolSize)); ThreadPool.SetMaxThreads(systemSettings["MaxThreadPoolWorkerThreads"].ValueAs<int>(DefaultMaxThreadPoolSize), systemSettings["MaxThreadPoolIOPortThreads"].ValueAs<int>(DefaultMaxThreadPoolSize)); } catch (Exception ex) { DisplayStatusMessage("Failed to set desired thread pool size due to exception: {0}", UpdateType.Alarm, ex.Message); m_serviceHelper.ErrorLogger.Log(ex); } // Define a generation zero garbage collection timer int gcGenZeroInterval = systemSettings["GCGenZeroInterval"].ValueAs<int>(DefaultGCGenZeroInterval); if (gcGenZeroInterval > 0) { m_gcGenZeroTimer = new System.Timers.Timer(); m_gcGenZeroTimer.Elapsed += m_gcGenZeroTimer_Elapsed; m_gcGenZeroTimer.Interval = gcGenZeroInterval; m_gcGenZeroTimer.Enabled = true; } // Define guid with query string delimeters according to database needs Dictionary<string, string> settings = m_connectionString.ParseKeyValuePairs(); string setting; if (settings.TryGetValue("Provider", out setting)) { // Check if provider is for Access since it uses braces as Guid delimeters if (setting.StartsWith("Microsoft.Jet.OLEDB", StringComparison.OrdinalIgnoreCase)) { m_nodeIDQueryString = "{" + m_iaonSession.NodeID + "}"; // Make sure path to Access database is fully qualified if (settings.TryGetValue("Data Source", out setting)) { settings["Data Source"] = FilePath.GetAbsolutePath(setting); m_connectionString = settings.JoinKeyValuePairs(); } } } if (string.IsNullOrWhiteSpace(m_nodeIDQueryString)) m_nodeIDQueryString = "'" + m_iaonSession.NodeID + "'"; #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) { m_serviceHelper.ErrorLogger.Log(ex, false); } #endif }
internal Boolean Contains(ConfigurationType pConfigurationType) { return _GeneratorsList.ContainsKey(pConfigurationType); }
public ConfigurationMethodAttribute(ConfigurationType registerAs) { RegisterAs = registerAs; }
private DataSet GetConfigurationDataSet(ConfigurationType configType, string connectionString, string dataProviderString) { DataSet configuration = null; bool configException = false; Ticks startTime = DateTime.UtcNow.Ticks; double elapsedTime; switch (configType) { case ConfigurationType.Database: // Attempt to load configuration from a database connection IDbConnection connection = null; Dictionary<string, string> settings; string assemblyName, connectionTypeName, adapterTypeName; Assembly assembly; Type connectionType, adapterType; DataTable entities, source, destination; try { settings = dataProviderString.ParseKeyValuePairs(); assemblyName = settings["AssemblyName"].ToNonNullString(); connectionTypeName = settings["ConnectionType"].ToNonNullString(); adapterTypeName = settings["AdapterType"].ToNonNullString(); if (string.IsNullOrWhiteSpace(connectionTypeName)) throw new InvalidOperationException("Database connection type was not defined."); if (string.IsNullOrWhiteSpace(adapterTypeName)) throw new InvalidOperationException("Database adapter type was not defined."); assembly = Assembly.Load(new AssemblyName(assemblyName)); connectionType = assembly.GetType(connectionTypeName); adapterType = assembly.GetType(adapterTypeName); connection = (IDbConnection)Activator.CreateInstance(connectionType); connection.ConnectionString = m_connectionString; connection.Open(); DisplayStatusMessage("Database configuration connection opened.", UpdateType.Information); // Execute any defined startup data operations ExecuteStartupDataOperations(connection, adapterType); configuration = new DataSet("Iaon"); // Load configuration entities defined in database entities = connection.RetrieveData(adapterType, "SELECT * FROM ConfigurationEntity WHERE Enabled <> 0 ORDER BY LoadOrder"); entities.TableName = "ConfigurationEntity"; // Add configuration entities table to system configuration for reference configuration.Tables.Add(entities.Copy()); Ticks operationStartTime; double operationElapsedTime; // Add each configuration entity to the system configuration foreach (DataRow entityRow in entities.Rows) { // Load configuration entity data filtered by node ID operationStartTime = DateTime.UtcNow.Ticks; source = connection.RetrieveData(adapterType, string.Format("SELECT * FROM {0} WHERE NodeID={1}", entityRow["SourceName"].ToString(), m_nodeIDQueryString)); operationElapsedTime = (DateTime.UtcNow.Ticks - operationStartTime).ToSeconds(); // Update table name as defined in configuration entity source.TableName = entityRow["RuntimeName"].ToString(); DisplayStatusMessage("Loaded {0} row{1} from \"{2}\" in {3}...", UpdateType.Information, source.Rows.Count, source.Rows.Count == 1 ? "" : "s", source.TableName, operationElapsedTime < 0.01D ? "less than a second" : operationElapsedTime.ToString("0.00") + " seconds"); operationStartTime = DateTime.UtcNow.Ticks; // Clone data source destination = source.Clone(); // Get destination column collection DataColumnCollection columns = destination.Columns; // Remove redundant node ID column columns.Remove("NodeID"); // Pre-cache column index translation after removal of NodeID column to speed data copy Dictionary<int, int> columnIndex = new Dictionary<int, int>(); foreach (DataColumn column in columns) { columnIndex[column.Ordinal] = source.Columns[column.ColumnName].Ordinal; } // Manually copy-in each row into table foreach (DataRow sourceRow in source.Rows) { DataRow newRow = destination.NewRow(); // Copy each column of data in the current row for (int x = 0; x < columns.Count; x++) { newRow[x] = sourceRow[columnIndex[x]]; } // Add new row to destination table destination.Rows.Add(newRow); } operationElapsedTime = (DateTime.UtcNow.Ticks - operationStartTime).ToSeconds(); // Add entity configuration data to system configuration configuration.Tables.Add(destination); DisplayStatusMessage("{0} configuration pre-cache completed in {1}.", UpdateType.Information, source.TableName, operationElapsedTime < 0.01D ? "less than a second" : operationElapsedTime.ToString("0.00") + " seconds"); } DisplayStatusMessage("Database configuration successfully loaded.", UpdateType.Information); } catch (Exception ex) { configException = true; DisplayStatusMessage("Failed to load database configuration due to exception: {0} Attempting to use last known good configuration.", UpdateType.Warning, ex.Message); m_serviceHelper.ErrorLogger.Log(ex); configuration = null; } finally { if (connection != null) connection.Dispose(); DisplayStatusMessage("Database configuration connection closed.", UpdateType.Information); } break; case ConfigurationType.WebService: // Attempt to load configuration from webservice based connection WebRequest request = null; Stream response = null; try { DisplayStatusMessage("Webservice configuration connection opened.", UpdateType.Information); configuration = new DataSet(); request = WebRequest.Create(connectionString); response = request.GetResponse().GetResponseStream(); configuration.ReadXml(response); DisplayStatusMessage("Webservice configuration successfully loaded.", UpdateType.Information); } catch (Exception ex) { configException = true; DisplayStatusMessage("Failed to load webservice configuration due to exception: {0} Attempting to use last known good configuration.", UpdateType.Warning, ex.Message); m_serviceHelper.ErrorLogger.Log(ex); configuration = null; } finally { if (response != null) response.Dispose(); DisplayStatusMessage("Webservice configuration connection closed.", UpdateType.Information); } break; case ConfigurationType.BinaryFile: // Attempt to load cached binary configuration file try { DisplayStatusMessage("Loading binary based configuration from \"{0}\".", UpdateType.Information, connectionString); using (FileStream stream = File.OpenRead(connectionString)) { configuration = stream.DeserializeToDataSet(); } DisplayStatusMessage("Binary based configuration successfully loaded.", UpdateType.Information); } catch (Exception ex) { configException = true; DisplayStatusMessage("Failed to load binary based configuration due to exception: {0}.", UpdateType.Alarm, ex.Message); m_serviceHelper.ErrorLogger.Log(ex); configuration = null; } break; case ConfigurationType.XmlFile: // Attempt to load cached XML configuration file try { DisplayStatusMessage("Loading XML based configuration from \"{0}\".", UpdateType.Information, connectionString); configuration = new DataSet(); configuration.ReadXml(connectionString); DisplayStatusMessage("XML based configuration successfully loaded.", UpdateType.Information); } catch (Exception ex) { configException = true; DisplayStatusMessage("Failed to load XML based configuration due to exception: {0}.", UpdateType.Alarm, ex.Message); m_serviceHelper.ErrorLogger.Log(ex); configuration = null; } break; } if (!configException) { elapsedTime = (DateTime.UtcNow.Ticks - startTime).ToSeconds(); DisplayStatusMessage("{0} configuration load process completed in {1}...", UpdateType.Information, configType, elapsedTime < 0.01D ? "less than a second" : elapsedTime.ToString("0.00") + " seconds"); } return configuration; }
public void GetSettingProperties_FromNestedWithIgnore() { var settings = ConfigurationType.GetSettingProperties(typeof(Foo)).ToList(); settings.Count.Verify().IsEqual(3); }
/// <summary> /// Assert that the output directory and output file exist. If they do not exist then /// an assertion exception is thrown. /// </summary> /// <param name="configuration"></param> /// <param name="output"></param> /// <param name="solutionName"></param> protected void AssertOutputExists (ConfigurationType configType, OutputType outputType, string solutionName) { string baseDir = Path.Combine(this.CurrentBaseDir.FullName, solutionName); string binDir = Path.Combine(baseDir, "bin"); string outputDir = Path.Combine(binDir, configType.ToString()); string outputFile = Path.Combine(outputDir, String.Format("{0}.{1}", solutionName, outputType.ToString())); DirectoryInfo od = new DirectoryInfo(outputDir); FileInfo of = new FileInfo(outputFile); Assert.IsTrue(od.Exists, String.Format("Output directory does not exist: {0}.", od.FullName)); Assert.IsTrue(of.Exists, String.Format("Output file does not exist: {0}.", of.FullName)); }
/// <inheritdoc /> public bool AppliesTo(ConfigurationType configurationType) { return(configurationType == ConfigurationType.Global); }