private bool Load(string file) { var map = new ExeConfigurationFileMap { ExeConfigFilename = file }; config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); var xml = new XmlDocument(); using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read)) xml.Load(stream); //var cfgSections = xml.GetElementsByTagName("configSections"); //if (cfgSections.Count > 0) //{ // foreach (XmlNode node in cfgSections[0].ChildNodes) // { // var type = System.Activator.CreateInstance( // Type.GetType(node.Attributes["type"].Value)) // as IConfigurationSectionHandler; // if (type == null) continue; // customSections.Add(node.Attributes["name"].Value, type); // } //} return config.HasFile; }
protected BulkLoader(Configuration.Configuration config) { _jobs = new JobList(); _jobs.RowsInserted += (s, e) => OnRowsInserted(e); Config = config; DefaultSchema = "dbo"; }
public ScreenshotRepository() { config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = "App.config" }, ConfigurationUserLevel.None); connectionString = config.ConnectionStrings.ConnectionStrings["MySql"].ConnectionString; db = new MySqlConnection(connectionString); }
private OptionsForm(bool local) { InitializeComponent(); // Copy the Bootstrap.exe file to New.exe, // so that the configuration file will load properly string currentDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); string sandboxDir = Path.Combine(currentDir, "Sandbox"); if (!File.Exists(Path.Combine(sandboxDir, "New.exe"))) { File.Copy( Path.Combine(sandboxDir, "Bootstrap.exe"), Path.Combine(sandboxDir, "New.exe") ); } string filename = local ? "New.exe" : "Bootstrap.exe"; string filepath = Path.Combine(sandboxDir, filename); _Configuration = ConfigurationManager.OpenExeConfiguration(filepath); // Get the DDay.Update configuration section _Cfg = _Configuration.GetSection("DDay.Update") as DDayUpdateConfigurationSection; // Set the default setting on which application folder to use. cbAppFolder.SelectedIndex = 0; SetValuesFromConfig(); if (!local) _Configuration.SaveAs(Path.Combine(sandboxDir, "New.exe.config")); }
// https://msdn.microsoft.com/en-us/library/tkwek5a4%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 // Example Configuration Code for an HTTP Module: public static void AddModule(Configuration config, string moduleName, string moduleClass) { HttpModulesSection section = (HttpModulesSection)config.GetSection("system.web/httpModules"); // Create a new module action object. HttpModuleAction moduleAction = new HttpModuleAction( moduleName, moduleClass); // "RequestTimeIntervalModule", "Samples.Aspnet.HttpModuleExamples.RequestTimeIntervalModule"); // Look for an existing configuration for this module. int indexOfModule = section.Modules.IndexOf(moduleAction); if (-1 != indexOfModule) { // Console.WriteLine("RequestTimeIntervalModule module is already configured at index {0}", indexOfModule); } else { section.Modules.Add(moduleAction); if (!section.SectionInformation.IsLocked) { config.Save(); // Console.WriteLine("RequestTimeIntervalModule module configured."); } } }
public BaseTest() { var configMap = new ExeConfigurationFileMap {ExeConfigFilename = "MySettings.config"}; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); if (config.HasFile) _config = config; }
///<summary> ///创建ConnectionString(如果存在,先删除再创建) ///</summary> ///<param name="config">Configuration实例</param> ///<param name="newName">连接字符串名称</param> ///<param name="newConString">连接字符串内容</param> ///<param name="newProviderName">数据提供程序名称</param> public static Boolean CreateConnectionStringsConfig(Configuration config, string newName, string newConString, string newProviderName) { if (config == null && string.IsNullOrEmpty(newName) && string.IsNullOrEmpty(newConString) && string.IsNullOrEmpty(newProviderName)) { return false; } bool isModified = false; //记录该连接串是否已经存在 //如果要更改的连接串已经存在 if (config.ConnectionStrings.ConnectionStrings[newName] != null) { isModified = true; } //新建一个连接字符串实例 ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName); // 如果连接串已存在,首先删除它 if (isModified) { config.ConnectionStrings.ConnectionStrings.Remove(newName); } // 将新的连接串添加到配置文件中. config.ConnectionStrings.ConnectionStrings.Add(mySettings); // 保存对配置文件所作的更改 config.Save(ConfigurationSaveMode.Modified); return true; }
public static SerializationSectionGroup GetSectionGroup (ConfigurationType config) { var ret = (SerializationSectionGroup) config.GetSectionGroup ("system.runtime.serialization"); if (ret == null) throw new SystemException ("Internal configuration error: section 'system.runtime.serialization' was not found."); return ret; }
private void SetConfigValue(string configKey , string configValue,Configuration conf) { if (conf.AppSettings.Settings[configKey] == null) conf.AppSettings.Settings.Add(configKey, configValue); else conf.AppSettings.Settings[configKey].Value = configValue; }
/// <summary> /// Retrieves the current UserSettingsSection from the specified configuration, if none /// exists a new one is created. If a previous version of the userSettings exists they /// will be copied to the UserSettingsSection. /// </summary> public static UserSettingsSection UserSettingsFrom(Configuration config) { UserSettingsSection settings = null; try { settings = (UserSettingsSection)config.Sections[SECTION_NAME]; } catch(InvalidCastException) { config.Sections.Remove(SECTION_NAME); } if (settings == null) { settings = new UserSettingsSection(); settings.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser; settings.SectionInformation.RestartOnExternalChanges = false; settings.SectionInformation.Type = String.Format("{0}, {1}", typeof(UserSettingsSection).FullName, typeof(UserSettingsSection).Assembly.GetName().Name); UpgradeUserSettings(config, settings); config.Sections.Add(SECTION_NAME, settings); } else if (!config.HasFile) UpgradeUserSettings(config, settings); if (settings.IsModified()) { try { config.Save(); } catch (Exception e) { Trace.TraceError("{1}\r\n{0}", e, "Failed to save configuration."); } } return settings; }
//private static string AppConfigPath() //{ // return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppConfigFileName); //} /// <summary> /// 获取当前应用配置 /// </summary> /// <returns></returns> public Configuration getCurrentConfig(char AppType = EnumAppType.Web) { if (currentConfig==null){ currentConfig = UtilSystem.getCurrentConfig(AppType); } return currentConfig; }
public MocsForm() { InitializeComponent(); _configuration = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); _notifyIcon = new NotifyIcon(); _notifyIcon.Text = "Mocs Notification"; _notifyIcon.Visible = true; _notifyIcon.Icon = new Icon(Assembly.GetExecutingAssembly().GetManifestResourceStream("MocsClient.sync.ico")); _notifyIcon.DoubleClick += new EventHandler(_notifyIcon_DoubleClick); // Old school balloon tip //_notifyIcon.BalloonTipClicked += new EventHandler(_notifyIcon_BalloonTipClicked); BuildContextMenu(); _notifyIcon.ContextMenu = _contextMenu; _messageInterceptor = new MessageInterceptor(); _messageInterceptor.Initialize(); dataGridViewNotification.MouseWheel += new MouseEventHandler(dataGridViewNotification_MouseWheel); dataGridViewNotification.KeyDown += new KeyEventHandler(dataGridViewNotification_KeyDown); dataGridViewNotification.KeyUp += new KeyEventHandler(dataGridViewNotification_KeyUp); }
public ConfigurationMap(Configuration file, IPluginSettings settings, bool autoLoad) { this.file = file; this.settings = settings; if (autoLoad) Load(); }
public FormUpdater(string patcherExecutable, string patcherArguments) { this.patcherExecutable = patcherExecutable; this.patcherArguments = patcherArguments; try { hyperConfigFile = ConfigurationManager.OpenExeConfiguration(patcherExecutable); } catch (Exception) { MessageBox.Show("Failed to load " + patcherExecutable + ".config file", "Selfupdater"); Environment.Exit(0); } hyperSettings = hyperConfigFile.AppSettings.Settings; hyperFolder = new DirectoryInfo(Environment.CurrentDirectory); InitializeComponent(); try { hyperVersion = Convert.ToUInt32(hyperSettings["hyperVersion"].Value); patchesWebPath = new Uri(hyperSettings["patchesWebPath"].Value); } catch (Exception) { hyperVersion = 0; } MessageBox.Show("Updates are going to be installed now.", "Selfupdater"); InitUpdateProcess(); }
/// <summary> /// This method will retrieve the configuration settings. /// </summary> private void GetConfiguration() { try { m_config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); if (m_config.Sections["TracePreferences"] == null) { m_settings = new TracePreferences(); m_config.Sections.Add("TracePreferences", m_settings); m_config.Save(ConfigurationSaveMode.Full); } else m_settings = (TracePreferences)m_config.GetSection("TracePreferences"); } catch (InvalidCastException e) { System.Diagnostics.Trace.WriteLine("Preference Error - " + e.Message, "MainForm.GetConfiguration"); MessageBoxOptions options = 0; MessageBox.Show(Properties.Resources.PREF_NOTLOADED, Properties.Resources.PREF_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, options); m_settings = new TracePreferences(); } catch (ArgumentException e) { System.Diagnostics.Trace.WriteLine("Argument Error - " + e.Message, "MainForm.GetConfiguration"); throw; } catch (ConfigurationErrorsException e) { System.Diagnostics.Trace.WriteLine("Configuration Error - " + e.Message, "MainForm.GetConfiguration"); throw; } }
private static void CrearArchivoConfig() { XmlTextWriter.Create(Assembly.GetExecutingAssembly().Location + ".config"); _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); _config.Save(); }
/// <summary> /// Loads the config file /// </summary> public TreeTabConfig() { try { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); System.Uri uri = new Uri(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location)); fileMap.ExeConfigFilename = Path.Combine(uri.LocalPath, CONFIG_FILENAME); config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); if (config.HasFile) { ConfigurationSection cs = config.GetSection(CONTEXT_MENU_ICONS_SECTION); if (cs != null) { XmlDocument xmlConf = new XmlDocument(); xmlConf.LoadXml(cs.SectionInformation.GetRawXml()); xmlContextMenuIcons = (XmlElement)xmlConf.FirstChild; this.isCorrectlyLoaded = true; } } } catch { this.isCorrectlyLoaded = false; } }
/// <summary> /// Merge default settings (install DLLs) with current settings (user.config) /// Read settings from %APPDATA%\ho\ho_tools\user.config /// </summary> public AddinSettings() { Configuration roamingConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); //the roamingConfig now get a path such as C:\Users\<user>\AppData\Roaming\Sparx_Systems_Pty_Ltd\DefaultDomain_Path_2epjiwj3etsq5yyljkyqqi2yc4elkrkf\9,_2,_0,_921\user.config // which I don't like. So we move up three directories and then add a directory for the EA Navigator so that we get // C:\Users\<user>\AppData\Roaming\GeertBellekens\EANavigator\user.config string configFileName = System.IO.Path.GetFileName(roamingConfig.FilePath); string configDirectory = System.IO.Directory.GetParent(roamingConfig.FilePath).Parent.Parent.Parent.FullName; string newConfigFilePath = configDirectory + @"\ho\ho_Tools\" + configFileName; // Map the roaming configuration file. This // enables the application to access // the configuration file using the // System.Configuration.Configuration class ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap(); configFileMap.ExeConfigFilename = newConfigFilePath; // Get the mapped configuration file. currentConfig = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); //merge the default settings this.mergeDefaultSettings(); this.shortcutsSearch = getShortcutsSearch(); this.shortcutsServices = getShortcutsServices(); this.globalShortcutsService = getGlobalShortcutsService(); this.globalShortcutsSearch = getGlobalShortcutsSearch(); getConnector(_logicalConnectors); getConnector(_activityConnectors); getAllServices(); updateSearchesAndServices(); }
protected void btnSubmit_Click(object sender, EventArgs e) { Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); //操作appSettings AppSettingsSection appseting = (AppSettingsSection)Configuration.GetSection("appSettings"); //修改设置 try { appseting.Settings["txtiosapplink"].Value = this.txtiosapplink.Text; } catch (Exception) { appseting.Settings.Add("txtiosapplink", this.txtiosapplink.Text); } try { appseting.Settings["txtapklink"].Value = this.txtapklink.Text; } catch (Exception) { appseting.Settings.Add("txtapklink", this.txtapklink.Text); } Configuration.Save(); }
public ImageAnalyzer() { configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); confCollection = configManager.AppSettings.Settings; string keyId = confCollection["FaceAPIKey"].Value; faceDetector = new FaceServiceClient(keyId); }
public Gadget() { InitializeComponent(); cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); Left = Int32.Parse(cfg.AppSettings.Settings["LocationX"].Value); Top = Int32.Parse(cfg.AppSettings.Settings["LocationY"].Value); Width = Int32.Parse(cfg.AppSettings.Settings["Width"].Value); Height = Int32.Parse(cfg.AppSettings.Settings["Height"].Value); string symbols = cfg.AppSettings.Settings["Symbols"].Value; if (!string.IsNullOrWhiteSpace(symbols)) { string[] arr = symbols.Split(new char[] { ';' }); cbSymbols.ItemsSource = arr; } SourceInitialized += new EventHandler(Gadjet_SourceInitialized); int defaultCardRank = Int32.Parse(cfg.AppSettings.Settings["DefaultRank"].Value); if (defaultCardRank < 0) defaultCardRank = 10; presenter = new CardStackPresenter(this, defaultCardRank); presenter.NextCard(); }
static SecureSettings() { if (System.Web.HttpContext.Current != null) _config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); else _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); }
public Settings() { try { Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); Msg.Log("Loading config file \"" + Path.GetFileName(Config.FilePath) + "\"."); } catch (ConfigurationErrorsException) { Msg.Log ("Error reading config file!"); Msg.MsgBox("Error reading config file!"); return; } //Create keys with default values in config file if they don't exist yet. this.Add("GameDir", null); this.Add("ModConfig", "Default"); this.Add("ModConfigList", "Default"); this.Add("ModConfig_Default", ""); this.Add("SkinConfig", "Default"); this.Add("SkinConfigList", "Default"); this.Add("SkinConfig_Default", ""); this.Add("ModsReplaceDefaultSkins", "True"); this.Add("ModConfigAutosave", "True"); this.Add("SkinConfigAutosave", "True"); this.Save(); //Save config to disk. }
public ContentPathProvider(VirtualPathProvider baseProvider, Configuration.Configuration services) { _baseProvider = baseProvider; _config = services; _internalResources = new Dictionary<string, string>(); switch (_config.ViewEngineOptions.Type) { case Configuration.ViewEngineType.Razor: _extension = ".cshtml"; break; case Configuration.ViewEngineType.ASPX: _extension = ".aspx"; break; default: throw new ArgumentException("Invalid ViewEngine Specified."); } Action<string> addResource = (file) => _internalResources.Add(file + _extension, string.Format("Meek.Content.{0}.{1}{2}", _config.ViewEngineOptions.Type.ToString(), file, _extension)); addResource("Manage"); addResource("CreatePartial"); addResource("List"); addResource("BrowseFiles"); addResource("UploadFileSuccess"); }
static ExplorerSettings() { config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); try { /*if (config.AppSettings.Settings["LoggerMode"].Value == "info") logger = LoggerMode.info; else if (config.AppSettings.Settings["LoggerMode"].Value == "debug") logger = LoggerMode.debug; else throw new Exception("LoggerMode is set improperly.");*/ loggingDirectory = config.AppSettings.Settings["LoggingDirectory"].Value; storageDirectory = config.AppSettings.Settings["StorageDirectory"].Value; //connectionString = config.ConnectionStrings.ConnectionStrings[config.AppSettings.Settings["SQLProvider"].Value].ConnectionString; tracingDirectory = config.AppSettings.Settings["TracingDirectory"].Value; workingMode = (ManagerType)Enum.Parse(typeof(ManagerType), config.AppSettings.Settings["WorkingMode"].Value); staticGenerationDirectory = config.AppSettings.Settings["StaticGenerationDirectory"].Value; matrixConvertionToolDirectory = config.AppSettings.Settings["MatrixConvertionToolDirectory"].Value; modelCheckingToolDirectory = config.AppSettings.Settings["ModelCheckingToolDirectory"].Value; } catch { throw new CoreException("The structure of Configuration file is not correct."); } }
protected static Configuration ConfigAppSettingsto(string filename) { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = filename; config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); return config; }
private void ConfigureAppSettings(Configuration config) { foreach (var setting in config.AppSettings.Settings.Cast<KeyValueConfigurationElement>()) { ConfigurationManager.AppSettings.Set(setting.Key, setting.Value); } }
public ConfigurationManager() { //_configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(exePath); _configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); SetDefaultSettings(); }
public WeatherOption() { try { string exeConfigPath = this.GetType().Assembly.Location; config = ConfigurationManager.OpenExeConfiguration(exeConfigPath); } catch (Exception ex) { //handle errror here.. means DLL has no sattelite configuration file. } if (config != null) { InitializeComponent(); txtApiKey.Text = GetAppSetting(config, SETTING_APIKEY); txtLat.Text = GetAppSetting(config, SETTING_LAT); txtLng.Text = GetAppSetting(config, SETTING_LONG); // If the lat/lng are not set, default it to InControl's lat/long values if (txtLat.Text == "yourlat") { txtLat.Text = base.getSetting(SETTING_LAT); } if (txtLng.Text == "yourlong") { txtLng.Text = base.getSetting(SETTING_LONG); } if (GetAppSetting(config, SETTING_SIGNS) == "metric") { radioMetric.IsChecked = true; } else { radioImperial.IsChecked = true; } } }
private NamedPipeMessageBus(Configuration configuration) { LoadConfiguration(configuration); _readThread = new Thread(ReadData); _readThread.Start(); }
public static void GetRoleServiceSection() { //<snippet4> // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); // Get the external Web services section. ScriptingWebServicesSectionGroup webServicesSection = (ScriptingWebServicesSectionGroup)configuration.GetSectionGroup( "system.web.extensions/scripting/webServices"); // Get the role service section. ScriptingRoleServiceSection roleSection = webServicesSection.RoleService; //</snippet4> }
public void StartSacta() { if (sModule == null) { //System.Diagnostics.Debug.Assert(false); System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); System.Configuration.KeyValueConfigurationElement s = config.AppSettings.Settings["Sistema"]; IdSistema = s.Value; sModule = new Sacta.SactaModule(IdSistema, MySqlConnectionToCd40); sModule.Start(); sModule.SactaActivityChanged += new Utilities.GenericEventHandler <System.Collections.Generic.Dictionary <string, object> >(sModule_SactaActivityChanged); } else { sModule.Start(); } }
protected void Button1_Click(object sender, EventArgs e) { // Get the application configuration file. System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/"); // <Snippet2> System.Web.Configuration.CacheSection cacheSection = (System.Web.Configuration.CacheSection)config.GetSection( "system.web/caching/cache"); // </Snippet2> // <Snippet6> // Increase the PrivateBytesLimit property to 0. cacheSection.PrivateBytesLimit = cacheSection.PrivateBytesLimit + 10; // </Snippet6> // <Snippet7> // Increase memory limit. cacheSection.PercentagePhysicalMemoryUsedLimit = cacheSection.PercentagePhysicalMemoryUsedLimit + 1; // </Snippet7> // <Snippet8> // Increase poll time. cacheSection.PrivateBytesPollTime = cacheSection.PrivateBytesPollTime + TimeSpan.FromMinutes(1); // </Snippet8> // <Snippet3> // Enable or disable memory collection. cacheSection.DisableMemoryCollection = !cacheSection.DisableMemoryCollection; // </Snippet3> // <Snippet4> // Enable or disable cache expiration. cacheSection.DisableExpiration = !cacheSection.DisableExpiration; // </Snippet4> // Save the configuration file. config.Save(System.Configuration.ConfigurationSaveMode.Modified); }
private void Insert() { rootCfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/petroneeds"); connection = rootCfg.ConnectionStrings.ConnectionStrings["petroneedsConnectionString2"].ConnectionString.ToString(); string sql; con = new SqlConnection(connection); con.ConnectionString = connection; con.Open(); sql = "INSERT INTO tbl_News (NewTitle, NewsDetail, DateCreated, image, status) VALUES ('" + Text_Title.Text + "', '" + Text_Details.Text + "', '" + Text_Date.Text + "', '" + Label2.Text + "', '0')"; comm = new SqlCommand(sql, con); comm.ExecuteNonQuery(); con.Close(); Reset_Items(); Label_Messages.Text = "Thank You, Your Record Saved"; }
private void Update() { rootCfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/petroneeds"); connection = rootCfg.ConnectionStrings.ConnectionStrings["petroneedsConnectionString2"].ConnectionString.ToString(); string sql; con = new SqlConnection(connection); con.ConnectionString = connection; con.Open(); sql = "UPDATE Mng_Word SET MngTitle = '" + Text_Title.Text + "', MngDetails ='" + Text_Details.Text + "', " + "MngDetails2 ='" + Text_Details2.Text + "', MngDetails3 ='" + Text_Details3.Text + "'"; comm = new SqlCommand(sql, con); comm.ExecuteNonQuery(); con.Close(); Reset_Items(); Label_Messages.Text = "Thank You, Your Record Saved"; }
public void EndSacta() { if (sModule == null) { //System.Diagnostics.Debug.Assert(false); System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); System.Configuration.KeyValueConfigurationElement s = config.AppSettings.Settings["Sistema"]; IdSistema = s.Value; sModule = new Sacta.SactaModule(IdSistema, MySqlConnectionToCd40); sModule.Stop(); } else { sModule.Stop(); } EstadoSacta = (byte)0; sModule = null; }
}//validateLogin private static OleDbConnection openConnection() { // path to the root of the web site where the web.config file exists string configPath = "~"; // access to web.config file System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath); // declaring the connection string string conStr = null; // get the value(s) in the connection string if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) { try { conStr = rootWebConfig.ConnectionStrings.ConnectionStrings["conStrBMC"].ToString(); } catch (Exception ex) { conStr = null; } if (conStr != null) { HttpContext.Current.Trace.Warn("BMC connection string = \"{0}\"", conStr); //Create an OleDbConnection object using the Connection String OleDbConnection cn = new OleDbConnection(conStr); //Open the connection. cn.Open(); return cn; } else { HttpContext.Current.Trace.Warn("No BMC connection string"); return null; } } return null; }// openConnection
public DataAccess() { System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot"); System.Configuration.ConnectionStringSettings connString; if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) { connString = rootWebConfig.ConnectionStrings.ConnectionStrings["CASConnectionString2"]; if (connString != null) { this.ConnectionString = connString.ConnectionString; } else { this.ConnectionString = ""; } } else { this.ConnectionString = ""; } Global_Sqlcn = new SqlConnection(ConnectionString); //Global_SqlcnReader = new SqlConnection(ConnectionString); while (true) { try { if (Global_Sqlcn.State != ConnectionState.Open) { Global_Sqlcn.Open(); } break; } catch (Exception es) { Message_Exeption(es); break; } } }
public static void GetConverterElement() { // Get the Web application configuration. System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); // Get the external JSON section. ScriptingJsonSerializationSection jsonSection = (ScriptingJsonSerializationSection)configuration.GetSection( "system.web.extensions/scripting/webServices/jsonSerialization"); //Get the converters collection. ConvertersCollection converters = jsonSection.Converters; if ((converters != null) && converters.Count > 0) { // Get the first registered converter. Converter converterElement = converters[0]; } }
/// <summary> /// /// </summary> /// <param name="Variavel"></param> /// <returns></returns> public string getWebConfig(string Variavel) { string strValue = ""; System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/"); System.Configuration.ConnectionStringSettings connString; if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count) { connString = rootWebConfig.ConnectionStrings.ConnectionStrings[Variavel]; if (null != connString) { strValue = connString.ConnectionString; } else { strValue = "erro"; } } return(strValue); }
protected void Button2_Click(object sender, EventArgs e) { // Get the application configuration file. System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/"); System.Web.Configuration.CacheSection cacheSection = (System.Web.Configuration.CacheSection)config.GetSection( "system.web/caching/cache"); // Read the cache section. System.Text.StringBuilder buffer = new System.Text.StringBuilder(); string currentFile = cacheSection.CurrentConfiguration.FilePath; bool dExpiration = cacheSection.DisableExpiration; bool dMemCollection = cacheSection.DisableMemoryCollection; TimeSpan pollTime = cacheSection.PrivateBytesPollTime; int phMemUse = cacheSection.PercentagePhysicalMemoryUsedLimit; long pvBytesLimit = cacheSection.PrivateBytesLimit; string cacheEntry = String.Format("File: {0} <br/>", currentFile); buffer.Append(cacheEntry); cacheEntry = String.Format("Expiration Disabled: {0} <br/>", dExpiration); buffer.Append(cacheEntry); cacheEntry = String.Format("Memory Collection Disabled: {0} <br/>", dMemCollection); buffer.Append(cacheEntry); cacheEntry = String.Format("Poll Time: {0} <br/>", pollTime.ToString()); buffer.Append(cacheEntry); cacheEntry = String.Format("Memory Limit: {0} <br/>", phMemUse.ToString()); buffer.Append(cacheEntry); cacheEntry = String.Format("Bytes Limit: {0} <br/>", pvBytesLimit.ToString()); buffer.Append(cacheEntry); Label1.Text = buffer.ToString(); }
internal SparkCLRDebugConfiguration(System.Configuration.Configuration configuration) : base(configuration) { }
internal static object GetSection(string sectionName, string path, HttpContext context) { if (String.IsNullOrEmpty(sectionName)) { return(null); } _Configuration c = OpenWebConfiguration(path, null, null, null, null, null, false); string configPath = c.ConfigPath; int baseCacheKey = 0; int cacheKey; bool pathPresent = !String.IsNullOrEmpty(path); string locationPath = null; if (pathPresent) { locationPath = "location_" + path; } baseCacheKey = sectionName.GetHashCode(); if (configPath != null) { baseCacheKey ^= configPath.GetHashCode(); } try { sectionCacheLock.EnterReadLock(); object o; if (pathPresent) { cacheKey = baseCacheKey ^ locationPath.GetHashCode(); if (sectionCache.TryGetValue(cacheKey, out o)) { return(o); } cacheKey = baseCacheKey ^ path.GetHashCode(); if (sectionCache.TryGetValue(cacheKey, out o)) { return(o); } } if (sectionCache.TryGetValue(baseCacheKey, out o)) { return(o); } } finally { sectionCacheLock.ExitReadLock(); } string cachePath = null; if (pathPresent) { string relPath; if (VirtualPathUtility.IsRooted(path)) { if (path [0] == '~') { relPath = path.Length > 1 ? path.Substring(2) : String.Empty; } else if (path [0] == '/') { relPath = path.Substring(1); } else { relPath = path; } } else { relPath = path; } HttpRequest req = context != null ? context.Request : null; if (req != null) { string vdir = VirtualPathUtility.GetDirectory(req.PathNoValidation); if (vdir != null) { vdir = vdir.TrimEnd(pathTrimChars); if (String.Compare(c.ConfigPath, vdir, StringComparison.Ordinal) != 0 && LookUpLocation(vdir.Trim(pathTrimChars), ref c)) { cachePath = path; } } } if (LookUpLocation(relPath, ref c)) { cachePath = locationPath; } else { cachePath = path; } } ConfigurationSection section = c.GetSection(sectionName); if (section == null) { return(null); } #if TARGET_J2EE object value = get_runtime_object.Invoke(section, new object [0]); if (String.CompareOrdinal("appSettings", sectionName) == 0) { NameValueCollection collection; collection = new KeyValueMergedCollection(HttpContext.Current, (NameValueCollection)value); value = collection; } #else #if MONOWEB_DEP object value = SettingsMappingManager.MapSection(get_runtime_object.Invoke(section, new object [0])); #else object value = null; #endif #endif if (cachePath != null) { cacheKey = baseCacheKey ^ cachePath.GetHashCode(); } else { cacheKey = baseCacheKey; } AddSectionToCache(cacheKey, value); return(value); }
internal SparkCLRLocalConfiguration(System.Configuration.Configuration configuration) : base(configuration) { }
public void RunDllUpdate(String[] args) { if (args.Length < 2) { Console.Error.WriteLine("rdfWebDeploy: Error: 2 Arguments are required in order to use the -dllupdate mode"); return; } if (args.Length > 2) { if (!this.SetOptions(args.Skip(2).ToArray())) { Console.Error.WriteLine("rdfWebDeploy: DLL Update aborted since one/more options were not valid"); return; } } String appFolder; if (!this._noLocalIIS) { //Open the Configuration File System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(args[1], this._site); Console.Out.WriteLine("rdfWebDeploy: Opened the Web.config file for the specified Web Application"); appFolder = Path.GetDirectoryName(config.FilePath); } else { appFolder = Path.GetDirectoryName(args[1]); } //Detect Folders String binFolder = Path.Combine(appFolder, "bin\\"); if (!Directory.Exists(binFolder)) { Directory.CreateDirectory(binFolder); Console.WriteLine("rdfWebDeploy: Created a bin\\ directory for the web application"); } //Copy all required DLLs are in the bin directory of the application String sourceFolder = RdfWebDeployHelper.ExecutablePath; IEnumerable <String> dlls = RdfWebDeployHelper.RequiredDLLs; if (this._sql) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredSqlDLLs); } if (this._virtuoso) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredVirtuosoDLLs); } if (this._fulltext) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredFullTextDLLs); } foreach (String dll in dlls) { if (File.Exists(Path.Combine(sourceFolder, dll))) { File.Copy(Path.Combine(sourceFolder, dll), Path.Combine(binFolder, dll), true); Console.WriteLine("rdfWebDeploy: Updated " + dll + " in the web applications bin directory"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Required DLL " + dll + " which needs deploying to the web applications bin directory could not be found"); return; } } Console.WriteLine("rdfWebDeploy: OK - All required DLLs are now up to date"); }
public static void Main() { try { // <Snippet1> // Get the Web application configuration object. System.Configuration.Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); // Get the section related object. System.Web.Configuration.SessionStateSection sessionStateSection = (System.Web.Configuration.SessionStateSection) configuration.GetSection("system.web/sessionState"); // </Snippet1> // <Snippet2> // Display the current AllowCustomSqlDatabase property value. Console.WriteLine("AllowCustomSqlDatabase: {0}", sessionStateSection.AllowCustomSqlDatabase); // </Snippet2> // <Snippet3> // Display the current RegenerateExpiredSessionId property value. Console.WriteLine("RegenerateExpiredSessionId: {0}", sessionStateSection.RegenerateExpiredSessionId); // </Snippet3> // <Snippet4> // Display the current CustomProvider property value. Console.WriteLine("CustomProvider: {0}", sessionStateSection.CustomProvider); // </Snippet4> // <Snippet5> // Display the current CookieName property value. Console.WriteLine("CookieName: {0}", sessionStateSection.CookieName); // </Snippet5> // <Snippet6> // Display the current StateNetworkTimeout property value. Console.WriteLine("StateNetworkTimeout: {0}", sessionStateSection.StateNetworkTimeout); // </Snippet6> // <Snippet7> // Display the current Cookieless property value. Console.WriteLine("Cookieless: {0}", sessionStateSection.Cookieless); // </Snippet7> // <Snippet8> // Display the current SqlConnectionString property value. Console.WriteLine("SqlConnectionString: {0}", sessionStateSection.SqlConnectionString); // </Snippet8> // <Snippet9> // Display the current StateConnectionString property value. Console.WriteLine("StateConnectionString: {0}", sessionStateSection.StateConnectionString); // </Snippet9> // <Snippet10> // Display elements of the Providers collection property. foreach (ProviderSettings providerItem in sessionStateSection.Providers) { Console.WriteLine(); Console.WriteLine("Provider Details:"); Console.WriteLine("Name: {0}", providerItem.Name); Console.WriteLine("Type: {0}", providerItem.Type); } // </Snippet10> // <Snippet11> // Display the current Timeout property value. Console.WriteLine("Timeout: {0}", sessionStateSection.Timeout); // </Snippet11> // <Snippet13> // Display the current SqlCommandTimeout property value. Console.WriteLine("SqlCommandTimeout: {0}", sessionStateSection.SqlCommandTimeout); // </Snippet13> // <Snippet14> // Display the current Mode property value. Console.WriteLine("Mode: {0}", sessionStateSection.Mode); // </Snippet14> } catch (System.ArgumentException) { // Unknown error. Console.WriteLine("A invalid argument exception detected in " + "UsingSessionStateSection Main. Check your command line" + "for errors."); } Console.ReadLine(); }
public ConnectionStringsStore() : base(new[] { typeof(string) }) { _exeConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); _connectionStringsSection = _exeConfiguration.ConnectionStrings; }
private System.Configuration.Configuration ImportConfiguration() { // get a temp filename to hold the current settings which are failing string tempFile = Path.GetTempFileName(); fileWatcher.StopObservation(); MoveAndDeleteFile(fileLocations.Configuration, tempFile); SaveDefaultConfigFile(); fileWatcher.StartObservation(); System.Configuration.Configuration c = OpenConfiguration(); // get a list of the properties on the Settings object (static props) PropertyInfo[] propList = typeof(Settings).GetProperties(); // read all the xml from the erroring file XmlDocument doc = new XmlDocument(); doc.LoadXml(File.ReadAllText(tempFile)); // get the settings root XmlNode root = doc.SelectSingleNode("/configuration/settings"); try { // for each setting's attribute foreach (XmlAttribute att in root.Attributes) { // scan for the related property if any try { foreach (PropertyInfo info in propList) { try { if (info.Name.ToLower() == att.Name.ToLower()) { // found a matching property, try to set it string val = att.Value; info.SetValue(null, Convert.ChangeType(val, info.PropertyType), null); break; } } catch (Exception exc) { // ignore the error Logging.Error("Remapping Settings Inner", exc); } } } catch (Exception exc) // ignore the error { Logging.Error("Remapping Settings Outer", exc); } } } catch (Exception exc) // ignore the error { Logging.Error("Remapping Settings Outer Try", exc); } XmlNodeList favs = doc.SelectNodes("/configuration/settings/favorites/add"); try { foreach (XmlNode fav in favs) { try { FavoriteConfigurationElement newFav = new FavoriteConfigurationElement(); foreach (XmlAttribute att in fav.Attributes) { try { foreach (PropertyInfo info in newFav.GetType().GetProperties()) { try { if (info.Name.ToLower() == att.Name.ToLower()) { // found a matching property, try to set it string val = att.Value; if (info.PropertyType.IsEnum) { info.SetValue(newFav, Enum.Parse(info.PropertyType, val), null); } else { info.SetValue(newFav, Convert.ChangeType(val, info.PropertyType), null); } break; } } catch (Exception exc) // ignore the error { Logging.Error("Remapping Favorites 1", exc); } } } catch (Exception exc) // ignore the error { Logging.Error("Remapping Favorites 2", exc); } } AddFavorite(newFav); } catch (Exception exc) // ignore the error { Logging.Error("Remapping Favorites 3", exc); } } } catch (Exception exc) // ignore the error { Logging.Error("Remapping Favorites 4", exc); } return(c); }
private static void ToggleConnectionStringProtection(string pathName, bool protect) { // Define the Dpapi provider name. string strProvider = "DataProtectionConfigurationProvider"; // string strProvider = "RSAProtectedConfigurationProvider"; System.Configuration.Configuration oConfiguration = null; System.Configuration.ConnectionStringsSection oSection = null; try { // Open the configuration file and retrieve // the connectionStrings section. // For Web! // oConfiguration = System.Web.Configuration. // WebConfigurationManager.OpenWebConfiguration("~"); // For Windows! // Takes the executable file name without the config extension. oConfiguration = System.Configuration.ConfigurationManager.OpenExeConfiguration(pathName); if (oConfiguration != null) { bool blnChanged = false; oSection = oConfiguration.GetSection("connectionStrings") as System.Configuration.ConnectionStringsSection; if (oSection != null) { if ((!(oSection.ElementInformation.IsLocked)) && (!(oSection.SectionInformation.IsLocked))) { if (protect) { if (!(oSection.SectionInformation.IsProtected)) { blnChanged = true; // Encrypt the section. oSection.SectionInformation.ProtectSection(strProvider); } } else { if (oSection.SectionInformation.IsProtected) { blnChanged = true; // Remove encryption. oSection.SectionInformation.UnprotectSection(); } } } if (blnChanged) { // Indicates whether the associated configuration section // will be saved even if it has not been modified. oSection.SectionInformation.ForceSave = true; // Save the current configuration. oConfiguration.Save(); ConfigurationManager.RefreshSection("connectionStrings"); } } } } catch (System.Exception ex) { throw (ex); } finally { } }
internal SparkCLRConfiguration(System.Configuration.Configuration configuration) { appSettings = configuration.AppSettings; }
public virtual void Init() { this.configuration = GetConfiguration(); this.databasesConfiguration = (IDatabasesConfigurationService)AppController.Instance.GetService <IDatabasesConfigurationService, DatabaseConfigurationService>(); }
private void BindGridViewData_forallMember() { try { System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot"); System.Configuration.ConnectionStringSettings connStringSQL; connStringSQL = rootWebConfig.ConnectionStrings.ConnectionStrings["DefaultConnection"]; string MyconnStr = null; if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) { if (connStringSQL != null) { if (connStringSQL.ProviderName == "System.Data.SqlClient") { MyconnStr = connStringSQL.ConnectionString; SqlConnection conn = new SqlConnection(@"" + MyconnStr + ""); conn.Open(); //Image_MemberPicture.ImageUrl = ImageConverter(strBase64); SqlCommand MyCommand; string MySqlString = null; SqlDataReader dataReader; //MySqlString = "Select * FROM [NRB_MMS].[dbo].[Member] order by FAMILYID,MemberID ASC"; MySqlString = "SELECT [MemberID],[FamilyID],[MemberFname],[MemberLname]," + " [MemberAvgift],[Status],[Email_UserName], " + " [Phone_Nr] FROM [NRB_MMS].[dbo].[Member] order by FAMILYID,MemberID ASC"; //MySqlString = "SELECT PERSONLIGIMAGE FROM [NRB_MMS].[dbo].[Member] order by FAMILYID,MemberID ASC"; MyCommand = new SqlCommand(MySqlString, conn); dataReader = MyCommand.ExecuteReader(); //List<IMAGE> userImageInfobyID = dataReader.Automap<dataReader> ["PERSONLIGIMAGE"]; //var dt=new DataTable(); //dt.Load(dataReader); //List<IMAGE> dr=dt.AsEnumerable().ToList(); ////GetImageSign1FromImageByID //IMAGE TheValue = userImageInfobyID.FirstOrDefault(); //if (TheValue != null) //{ // //GridView_Info.Visible = false; // //GridView_Info.DataSource = userImageInfobyID; // //GridView_Info.DataBind(); // GridView_Info.Visible = false; // Repeater1.Visible = true; // Repeater1.DataSource = userImageInfobyID; // Repeater1.DataBind(); //} //MyCommand.Parameters.AddWithValue("@user", TextBox_UserName.Text); GridViewMemInfoLinq.DataSource = null; GridViewMemInfoLinq.DataBind(); if (dataReader.HasRows) { GridViewMemInfoLinq.Visible = true; GridViewMemInfoLinq.DataSource = dataReader; GridViewMemInfoLinq.DataBind(); } dataReader.Close(); dataReader.Dispose(); } else { Response.Write("<script LANGUAGE='JavaScript' >alert('Ingen information hittades!')</script>"); //dataReader.Close(); //MyCommand.Dispose(); } } } } catch (Exception ex) { throw new ApplicationException(ex.Message.ToString()); } //IsSearch_MemberID = 1; }
public UsingHttpHandlersSection() { // Process the // System.Web.Configuration.HttpHandlersSectionobject. try { // <Snippet1> // Get the Web application configuration. System.Configuration.Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); // Get the section. System.Web.Configuration.HttpHandlersSection httpHandlersSection = (System.Web.Configuration.HttpHandlersSection)configuration.GetSection("system.web/httphandlers"); // </Snippet1> // <Snippet2> // Get the handlers. System.Web.Configuration.HttpHandlerActionCollection httpHandlers = httpHandlersSection.Handlers; // </Snippet2> // <Snippet3> // Add a new HttpHandlerAction to the Handlers property HttpHandlerAction collection. httpHandlersSection.Handlers.Add(new HttpHandlerAction( "Calculator.custom", "Samples.Aspnet.SystemWebConfiguration.Calculator, CalculatorHandler", "GET", true)); // </Snippet3> // <Snippet4> // Get a HttpHandlerAction in the Handlers property HttpHandlerAction collection. HttpHandlerAction httpHandler = httpHandlers[0]; // </Snippet4> // <Snippet5> // Change the Path for the HttpHandlerAction. httpHandler.Path = "Calculator.custom"; // </Snippet5> // <Snippet6> // Change the Type for the HttpHandlerAction. httpHandler.Type = "Samples.Aspnet.SystemWebConfiguration.Calculator, CalculatorHandler"; // </Snippet6> // <Snippet7> // Change the Verb for the HttpHandlerAction. httpHandler.Verb = "POST"; // </Snippet7> // <Snippet8> // Change the Validate for the HttpHandlerAction. httpHandler.Validate = false; // </Snippet8> // <Snippet9> // Get the specified handler's index. HttpHandlerAction httpHandler2 = new HttpHandlerAction( "Calculator.custom", "Samples.Aspnet.SystemWebConfiguration.Calculator, CalculatorHandler", "GET", true); int handlerIndex = httpHandlers.IndexOf(httpHandler2); // </Snippet9> // <Snippet10> // Remove a HttpHandlerAction object HttpHandlerAction httpHandler3 = new HttpHandlerAction( "Calculator.custom", "Samples.Aspnet.SystemWebConfiguration.Calculator, CalculatorHandler", "GET", true); httpHandlers.Remove(httpHandler3); // </Snippet10> // <Snippet11> // Remove a HttpHandlerAction object with 0 index. httpHandlers.RemoveAt(0); // </Snippet11> // <Snippet12> // Clear all CustomError objects from the Handlers property HttpHandlerAction collection. httpHandlers.Clear(); // </Snippet12> // <Snippet13> // Remove the handler with the specified verb and path. httpHandlers.Remove("GET", "*.custom"); // </Snippet13> Console.WriteLine("List the Errors collection:"); int handlerActionCtr = 0; foreach (HttpHandlerAction handlerAction in httpHandlersSection.Handlers) { // <Snippet14> string type = handlerAction.Type; // </Snippet14> // <Snippet15> string verb = handlerAction.Verb; // </Snippet15> // <Snippet16> bool validation = handlerAction.Validate; // </Snippet16> Console.WriteLine(" {0}: message", ++handlerActionCtr); } // Update if not locked. if (!httpHandlersSection.SectionInformation.IsLocked) { configuration.Save(); Console.WriteLine("** Configuration updated."); } else { Console.WriteLine("** Could not update, section is locked."); } } catch (System.ArgumentException e) { // Unknown error. Console.WriteLine(e.ToString()); } }
/// <summary> /// Loads the <see cref="DomainConfiguration"/> for <see cref="Domain"/> /// with the specified <paramref name="name"/> /// from application configuration file (section with <see cref="SectionName"/>). /// </summary> /// <param name="configuration">A <see cref="System.Configuration.Configuration"/> /// instance to load from.</param> /// <param name="name">Name of the <see cref="Domain"/>.</param> /// <returns> /// The <see cref="DomainConfiguration"/> for the specified domain. /// </returns> /// <exception cref="InvalidOperationException">Section <see cref="SectionName"/> /// is not found in application configuration file, or there is no configuration for /// the <see cref="Domain"/> with specified <paramref name="name"/>.</exception> public static DomainConfiguration Load(System.Configuration.Configuration configuration, string name) { return(Load(configuration, SectionName, name)); }
internal static object GetSection(string sectionName, string path, HttpContext context) { // FindWebConfig must not be used here with its result being passed to // OpenWebConfiguration below. The reason is that if we have a request for // ~/somepath/, but FindWebConfig returns ~/ and the ~/web.config contains // <location path="somepath"> then OpenWebConfiguration will NOT return the // contents of <location>, thus leading to bugs (ignored authorization // section for instance) string config_vdir = FindWebConfig(path); if (String.IsNullOrEmpty(config_vdir)) { config_vdir = "/"; } int sectionCacheKey = GetSectionCacheKey(sectionName, config_vdir); object cachedSection; bool locked = false; try { #if SYSTEMCORE_DEP sectionCacheLock.EnterReadLock(); #endif locked = true; if (sectionCache.TryGetValue(sectionCacheKey, out cachedSection) && cachedSection != null) { return(cachedSection); } } finally { #if SYSTEMCORE_DEP if (locked) { sectionCacheLock.ExitReadLock(); } #endif } HttpRequest req = context != null ? context.Request : null; _Configuration c = OpenWebConfiguration(path, /* path */ null, /* site */ req != null ? VirtualPathUtility.GetDirectory(req.Path) : null, /* locationSubPath */ null, /* server */ null, /* userName */ null, /* password */ false /* path from FindWebConfig */); ConfigurationSection section = c.GetSection(sectionName); if (section == null) { return(null); } #if TARGET_J2EE object value = get_runtime_object.Invoke(section, new object [0]); if (String.CompareOrdinal("appSettings", sectionName) == 0) { NameValueCollection collection; collection = new KeyValueMergedCollection(HttpContext.Current, (NameValueCollection)value); value = collection; } AddSectionToCache(sectionCacheKey, value); return(value); #else #if MONOWEB_DEP object value = SettingsMappingManager.MapSection(get_runtime_object.Invoke(section, new object [0])); #else object value = null; #endif AddSectionToCache(sectionCacheKey, value); return(value); #endif }
internal void ForceReload() { _config = GetConfiguration(); }
protected internal override bool TryAdd(string name, Binding binding, System.Configuration.Configuration config) { return(false); }
protected internal abstract bool TryAdd(string name, ServiceEndpoint endpoint, ConfigurationType config);
private bool UpdateConfigItems() { bool dataIsValid = true; this.lblUpdateResults.Text = string.Empty; System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); DataTable dt = keyValsDataSet.Tables["KeyValTable"]; int numUpdates = 0; string key = string.Empty; string val = string.Empty; foreach (DataRow dr in dt.Rows) { if (dr.RowState == DataRowState.Modified) { key = dr["AppSetting"].ToString(); val = dr["SettingValue"].ToString(); dataIsValid = VerifyColumnValue(key, val); if (dataIsValid) { config.AppSettings.Settings[key].Value = val; numUpdates++; } } if (dataIsValid == false) { break; } } if (dataIsValid) { if (numUpdates > 0) { config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); dt.AcceptChanges(); GetLoggingSettings(); _msg.Length = 0; _msg.Append(numUpdates.ToString()); _msg.Append(" application "); if (numUpdates == 1) { _msg.Append(" setting was "); } else { _msg.Append(" settings were "); } _msg.Append(" changed."); this.lblUpdateResults.Text = _msg.ToString(); } else { _msg.Length = 0; _msg.Append("No changes were pending to the application settings."); this.lblUpdateResults.Text = _msg.ToString(); } } else { this.lblDataValidationMessage.Text = _verifyDataMessages.ToString(); } return(dataIsValid); }
public void RunDeploy(String[] args) { if (args.Length < 3) { Console.Error.WriteLine("rdfWebDeploy: Error: 3 Arguments are required in order to use the -deploy mode, type rdfWebDeploy -help to see usage summary"); return; } if (args.Length > 3) { if (!this.SetOptions(args.Skip(3).ToArray())) { Console.Error.WriteLine("rdfWebDeploy: Deployment aborted since one/more options were not valid"); return; } } if (this._noLocalIis) { Console.WriteLine("rdfWebDeploy: No Local IIS Server available so switching to -xmldeploy mode"); XmlDeploy xdeploy = new XmlDeploy(); xdeploy.RunXmlDeploy(args); return; } //Define the Server Manager object Admin.ServerManager manager = null; try { //Connect to the Server Manager if (!this._noIntegratedRegistration) { manager = new Admin.ServerManager(); } //Open the Configuration File System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(args[1], this._site); Console.Out.WriteLine("rdfWebDeploy: Opened the Web.config file for the specified Web Application"); //Detect Folders String appFolder = Path.GetDirectoryName(config.FilePath); String binFolder = Path.Combine(appFolder, "bin\\"); String appDataFolder = Path.Combine(appFolder, "App_Data\\"); if (!Directory.Exists(binFolder)) { Directory.CreateDirectory(binFolder); Console.WriteLine("rdfWebDeploy: Created a bin\\ directory for the web application"); } if (!Directory.Exists(appDataFolder)) { Directory.CreateDirectory(appDataFolder); Console.WriteLine("rdfWebDeploy: Created an App_Data\\ directory for the web application"); } //Deploy dotNetRDF and required DLLs to the bin directory of the application String sourceFolder = RdfWebDeployHelper.ExecutablePath; IEnumerable <String> dlls = RdfWebDeployHelper.RequiredDLLs; if (this._virtuoso) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredVirtuosoDLLs); } if (this._fulltext) { dlls = dlls.Concat(RdfWebDeployHelper.RequiredFullTextDLLs); } foreach (String dll in dlls) { if (File.Exists(Path.Combine(sourceFolder, dll))) { File.Copy(Path.Combine(sourceFolder, dll), Path.Combine(binFolder, dll), true); Console.WriteLine("rdfWebDeploy: Deployed " + dll + " to the web applications bin directory"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Required DLL " + dll + " which needs deploying to the web applications bin directory could not be found"); return; } } //Deploy the configuration file to the App_Data directory if (File.Exists(args[2])) { File.Copy(args[2], Path.Combine(appDataFolder, args[2]), true); Console.WriteLine("rdfWebDeploy: Deployed the configuration file to the web applications App_Data directory"); } else if (!File.Exists(Path.Combine(appDataFolder, args[2]))) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to continue deployment as the configuration file " + args[2] + " could not be found either locally for deployment to the App_Data folder or already present in the App_Data folder"); return; } //Set the AppSetting for the configuration file config.AppSettings.Settings.Remove("dotNetRDFConfig"); config.AppSettings.Settings.Add("dotNetRDFConfig", "~/App_Data/" + Path.GetFileName(args[2])); Console.WriteLine("rdfWebDeploy: Set the \"dotNetRDFConfig\" appSetting to \"~/App_Data/" + Path.GetFileName(args[2]) + "\""); //Now load the Configuration Graph from the App_Data folder Graph g = new Graph(); FileLoader.Load(g, Path.Combine(appDataFolder, args[2])); Console.WriteLine("rdfWebDeploy: Successfully deployed required DLLs and appSettings"); Console.WriteLine(); //Get the sections of the Configuration File we want to edit HttpHandlersSection handlersSection = config.GetSection("system.web/httpHandlers") as HttpHandlersSection; if (handlersSection == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Handlers section of the web applications Web.Config file"); return; } //Detect Handlers from the Configution Graph and deploy IUriNode rdfType = g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); IUriNode dnrType = g.CreateUriNode(new Uri(ConfigurationLoader.PropertyType)); IUriNode httpHandler = g.CreateUriNode(new Uri(ConfigurationLoader.ClassHttpHandler)); //Deploy for IIS Classic Mode if (!this._noClassicRegistration) { Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Classic Mode"); foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject)) { if (n.NodeType == NodeType.Uri) { String handlerPath = ((IUriNode)n).Uri.AbsolutePath; INode type = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault(); if (type == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified"); continue; } if (type.NodeType == NodeType.Literal) { String handlerType = ((ILiteralNode)type).Value; //First remove any existing registration handlersSection.Handlers.Remove("*", handlerPath); //Then add the new registration handlersSection.Handlers.Add(new HttpHandlerAction(handlerPath, handlerType, "*")); Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal"); continue; } } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node"); } } //Deploy Negotiate by File Extension if appropriate if (this._negotiate) { HttpModulesSection modulesSection = config.GetSection("system.web/httpModules") as HttpModulesSection; if (modulesSection == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file"); return; } modulesSection.Modules.Remove("NegotiateByExtension"); modulesSection.Modules.Add(new HttpModuleAction("NegotiateByExtension", "VDS.RDF.Web.NegotiateByFileExtension")); Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module"); } Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Classic Mode"); } //Save the completed Configuration File config.Save(ConfigurationSaveMode.Minimal); Console.WriteLine(); //Deploy for IIS Integrated Mode if (!this._noIntegratedRegistration) { Console.WriteLine("rdfWebDeploy: Attempting deployment for IIS Integrated Mode"); Admin.Configuration adminConfig = manager.GetWebConfiguration(this._site, args[1]); Admin.ConfigurationSection newHandlersSection = adminConfig.GetSection("system.webServer/handlers"); Admin.ConfigurationElementCollection newHandlers = newHandlersSection.GetCollection(); foreach (INode n in g.GetTriplesWithPredicateObject(rdfType, httpHandler).Select(t => t.Subject)) { if (n.NodeType == NodeType.Uri) { String handlerPath = ((IUriNode)n).Uri.AbsolutePath; INode type = g.GetTriplesWithSubjectPredicate(n, dnrType).Select(t => t.Object).FirstOrDefault(); if (type == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as there is no dnr:type property specified"); continue; } if (type.NodeType == NodeType.Literal) { String handlerType = ((ILiteralNode)type).Value; //First remove any existing registration foreach (Admin.ConfigurationElement oldReg in newHandlers.Where(el => el.GetAttributeValue("name").Equals(handlerPath)).ToList()) { newHandlers.Remove(oldReg); } //Then add the new registration Admin.ConfigurationElement reg = newHandlers.CreateElement("add"); reg["name"] = handlerPath; reg["path"] = handlerPath; reg["verb"] = "*"; reg["type"] = handlerType; newHandlers.AddAt(0, reg); Console.WriteLine("rdfWebDeploy: Deployed the Handler <" + n.ToString() + "> to the web applications Web.Config file"); } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy the Handler <" + n.ToString() + "> as the value given for the dnr:type property is not a Literal"); continue; } } else { Console.Error.WriteLine("rdfWebDeploy: Error: Cannot deploy a Handler which is not specified as a URI Node"); } //Deploy Negotiate by File Extension if appropriate if (this._negotiate) { Admin.ConfigurationSection newModulesSection = adminConfig.GetSection("system.webServer/modules"); if (newModulesSection == null) { Console.Error.WriteLine("rdfWebDeploy: Error: Unable to access the Modules section of the web applications Web.Config file"); return; } //First remove the Old Module Admin.ConfigurationElementCollection newModules = newModulesSection.GetCollection(); foreach (Admin.ConfigurationElement oldReg in newModules.Where(el => el.GetAttribute("name").Equals("NegotiateByExtension")).ToList()) { newModules.Remove(oldReg); } //Then add the new Module Admin.ConfigurationElement reg = newModules.CreateElement("add"); reg["name"] = "NegotiateByExtension"; reg["type"] = "VDS.RDF.Web.NegotiateByFileExtension"; newModules.AddAt(0, reg); Console.WriteLine("rdfWebDeploy: Deployed the Negotiate by File Extension Module"); } } manager.CommitChanges(); Console.WriteLine("rdfWebDeploy: Successfully deployed for IIS Integrated Mode"); } } catch (ConfigurationException configEx) { Console.Error.WriteLine("rdfWebDeploy: Configuration Error: " + configEx.Message); } catch (Exception ex) { Console.Error.WriteLine("rdfWebDeploy: Error: " + ex.Message); Console.Error.WriteLine(ex.StackTrace); } finally { if (manager != null) { manager.Dispose(); } } }