OpenMappedExeConfiguration() public static method

public static OpenMappedExeConfiguration ( ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel ) : Configuration
fileMap ExeConfigurationFileMap
userLevel ConfigurationUserLevel
return Configuration
Beispiel #1
0
        private static Configuration GetUserConfig(Project project, string assemblyFullName)
        {
            DebugCheck.NotNull(project);

            var userConfigFilename
                = Path.Combine(
                      (string)project.Properties.Item("FullPath").Value,
                      project.IsWebProject()
                        ? "Web.config"
                        : "App.config");

            var document = XDocument.Load(userConfigFilename);

            FixUpConfig(document, assemblyFullName);

            var tempFile = Path.GetTempFileName();

            document.Save(tempFile);

            return(ConfigurationManager.OpenMappedExeConfiguration(
                       new ExeConfigurationFileMap {
                ExeConfigFilename = tempFile
            },
                       ConfigurationUserLevel.None));
        }
Beispiel #2
0
        /// <summary>
        /// Attempts to find a database connection string for a project.
        /// </summary>
        /// <param name="project">The project to search for a connection string</param>
        public SqlConnectionStringBuilder Locate(Project project)
        {
            // Try to find the app config file.
            var configItem = project.TryFindChild(item => !String.IsNullOrEmpty(item.Name) && ConfigNamePattern.IsMatch(item.Name));

            if (configItem == null)
            {
                throw new ConnectionStringLocationException("Valid config file could not be found.");
            }

            var configFile = new ExeConfigurationFileMap {
                ExeConfigFilename = configItem.FileNames[0]
            };
            var config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
            var connectionStringSettings = config.ConnectionStrings.ConnectionStrings
                                           .Cast <ConnectionStringSettings>()
                                           .Reverse()
                                           .FirstOrDefault(cs => cs.ProviderName == EntityProviderName);

            if (connectionStringSettings == null)
            {
                throw new ConnectionStringLocationException($"Connection string for provider '{EntityProviderName}' not found.");
            }

            var entityConnString = new DbConnectionStringBuilder
            {
                ConnectionString = connectionStringSettings.ConnectionString
            };
            var connectionString = (string)entityConnString[ProviderConnectionStringKey];

            return(new SqlConnectionStringBuilder(connectionString));
        }
Beispiel #3
0
        private void ChangeFoowwEnvironmentToTest(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            string appConfigPath              = GetStartupProjectDirectoryPath() + @"\app.config";
            string environmentNode            = "Environment";
            ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();

            configMap.ExeConfigFilename = appConfigPath;
            Configuration appConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

            // 没有配置,需要新增测试环境配置
            if (!appConfig.AppSettings.Settings.AllKeys.Contains(environmentNode))
            {
                appConfig.AppSettings.Settings.Add(environmentNode, "Test");
                appConfig.Save(ConfigurationSaveMode.Modified);
                //使connectionStrings配置节缓存失效,下次必须从磁盘读取
                ConfigurationManager.RefreshSection("appSettings");
                return;
            }

            // 否则改为测试
            string value = appConfig.AppSettings.Settings[environmentNode].Value;

            if (value.ToLower() != "test")
            {
                appConfig.AppSettings.Settings[environmentNode].Value = "Test";
                appConfig.Save(ConfigurationSaveMode.Modified);
                //使connectionStrings配置节缓存失效,下次必须从磁盘读取
                ConfigurationManager.RefreshSection("appSettings");
            }
        }
Beispiel #4
0
        private static AppConfiguration Load(IFileSystemInfo info)
        {
            var file = ResolveFile(info);

            var tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            try
            {
                using (var destination = new FileStream(tempFile, FileMode.Create, FileAccess.ReadWrite))
                    using (var source = file.OpenRead())
                    {
                        source.CopyTo(destination);
                    }

                var configuration = Manager.OpenMappedExeConfiguration(new ExeConfigurationFileMap {
                    ExeConfigFilename = tempFile
                }, ConfigurationUserLevel.None);
                return((AppConfiguration)configuration.GetSection(AppConfiguration.SectionName));
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
Beispiel #5
0
        private ConnectionStringSettings GetConnectionStringSettings(ProjectItem item, string name)
        {
            Property property = item.FindProperty(ProjectItemProperty.FullPath);
            var      exeConfigurationFileMap = new ExeConfigurationFileMap {
                ExeConfigFilename = property.Value.ToString()
            };
            Configuration            configuration = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
            ConnectionStringsSection strings       = configuration.ConnectionStrings;

            return(strings.ConnectionStrings[name]);
        }
Beispiel #6
0
        private static Configuration GetUserConfig(Project project)
        {
            Contract.Requires(project != null);

            var userConfigFilename
                = Path.Combine(
                      (string)project.Properties.Item("FullPath").Value,
                      project.IsWebProject()
                        ? "Web.config"
                        : "App.config");

            return(ConfigurationManager.OpenMappedExeConfiguration(
                       new ExeConfigurationFileMap {
                ExeConfigFilename = userConfigFilename
            },
                       ConfigurationUserLevel.None));
        }
        public ArchivizerConfiguration ReadConfiguration()
        {
            ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap()
            {
                ExeConfigFilename = "ArchivizerConfiguration.config"
            };
            var config = SystemConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

            var globalConfiguration = config.GetSection("GlobalConfigurationSection") as GlobalConfigurationSection;
            var supportedDirectory  = config.GetSection("SupportedArchivizerConfigurationForDirectorySection") as SupportedArchivizerConfigurationForDirectorySection;

            var configurations = supportedDirectory.GetConfiguration();

            var configuration = new ArchivizerConfiguration
            {
                Achivizer7zFullName                  = globalConfiguration.Archivizer7zFullName,
                DeleteSourceFileAfterArchiving       = globalConfiguration.DeleteSourceFileAfterArchiving,
                ArchivizerConfigurationsForDirectory = new ReadOnlyDictionary <string, ArchivizerConfigurationForDirectory>(configurations),
                MaxNumberOfLatestArchiveFilesInKept  = globalConfiguration.MaxNumberOfLatestArchiveFilesInKept
            };

            ValidateConfiguration(configuration);
            return(configuration);
        }
        private void SaveProperties(ExeConfigurationFileMap exeMap, SettingsPropertyValueCollection collection, ConfigurationUserLevel level, SettingsContext context, bool checkUserLevel)
        {
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap, level);

            UserSettingsGroup userGroup = config.GetSectionGroup("userSettings") as UserSettingsGroup;
            bool isRoaming = (level == ConfigurationUserLevel.PerUserRoaming);

#if true // my reimplementation
            if (userGroup == null)
            {
                userGroup = new UserSettingsGroup();
                config.SectionGroups.Add("userSettings", userGroup);
                ApplicationSettingsBase asb = context.CurrentSettings;
                ClientSettingsSection   cs  = new ClientSettingsSection();
                string class_name           = NormalizeInvalidXmlChars((asb != null ? asb.GetType() : typeof(ApplicationSettingsBase)).FullName);
                userGroup.Sections.Add(class_name, cs);
            }

            bool hasChanges = false;

            foreach (ConfigurationSection section in userGroup.Sections)
            {
                ClientSettingsSection userSection = section as ClientSettingsSection;
                if (userSection == null)
                {
                    continue;
                }

                foreach (SettingsPropertyValue value in collection)
                {
                    if (checkUserLevel && value.Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                    {
                        continue;
                    }
                    // The default impl does not save the ApplicationScopedSetting properties
                    if (value.Property.Attributes.Contains(typeof(ApplicationScopedSettingAttribute)))
                    {
                        continue;
                    }

                    hasChanges = true;
                    SettingElement element = userSection.Settings.Get(value.Name);
                    if (element == null)
                    {
                        element = new SettingElement(value.Name, value.Property.SerializeAs);
                        userSection.Settings.Add(element);
                    }
                    if (element.Value.ValueXml == null)
                    {
                        element.Value.ValueXml = new XmlDocument().CreateElement("value");
                    }
                    switch (value.Property.SerializeAs)
                    {
                    case SettingsSerializeAs.Xml:
                        element.Value.ValueXml.InnerXml = (value.SerializedValue as string) ?? string.Empty;
                        break;

                    case SettingsSerializeAs.String:
                        element.Value.ValueXml.InnerText = value.SerializedValue as string;
                        break;

                    case SettingsSerializeAs.Binary:
                        element.Value.ValueXml.InnerText = value.SerializedValue != null?Convert.ToBase64String(value.SerializedValue as byte []) : string.Empty;

                        break;

                    default:
                        throw new NotImplementedException();
                    }
                }
            }
            if (hasChanges)
            {
                config.Save(ConfigurationSaveMode.Minimal, true);
            }
#else // original impl. - likely buggy to miss some properties to save
            foreach (ConfigurationSection configSection in userGroup.Sections)
            {
                ClientSettingsSection userSection = configSection as ClientSettingsSection;
                if (userSection != null)
                {
/*
 *                                      userSection.Settings.Clear();
 *
 *                                      foreach (SettingsPropertyValue propertyValue in collection)
 *                                      {
 *                                              if (propertyValue.IsDirty)
 *                                              {
 *                                                      SettingElement element = new SettingElement(propertyValue.Name, SettingsSerializeAs.String);
 *                                                      element.Value.ValueXml = new XmlDocument();
 *                                                      element.Value.ValueXml.InnerXml = (string)propertyValue.SerializedValue;
 *                                                      userSection.Settings.Add(element);
 *                                              }
 *                                      }
 */
                    foreach (SettingElement element in userSection.Settings)
                    {
                        if (collection [element.Name] != null)
                        {
                            if (collection [element.Name].Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                            {
                                continue;
                            }

                            element.SerializeAs             = SettingsSerializeAs.String;
                            element.Value.ValueXml.InnerXml = (string)collection [element.Name].SerializedValue;                                ///Value = XmlElement
                        }
                    }
                }
            }
            config.Save(ConfigurationSaveMode.Minimal, true);
#endif
        }
        private void SaveProperties(ExeConfigurationFileMap exeMap, SettingsPropertyValueCollection collection, ConfigurationUserLevel level, SettingsContext context, bool checkUserLevel)
        {
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap, level);

            UserSettingsGroup userGroup = config.GetSectionGroup("userSettings") as UserSettingsGroup;
            bool isRoaming = (level == ConfigurationUserLevel.PerUserRoaming);

            if (userGroup == null)
            {
                userGroup = new UserSettingsGroup();
                config.SectionGroups.Add("userSettings", userGroup);
            }
            ApplicationSettingsBase asb       = context.CurrentSettings;
            string class_name                 = NormalizeInvalidXmlChars((asb != null ? asb.GetType() : typeof(ApplicationSettingsBase)).FullName);
            ClientSettingsSection userSection = null;
            ConfigurationSection  cnf         = userGroup.Sections.Get(class_name);

            userSection = cnf as ClientSettingsSection;
            if (userSection == null)
            {
                userSection = new ClientSettingsSection();
                userGroup.Sections.Add(class_name, userSection);
            }

            bool hasChanges = false;

            if (userSection == null)
            {
                return;
            }

            foreach (SettingsPropertyValue value in collection)
            {
                if (checkUserLevel && value.Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                {
                    continue;
                }
                // The default impl does not save the ApplicationScopedSetting properties
                if (value.Property.Attributes.Contains(typeof(ApplicationScopedSettingAttribute)))
                {
                    continue;
                }

                hasChanges = true;
                SettingElement element = userSection.Settings.Get(value.Name);
                if (element == null)
                {
                    element = new SettingElement(value.Name, value.Property.SerializeAs);
                    userSection.Settings.Add(element);
                }
                if (element.Value.ValueXml == null)
                {
                    element.Value.ValueXml = new XmlDocument().CreateElement("value");
                }
                switch (value.Property.SerializeAs)
                {
                case SettingsSerializeAs.Xml:
                    element.Value.ValueXml.InnerXml = StripXmlHeader(value.SerializedValue as string);
                    break;

                case SettingsSerializeAs.String:
                    element.Value.ValueXml.InnerText = value.SerializedValue as string;
                    break;

                case SettingsSerializeAs.Binary:
                    element.Value.ValueXml.InnerText = value.SerializedValue != null?Convert.ToBase64String(value.SerializedValue as byte []) : string.Empty;

                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            if (hasChanges)
            {
                config.Save(ConfigurationSaveMode.Minimal, true);
            }
        }
 /// <summary>
 /// Opens the mapped exe configuration. See the doc of ConfigurationManager to know exactly what it does.
 /// </summary>
 /// <param name="fileMap">The file map.</param>
 /// <param name="userLevel">The user level.</param>
 /// <returns>
 /// A configuration object
 /// </returns>
 public virtual Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel)
 {
     return(ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel));
 }