Beispiel #1
0
 protected ConfigKeyAttribute( ConfigSection section, [NotNull] Type valueType, object defaultValue, [NotNull] string description )
     : base( description ) {
     if( valueType == null ) throw new ArgumentNullException( "valueType" );
     if( description == null ) throw new ArgumentNullException( "description" );
     ValueType = valueType;
     DefaultValue = defaultValue;
     Section = section;
     NotBlank = false;
 }
        public static ComponentBase Create(IDictionary<string, string> globalValues, ConfigSection section, int index)
        {
            if (!section.ContainsKey(ComponentTypeString))
            {
                throw new ArgumentException("No ComponentType given for section: " + section.Name);
            }

            //assign all global values to the local configSection.
            IDictionary<string, string> localValues = section.ValuesAsDictionary;
            foreach (KeyValuePair<string, string> globalValue in globalValues)
            {
                if (!localValues.ContainsKey(globalValue.Key))
                {
                    localValues.Add(globalValue.Key, globalValue.Value);
                }
            }

            ComponentBase item = null;

            switch (ParseToComponentType(section[ComponentTypeString]))
            {
                case ComponentType.FileInstaller:
                    item = new  FileInstallerComponentGraph(section.Name, localValues);
                    break;
                case ComponentType.FileRemover:
                    item = new FileRemoverComponentGraph(section.Name, localValues);
                    break;
                case ComponentType.AppPoolInstaller:
                    item = new AppPoolInstallerComponentGraph(section.Name, localValues);
                    break;
                case ComponentType.WebSiteInstaller:
                case ComponentType.ApplicationInstaller:
                    item =  null;
                    break;
                case ComponentType.RemoteExecutionComponent:
                    item = new RemoteExecutionComponentGraph(section.Name, localValues);
                    break;
                case ComponentType.AppPoolRemover:
                    item = new IisRemoverComponentGraph(section.Name, localValues, ComponentType.AppPoolRemover);
                    break;
                case ComponentType.WebSiteRemover:
                    item = new IisRemoverComponentGraph(section.Name, localValues, ComponentType.WebSiteRemover);
                    break;
                case ComponentType.ApplicationRemover:
                    item = new IisRemoverComponentGraph(section.Name, localValues, ComponentType.ApplicationRemover);
                    break;
                default:
                    throw new ArgumentException("unknown installer section: " + section[ComponentTypeString]);
            }

            if (item != null)
            {
                item.Index = index;
            }

            return item;
        }
        internal CollectionsGroup(CollectionsGroupCollection collections, ConfigSection parent)
        {
            if (collections == null)
            {
                throw new ArgumentException("CollectionsGroupCollection object was null.");
            }
            Collections = collections;

            foreach (ConfigurationGroupElement configGroup in collections)
            {
                collectionNames.Add(configGroup.Name);
            }

            Parent = parent;
        }
        internal CollectionsGroup(CollectionsGroupCollection collections, ConfigSection parent, bool allowValueInheritance)
        {
            AllowValueInheritance = allowValueInheritance;
            if (collections == null)
            {
                throw new ArgumentException("CollectionsGroupCollection object was null.");
            }
            Collections = collections;

            foreach (ConfigurationGroupElement configGroup in collections)
            {
                collectionNames.Add(configGroup.Name);
            }

            Parent = parent;
        }
		public static Configuration ProtectedConfiguration( string connectionProvider, ConfigSection configSection, Configuration configuration )
		{
			switch( configSection )
			{
				case ConfigSection.AppSettings:
					configuration = ProtectAppSettings( connectionProvider, configuration );
					break;
				case ConfigSection.ConnectionStrings:
					configuration = ProtectConnectionStrings( connectionProvider, configuration );
					break;
				default:
					configuration = ProtectAppSettings( connectionProvider, configuration );
					configuration = ProtectConnectionStrings( connectionProvider, configuration );
					break;
			}
			return configuration;
		}
        public override void Initialise(IBuilderContext builderContext)
        {
            var configMain = builderContext.ConfigurationResolver
                                 .GetConfigSection(HiveConfigSection.ConfigXmlKey) as HiveConfigSection;

            if (configMain == null)
                throw new ConfigurationErrorsException(
                    string.Format("Configuration section '{0}' not found when building packaging provider '{1}'",
                                  HiveConfigSection.ConfigXmlKey, ProviderKey));

            var readWriteConfig = configMain.Providers.ReadWriters[ProviderKey] ?? configMain.Providers.Readers[ProviderKey];

            if (readWriteConfig == null)
                throw new ConfigurationErrorsException(
                    string.Format("No configuration found for persistence provider '{0}'", ProviderKey));

            var deepConfigManager = DeepConfigManager.Default;
            var localConfig = !string.IsNullOrEmpty(readWriteConfig.ConfigSectionKey)
                              ? deepConfigManager.GetFirstWebSetting<ConfigSection, ConfigSection>(readWriteConfig.ConfigSectionKey, x => x, "~/App_Plugins")
                                ??
                                readWriteConfig.GetLocalProviderConfig() as ConfigSection
                              : null;

            _configSection = localConfig;

            // ElementInformation.Source appears to be one of few ways to determine if the config-section exists or was returned on-demand with default values
            if (_configSection != null && !string.IsNullOrEmpty(_configSection.ElementInformation.Source))
            {
                CanBuild = true;
                var supportedExtensions = deepConfigManager.GetFirstWebSetting<ConfigSection, string>(readWriteConfig.ConfigSectionKey, x => x.SupportedExtensions, "~/App_Plugins");
                var rootPath = deepConfigManager.GetFirstWebSetting<ConfigSection, string>(readWriteConfig.ConfigSectionKey, x => x.RootPath, "~/App_Plugins");
                var excludedExtensions = deepConfigManager.GetFirstWebSetting<ConfigSection, string>(readWriteConfig.ConfigSectionKey, x => x.ExcludedExetensions, "~/App_Plugins");
                var excludedDirectories = deepConfigManager.GetFirstWebSetting<ConfigSection, string>(readWriteConfig.ConfigSectionKey, x => x.ExcludedDirectories, "~/App_Plugins");
                var rootPublicDomain = deepConfigManager.GetFirstWebSetting<ConfigSection, string>(readWriteConfig.ConfigSectionKey, x => x.RootPublicDomain, "~/App_Plugins");
                rootPath = rootPath.TrimEnd("/") + "/";
                _settings = new Settings(supportedExtensions, "", rootPath, excludedExtensions, excludedDirectories, rootPublicDomain);
            }
            else
            {
                LogHelper.Warn<ProviderDemandBuilder>("Cannot register dependencies for provider {0} because ProviderConfigurationSection was specified with key '{1}' but no matching configSection was found. The provider may not be installed correctly.",
                    ProviderKey,
                    readWriteConfig.ConfigSectionKey);
            }
        }
 public BoolKeyAttribute(ConfigSection section, bool defaultValue, string description)
     : base(section, typeof(bool), defaultValue, description)
 {
 }
Beispiel #8
0
        static MenuState ShowSectionList() {
            Refresh( "Editing {0}", Paths.ConfigFileName );

            TextMenu menu = new TextMenu();

            ConfigSection[] sections = (ConfigSection[])Enum.GetValues( typeof( ConfigSection ) );
            for( int i = 0; i < sections.Length; i++ ) {
                menu.AddOption( i + 1,
                                sections[i].ToString(),
                                sections[i] );
            }
            TextOption optionRanks = menu.AddOption( sections.Length + 1, "Ranks" );

            menu.Column = Column.Right;
            TextOption optionSaveAndExit = menu.AddOption( "S", "Save and exit" );
            TextOption optionQuit = menu.AddOption( "Q", "Quit without saving" );
            TextOption optionResetEverything = menu.AddOption( "D", "Use defaults" );
            TextOption optionReloadConfig = menu.AddOption( "R", "Reload config" );

            var choice = menu.Show();

            if( choice == optionSaveAndExit ) {
                if( TextMenu.ShowYesNo( "Save and exit?" ) && Config.Save() ) {
                    return MenuState.Done;
                }

            } else if( choice == optionQuit ) {
                if( TextMenu.ShowYesNo( "Exit without saving?" ) ) {
                    return MenuState.Done;
                }

            } else if( choice == optionResetEverything ) {
                if( TextMenu.ShowYesNo( "Reset everything to defaults?" ) ) {
                    Config.LoadDefaults();
                    RankManager.ResetToDefaults();
                    Config.ResetLogOptions();
                }

            } else if( choice == optionReloadConfig ) {
                if( File.Exists( Paths.ConfigFileName ) ) {
                    if( TextMenu.ShowYesNo( "Reload configuration from \"{0}\"?",
                                            Paths.ConfigFileName ) ) {
                        Config.Reload( true );
                        Console.WriteLine( "Configuration file \"{0}\" reloaded.", Paths.ConfigFileName );
                    }
                } else {
                    Console.WriteLine( "Configuration file \"{0}\" does not exist.", Paths.ConfigFileName );
                }

            } else if( choice == optionRanks ) {
                return MenuState.Ranks;

            } else {
                currentSection = (ConfigSection)choice.Tag;
                return MenuState.KeyList;
            }

            return MenuState.SectionList;
        }
Beispiel #9
0
 /// <summary>
 /// Get the configuration value for a specific key
 /// </summary>
 /// <param name="section">The configuration section</param>
 /// <param name="key">Config file key</param>
 /// <param name="defaultValue">Default value - Returned the key cannot be found</param>
 /// <returns>The configuration value</returns>
 public static string GetValueForSection(ConfigSection section, string key, string defaultValue)
 {
     return(GetValueForSection(section.ToString(), key, defaultValue));
 }
Beispiel #10
0
 /// <summary>
 /// Add configuration override values
 /// </summary>
 /// <param name="configurations">Dictionary of configuration overrides</param>
 /// <param name="section">What section it should be added to</param>
 /// <param name="overrideExisting">If the override already exists should we override it</param>
 public static void AddTestSettingValues(IDictionary <string, string> configurations, ConfigSection section = DEFAULTMAQSSECTION, bool overrideExisting = false)
 {
     AddTestSettingValues(configurations, section.ToString(), overrideExisting);
 }
Beispiel #11
0
 public IntKeyAttribute(ConfigSection section, int defaultValue, [NotNull] string description)
     : base(section, typeof(int), defaultValue, description) {
     MinValue = int.MinValue;
     MaxValue = int.MaxValue;
 }
 public SqlPlusConfiguration()
 {
     const string sectionName = "sqlPlus";
     _configuration = new ConfigSection(sectionName);
 }
Beispiel #13
0
 public ColorKeyAttribute( ConfigSection section, string defaultColor, string description )
     : base( section, typeof( string ), Color.GetName( defaultColor ), description ) {
 }
        public void VerifyStripLeadingValueSpaces()
        {
            ConfigSection section = processor["nunit"];

            Assert.AreEqual("value", section["lvs"]);
        }
        public void VerifyStripTrailingKeySpaces()
        {
            ConfigSection section = processor["nunit"];

            Assert.AreEqual("value", section["tks"]);
        }
        static public void PlugInRemoveValue(ModToolPlugin tool, string key)
        {
            ConfigSection pluginSection = GetSectionForPlugin(tool);

            pluginSection.RemoveValue(key);
        }
        public void VerifyDiscardSingleQuotes()
        {
            ConfigSection section = processor["nunit"];

            Assert.AreEqual("single quote test", section["sqt"]);
        }
        static public void PlugInSetValue(ModToolPlugin tool, string key, string val)
        {
            ConfigSection pluginSection = GetSectionForPlugin(tool);

            pluginSection[key] = val;
        }
Beispiel #19
0
 /// <summary>
 /// Get a specific config section
 /// </summary>
 /// <param name="section">The configuration section</param>
 /// <returns>Section values, with overrides respected</returns>
 public static Dictionary <string, string> GetSection(ConfigSection section)
 {
     return(GetSection(section.ToString()));
 }
Beispiel #20
0
 public static bool DoesKeyExist(string key, ConfigSection section = ConfigSection.MagenicMaqs)
 {
     return(DoesKeyExist(key, section.ToString()));
 }
Beispiel #21
0
 public BoolKeyAttribute( ConfigSection section, bool defaultValue, string description )
     : base( section, typeof( bool ), defaultValue.ToString( CultureInfo.InvariantCulture ), description ) {
 }
        public void VerifyParseEmptyValue()
        {
            ConfigSection section = processor["nunit"];

            Assert.AreEqual("", section["emptyvalue"]);
        }
Beispiel #23
0
        static MenuState ShowSectionList()
        {
            ShowSeparator();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Config sections:");
            Console.ResetColor();
            for (int i = 0; i < sections.Length; i++)
            {
                Console.WriteLine("  {0}. {1}", i + 1, sections[i]);
            }
            //Console.WriteLine( "  Q. Quit" );
            //Console.WriteLine( "  R. Reset All" );
            //Console.WriteLine( "  S. Save" );

            string replyString;
            int reply;
            do
            {
                Console.Write("Enter your selection: "); // TODO
                replyString = Console.ReadLine();
                //!replyString.Equals("Q", StringComparison.OrdinalIgnoreCase) &&
                //     !replyString.Equals( "R", StringComparison.OrdinalIgnoreCase ) &&
                //     !replyString.Equals( "S", StringComparison.OrdinalIgnoreCase ) &&
            } while (!Int32.TryParse(replyString, out reply) &&
                     !Enum.IsDefined(typeof(ConfigSection), reply - 1));

            currentSection = (ConfigSection)(reply - 1);

            return MenuState.KeyList;
        }
        public void VerifyParseEmptyKey()
        {
            ConfigSection section = processor["nunit"];

            Assert.AreEqual("emptykey", section[""]);
        }
Beispiel #25
0
 public BoolKeyAttribute( ConfigSection section, bool defaultValue, string description )
     : base( section, typeof( bool ), defaultValue, description ) {
 }
        public void VerifyCaseInsensitiveKeys()
        {
            ConfigSection section = processor["galeon 1.0"];

            Assert.AreEqual("Galeon", section["bRoWsEr"]);
        }
Beispiel #27
0
 public StringKeyAttribute( ConfigSection section, object defaultValue, string description )
     : base( section, typeof( string ), defaultValue, description ) {
     MinLength = NoLengthRestriction;
     MaxLength = NoLengthRestriction;
     Regex = null;
 }
        protected void LoadChildren()
        {
            lock (_syncObj)
            {
                if (_childrenLoaded)
                {
                    return;
                }
                ILogger        logger        = ServiceRegistration.Get <ILogger>();
                IPluginManager pluginManager = ServiceRegistration.Get <IPluginManager>();
                string         itemLocation  = Constants.PLUGINTREE_BASELOCATION + Location;
                // We'll use a FixedItemStateTracker in the hope that the configuration will be disposed
                // after usage. The alternative would be to use a plugin item state tracker which is able to
                // remove a config element usage. But this would mean to also expose a listener registration
                // to the outside. I think this is not worth the labor.
                _childPluginItemStateTracker = new FixedItemStateTracker(string.Format("ConfigurationManager: ConfigurationNode '{0}'", itemLocation));
                ICollection <PluginItemMetadata> items = pluginManager.GetAllPluginItemMetadata(itemLocation);
                ISet <string> childSet = new HashSet <string>();
                foreach (PluginItemMetadata itemMetadata in items)
                {
                    try
                    {
                        ConfigBaseMetadata metadata = pluginManager.RequestPluginItem <ConfigBaseMetadata>(itemMetadata.RegistrationLocation, itemMetadata.Id, _childPluginItemStateTracker);
                        ConfigBase         childObj = Instantiate(metadata, itemMetadata.PluginRuntime);
                        if (childObj == null)
                        {
                            continue;
                        }
                        AddChildNode(childObj);
                        childSet.Add(metadata.Id);
                    }
                    catch (PluginInvalidStateException e)
                    {
                        logger.Warn("Cannot add configuration node for {0}", e, itemMetadata);
                    }
                }
                ICollection <string> childLocations = pluginManager.GetAvailableChildLocations(itemLocation);
                foreach (string childLocation in childLocations)
                {
                    string childId = RegistryHelper.GetLastPathSegment(childLocation);
                    if (childSet.Contains(childId))
                    {
                        continue;
                    }
                    logger.Warn("Configuration: Configuration section '{0}' was found in the tree but not explicitly registered as section (config items in this section are registered by those plugins: {1})",
                                childLocation, StringUtils.Join(", ", FindPluginRegistrations(childLocation)));
                    ConfigSectionMetadata dummyMetadata = new ConfigSectionMetadata(childLocation, Constants.INVALID_SECTION_TEXT, null, null, null, null);
                    ConfigSection         dummySection  = new ConfigSection();
                    dummySection.SetMetadata(dummyMetadata);
                    AddChildNode(dummySection);
                }
                _childrenLoaded = true;
            }

            // Attach listeners after all children have been loaded
            // so that searching for child locations works correctly.
            foreach (var node in _childNodes)
            {
                AttachListenToLocations(node.ConfigObj);
            }
        }
Beispiel #29
0
        private PropertyPage CreatePropertyPage(PropertyPage page, ConfigSection section)
        {
            switch (section)
            {
            case ConfigSection.UserInterface:
            {
#if FAMISTUDIO_WINDOWS
                var scalingValues = new[] { "System", "100%", "150%", "200%" };
#elif FAMISTUDIO_MACOS
                var scalingValues = new[] { "System", "100%", "200%" };
#else
                var scalingValues = new[] { "System" };
#endif
                var scalingIndex         = Settings.DpiScaling == 0 ? 0 : Array.IndexOf(scalingValues, $"{Settings.DpiScaling}%");
                var timeFormatIndex      = Settings.TimeFormat < (int)TimeFormat.Max ? Settings.TimeFormat : 0;
                var followSequencerIndex = Settings.FollowSequencer <= 0 ? 0 : Settings.FollowSequencer % FollowSequencerStrings.Length;

                page.AddStringList("Scaling (Requires restart):", scalingValues, scalingValues[scalingIndex]); // 0
                page.AddStringList("Time Format:", TimeFormatStrings, TimeFormatStrings[timeFormatIndex]);     // 1
                page.AddBoolean("Check for updates:", Settings.CheckUpdates);                                  // 2
                page.AddBoolean("Trackpad controls:", Settings.TrackPadControls);                              // 3
#if FAMISTUDIO_MACOS
                page.AddBoolean("Reverse trackpad direction:", Settings.ReverseTrackPad);                      // 4
                page.SetPropertyEnabled(4, Settings.TrackPadControls);
                page.PropertyChanged += Page_PropertyChanged;
                page.AddStringList("Follow Sequencer:", FollowSequencerStrings, FollowSequencerStrings[followSequencerIndex]);     // 5
#else
                page.AddStringList("Follow Sequencer:", FollowSequencerStrings, FollowSequencerStrings[followSequencerIndex]);     // 4
#endif
#if FAMISTUDIO_LINUX
                page.SetPropertyEnabled(0, false);
#endif

                break;
            }

            case ConfigSection.Sound:
            {
                page.AddIntegerRange("Stop instruments after (sec):", Settings.InstrumentStopTime, 0, 10); // 0
                page.AddBoolean("Prevent popping on square channels:", Settings.SquareSmoothVibrato);      // 1
                break;
            }

            case ConfigSection.MIDI:
            {
                int midiDeviceCount = Midi.InputCount;
                var midiDevices     = new List <string>();
                for (int i = 0; i < midiDeviceCount; i++)
                {
                    var name = Midi.GetDeviceName(i);
                    if (!string.IsNullOrEmpty(name))
                    {
                        midiDevices.Add(name);
                    }
                }

                var midiDevice = "";

                if (!string.IsNullOrEmpty(Settings.MidiDevice) && midiDevices.Contains(Settings.MidiDevice))
                {
                    midiDevice = Settings.MidiDevice;
                }
                else if (midiDevices.Count > 0)
                {
                    midiDevice = midiDevices[0];
                }

                page.AddStringList("Device :", midiDevices.ToArray(), midiDevice);     // 0
                break;
            }
            }

            page.Build();
            pages[(int)section] = page;

            return(page);
        }
Beispiel #30
0
        public static ReleaseVersion FromSection(ConfigSection section)
        {
            Version ver;
            try
            {
                ver = new Version(section.SubSection);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
                return null;
            }

            var version = new ReleaseVersion()
            {
                Version = ver,
                ReleaseType = ReleaseType.Major,
                DownloadPage = section.GetValue("DownloadPage")
            };

            Enum.TryParse<ReleaseType>(section.GetValue("ReleaseType"), true, out version.ReleaseType);

            return version;

        }
Beispiel #31
0
 public ColorKeyAttribute(ConfigSection section, [NotNull] string defaultColor, [NotNull] string description)
     : base(section, typeof(string), ChatColor.White, description) {
     if (defaultColor == null) throw new ArgumentNullException("defaultColor");
     string defaultColorName = ChatColor.GetName(defaultColor);
     if (defaultColorName == null) {
         throw new ArgumentException("Default color must be a valid color name.");
     }
     DefaultValue = defaultColorName;
 }
 public SectionDetails()
 {
   _section = new ConfigSection();
   _control = new FormControl();
   _designed = false;
   _rightToLeft = false;
   _width = -1;
 }
Beispiel #33
0
 public ConfigurableService(IConfig config)
 {
     _config = config.GetConfigForService <ConfigurableService, ConfigSection>();
 }
Beispiel #34
0
 /// <summary>
 /// Get the value from a specific section
 /// </summary>
 /// <param name="section">The configuration section</param>
 /// <param name="key">The key</param>
 /// <returns>The configuration value - Returns the empty string if the key is not found</returns>
 public static string GetValueForSection(ConfigSection section, string key)
 {
     return(GetValueForSection(section.ToString(), key, string.Empty));
 }
 protected override void customSerialize(ConfigSection section, ConfigFile file)
 {
     base.customSerialize(section, file);
     section.setValue("SplitterPosition", splitter.SplitterPosition);
 }
        public void InvalidKeysTest()
        {
            var configStore   = new MockConfigStore();
            var configSection = new ConfigSection(TraceType, configStore, SectionName);

            string rootPrefix = "Test.";

            var policy = new RoleInstanceStatusMaxAllowedHealthPolicy(configSection, rootPrefix);
            var ri     = new RoleInstance("1", RoleInstanceState.Unhealthy, DateTime.UtcNow);

            string maxAllowedKeyName = BaseRoleInstanceHealthPolicy.GetFullKeyName(
                rootPrefix,
                policy.Name,
                "HealthState");

            #region typo in key name

            string nonExistentKeyName = BaseRoleInstanceHealthPolicy.GetFullKeyName(
                rootPrefix,
                policy.Name,
                "HealthStatt"); // note the type from "HealthState". user has typed this in his clustermanifest.xml

            // set a default value to config store
            configStore.UpdateKey(SectionName, maxAllowedKeyName, HealthState.Error.ToString());

            // now update config store with an invalid key
            configStore.UpdateKey(SectionName, nonExistentKeyName, HealthState.Unknown.ToString());

            // fetch the correct key
            var maxAllowedHealthState = configStore.GetValue(SectionName, maxAllowedKeyName);

            const HealthState InputHealthState = HealthState.Unknown;
            HealthState       output           = policy.Apply(ri, InputHealthState);

            Assert.AreEqual(
                output,
                HealthState.Error,
                string.Format(CultureInfo.CurrentCulture, "Output health state clipped down from '{0}' to default max allowed state '{1}'", InputHealthState, output));

            // now user realizes that he has made a typo in his clustermanifest.xml
            configStore.UpdateKey(SectionName, maxAllowedKeyName, HealthState.Unknown.ToString());
            output = policy.Apply(ri, InputHealthState);

            Assert.AreEqual(output, HealthState.Unknown, string.Format(CultureInfo.CurrentCulture, "Output health state not clipped down from '{0}' to max allowed state '{1}'", InputHealthState, output));

            #endregion typo in key name

            #region typo in key value

            configStore.ClearKeys(); // revert to defaults
            string defaultMaxHealthState = policy.GetConfigValue(maxAllowedKeyName);

            Assert.AreEqual(defaultMaxHealthState, HealthState.Error.ToString());

            // In this case, we know the default value as 'Error'.
            // Ideally, we need to parse the enum and get the next higher enum to update the key with
            configStore.UpdateKey(SectionName, maxAllowedKeyName, "Wurning");

            output = policy.Apply(ri, InputHealthState);

            // verify that Wurning didn't apply due to the typo. Since input was higher (Unknown) than the default, the output is also Unknown
            // i.e. no clipping applied

            Assert.AreEqual(
                output,
                InputHealthState,
                string.Format(
                    CultureInfo.CurrentCulture,
                    "Output health state not altered from '{0}' to default max allowed state '{1}' as it may not be safe to apply default since input was already higher than default",
                    InputHealthState,
                    defaultMaxHealthState));

            // provide a lower health state. Since there is an error in parsing, a warning should be returned
            output = policy.Apply(ri, HealthState.Ok);

            // verify that input of Ok is converted to Warning so that user observes that something is wrong and fixes his typo

            Assert.AreEqual(
                output,
                HealthState.Warning,
                string.Format(
                    CultureInfo.CurrentCulture,
                    "Output health state altered from '{0}' to '{1}' as there was an error applying policy",
                    HealthState.Ok,
                    output));

            // user realizes typo and fixes it
            configStore.UpdateKey(SectionName, maxAllowedKeyName, HealthState.Warning.ToString());

            output = policy.Apply(ri, InputHealthState);

            // verify that the new max allowed policy is in effect
            Assert.AreEqual(
                output,
                HealthState.Warning,
                string.Format(CultureInfo.CurrentCulture, "Output health state clipped down from '{0}' to max allowed state '{1}'", InputHealthState, output));

            #endregion typo in key value
        }
Beispiel #37
0
 public void SetPathValue(string setting, string value)
 {
     SetValue(setting, ConfigSection.FixPath(value));
 }
Beispiel #38
0
        public void Update()
        {
            if (isFirstUpdate || configCache != Me.CustomData || Me.CustomData == "")
            {
                var config = new ConfigSection("main");
                config.Read(Me.CustomData);

                blockGroupName = config.Get <string>("block_group_name", "Heli Assist");

                start_mode       = config.Get <string>("start_mode", "flight");
                rememberLastMode = config.Get <bool>("remember_mode", true);

                maxFlightPitch = config.Get <float>("max_pitch", 40.0f);
                maxFlightRoll  = config.Get <float>("max_roll", 40.0f);

                maxLandingPitch = config.Get <float>("max_landing_pitch", 15.0f);
                maxLandingRoll  = config.Get <float>("max_landing_roll", 15.0f);

                precisionAimFactor = config.Get <float>("precision", 16.0f);
                mouseSpeed         = config.Get <float>("mouse_speed", 0.5f);

                if (Me.CustomData == "")
                {
                    Me.CustomData = configCache = config.write();
                }
                else
                {
                    configCache = Me.CustomData;
                }
            }

            var blockGroup = GridTerminalSystem.GetBlockGroupWithName(blockGroupName);

            if (blockGroup == null)
            {
                throw new Exception("Could not find block group with name '" + blockGroupName + "'");
            }

            controllerCache.Clear();
            blockGroup.GetBlocksOfType <IMyShipController>(controllerCache);
            if (!controllerCache.Any())
            {
                throw new Exception("Ship must have at least one ship controller");
            }
            controller = null;
            foreach (var controller in controllerCache)
            {
                if (controller.IsUnderControl || (controller.IsMainCockpit && this.controller == null))
                {
                    this.controller = controller;
                }
            }
            if (this.controller == null)
            {
                this.controller = controllerCache.First();
            }

            gyroCache.Clear();
            blockGroup.GetBlocksOfType <IMyGyro>(gyroCache);
            if (!gyroCache.Any())
            {
                throw new Exception("Ship must have atleast one gyroscope");
            }

            thrustCache.Clear();
            blockGroup.GetBlocksOfType <IMyThrust>(thrustCache);
            if (!thrustCache.Any())
            {
                throw new Exception("Ship must have atleast one thruster");
            }

            if (thrustController == null)
            {
                thrustController = new ThrusterController(controller, thrustCache);
            }
            else
            {
                thrustController.Update(controller, thrustCache);
            }

            if (gyroController == null)
            {
                gyroController = new GyroController(controller, gyroCache);
            }
            else
            {
                gyroController.Update(controller, gyroCache);
            }

            if (isFirstUpdate && rememberLastMode && IsValidMode(Storage))
            {
                SwitchToMode(Storage);
            }
            else if (isFirstUpdate)
            {
                SwitchToMode(start_mode);
            }

            isFirstUpdate  = false;
            updateFinished = true;
        }
Beispiel #39
0
 public EngineConfig(ConfigFile configFile)
 {
     section   = configFile.createOrRetrieveConfigSection("Engine");
     showStats = section.getValue("ShowStats", false);
 }
        private static void CreateActions(DeploymentStrategyComponentGraphBase deploymentStrategyComponentGraph, ConfigSection deployment, List<string> msdeployLocations)
        {
            foreach (ConfigSection section in deployment.Collections.GetCollections())
            {
                if (!section.ContainsKey("ComponentType"))
                {
                    //ignore sections such as MsDeploy Locations
                    continue;
                }

                ActionComponentGraphBase actionComponentGraph;
                ActionType actionType = TryParseComponentType(section["ComponentType"]);
                switch (actionType)
                {
                    case ActionType.FileDeployment:
                        actionComponentGraph = section.Create<FileCopyActionComponentGraph>();
                        break;
                    case ActionType.FilePermission:
                        actionComponentGraph = section.Create<SetFilePermissionComponentGraph>();
                        break;
                    case ActionType.AppPoolCreation:
                    case ActionType.AppPoolRemoval:
                    case ActionType.WebSiteCreation:
                    case ActionType.WebsiteRemoval:
                    case ActionType.AppCreation:
                    case ActionType.AppRemoval:
                        actionComponentGraph = section.Create<IisActionComponentGraph>();
                        break;
                    case ActionType.ApplicationExecution:
                        actionComponentGraph = section.Create<ApplicationExecutionDeploymentComponentGraph>();
                        break;
                    case ActionType.CreatePackage:
                        actionComponentGraph = section.Create<PackageCreationComponentGraph>();
                        break;
                    case ActionType.DeployPackage:
                        actionComponentGraph = section.Create<PackageDeploymentComponentGraph>();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                actionComponentGraph.ActionType = actionType;
                actionComponentGraph.MsDeployExeLocations.AddRange(msdeployLocations);
                deploymentStrategyComponentGraph.Actions.Add(actionComponentGraph);
            }
        }
Beispiel #41
0
 public EngineConfig(ConfigFile configFile)
 {
     section = configFile.createOrRetrieveConfigSection("Engine");
 }
        private static RemoteDetailsComponentGraph GetRemoteDetails(ConfigSection deployment)
        {
            //see if there are any remote details specified
            if (deployment.Collections.SectionNames.Contains("RemoteDetails"))
            {
                var details = deployment.Collections.GetCollection("RemoteDetails");
                return details.Create<RemoteDetailsComponentGraph>();
            }

            return null;
        }
 private static List<string> GetMsdeployLocations(ConfigSection deployment)
 {
     //see if there are any msdeploylocations specified
     List<string> msdeployLocations = new List<string>();
     if (deployment.Collections.SectionNames.Contains("MsDeployLocations"))
     {
         var msdeployLocs = deployment.Collections.GetCollection("MsDeployLocations");
         msdeployLocations.AddRange(msdeployLocs.ValuesAsDictionary.Where(x => !x.IsInherited).Select(location => location.Value));
     }
     return msdeployLocations;
 }
Beispiel #44
0
 public BaseScrapper(string scrapUri, ConfigSection config)
 {
     ScrapperUri = scrapUri;
     _config     = config;
 }
 static private ConfigSection GetSectionForPlugin(ModToolPlugin tool)
 {
     string sectionName = tool.GetType().Name;
     
     if (!s_pluginsConfig.ContainsValue(sectionName))
         s_pluginsConfig[sectionName] = new ConfigSection(sectionName);
     return s_pluginsConfig[sectionName];
 }
Beispiel #46
0
 protected StructuredDataExtractor GetDataExtractor(ConfigSection config)
 {
     return(new StructuredDataExtractor(config));
 }
Beispiel #47
0
 /// <summary>
 /// Returns a TreeNode created from a SettingBase.
 /// </summary>
 /// <param name="section">Setting to create TreeNode from.</param>
 /// <returns></returns>
 private TreeNode CreateTreeNode(ConfigSection section)
 {
   TreeNode node = new TreeNode();
   SectionDetails sectionTag = new SectionDetails();
   sectionTag.Section = section;
   node.Tag = sectionTag;
   node.Text = section.Text.Evaluate();
   node.ImageIndex = _treeSections.ImageList.Images.Count;
   node.SelectedImageIndex = _treeSections.ImageList.Images.Count;
   AddPNGToImageList(_treeSections.ImageList, section.SectionMetadata.IconSmallFilePath);
   return node;
 }
Beispiel #48
0
 public CameraSection(ConfigFile configFile)
 {
     configSection = configFile.createOrRetrieveConfigSection(Header);
 }
Beispiel #49
0
 public RankKeyAttribute( ConfigSection section, BlankValueMeaning blankMeaning, string description )
     : base( section, typeof( Rank ), "", description ) {
     CanBeLowest = true;
     CanBeHighest = true;
     BlankMeaning = blankMeaning;
     NotBlank = false;
 }
Beispiel #50
0
        public IBuildServerCredentials GetBuildServerCredentials(IBuildServerAdapter buildServerAdapter, bool useStoredCredentialsIfExisting)
        {
            lock (buildServerCredentialsLock)
            {
                IBuildServerCredentials buildServerCredentials = new BuildServerCredentials {
                    UseGuestAccess = true
                };

                const string CredentialsConfigName = "Credentials";
                const string UseGuestAccessKey     = "UseGuestAccess";
                const string UsernameKey           = "Username";
                const string PasswordKey           = "Password";
                using (var stream = GetBuildServerOptionsIsolatedStorageStream(buildServerAdapter, FileAccess.Read, FileShare.Read))
                {
                    if (stream.Position < stream.Length)
                    {
                        var protectedData = new byte[stream.Length];

                        stream.Read(protectedData, 0, (int)stream.Length);
                        try
                        {
                            byte[] unprotectedData = ProtectedData.Unprotect(protectedData, null,
                                                                             DataProtectionScope.CurrentUser);
                            using (var memoryStream = new MemoryStream(unprotectedData))
                            {
                                ConfigFile credentialsConfig = new ConfigFile("", false);

                                using (var textReader = new StreamReader(memoryStream, Encoding.UTF8))
                                {
                                    credentialsConfig.LoadFromString(textReader.ReadToEnd());
                                }

                                ConfigSection section = credentialsConfig.FindConfigSection(CredentialsConfigName);

                                if (section != null)
                                {
                                    buildServerCredentials.UseGuestAccess = section.GetValueAsBool(UseGuestAccessKey,
                                                                                                   true);
                                    buildServerCredentials.Username = section.GetValue(UsernameKey);
                                    buildServerCredentials.Password = section.GetValue(PasswordKey);

                                    if (useStoredCredentialsIfExisting)
                                    {
                                        return(buildServerCredentials);
                                    }
                                }
                            }
                        }
                        catch (CryptographicException)
                        {
                            // As per MSDN, the ProtectedData.Unprotect method is per user,
                            // it will throw the CryptographicException if the current user
                            // is not the one who protected the data.

                            // Set this variable to false so the user can reset the credentials.
                            useStoredCredentialsIfExisting = false;
                        }
                    }
                }

                if (!useStoredCredentialsIfExisting)
                {
                    buildServerCredentials = ShowBuildServerCredentialsForm(buildServerAdapter.UniqueKey, buildServerCredentials);

                    if (buildServerCredentials != null)
                    {
                        ConfigFile credentialsConfig = new ConfigFile("", true);

                        ConfigSection section = credentialsConfig.FindOrCreateConfigSection(CredentialsConfigName);

                        section.SetValueAsBool(UseGuestAccessKey, buildServerCredentials.UseGuestAccess);
                        section.SetValue(UsernameKey, buildServerCredentials.Username);
                        section.SetValue(PasswordKey, buildServerCredentials.Password);

                        using (var stream = GetBuildServerOptionsIsolatedStorageStream(buildServerAdapter, FileAccess.Write, FileShare.None))
                        {
                            using (var memoryStream = new MemoryStream())
                            {
                                using (var textWriter = new StreamWriter(memoryStream, Encoding.UTF8))
                                {
                                    textWriter.Write(credentialsConfig.GetAsString());
                                }

                                var protectedData = ProtectedData.Protect(memoryStream.ToArray(), null, DataProtectionScope.CurrentUser);
                                stream.Write(protectedData, 0, protectedData.Length);
                            }
                        }

                        return(buildServerCredentials);
                    }
                }

                return(null);
            }
        }
Beispiel #51
0
 public IPKeyAttribute( ConfigSection section, BlankValueMeaning defaultMeaning, string description )
     : base( section, typeof( IPAddress ), "", description ) {
     BlankMeaning = defaultMeaning;
     switch( BlankMeaning ) {
         case BlankValueMeaning.Any:
             DefaultValue = IPAddress.Any;
             break;
         case BlankValueMeaning.Loopback:
             DefaultValue = IPAddress.Loopback;
             break;
         default:
             DefaultValue = IPAddress.None;
             break;
     }
 }
Beispiel #52
0
            public static H5ConfigInfo Parse(string pJSON)
            {
                JObject      jo         = JObject.Parse(pJSON);
                var          properties = jo.Properties();
                H5ConfigInfo config     = new H5ConfigInfo();

                foreach (var p in properties)
                {
                    if (p.Name == "Config")
                    {//配置项
                        ConfigSection cs = new ConfigSection();
                        config.Config = cs;
                        var configSection = p.Value as JObject;
                        if (configSection != null)
                        {
                            var sh = configSection.Property("Shorthand").Value as JObject;
                            if (sh != null)
                            {
                                var items = sh.Properties();
                                cs.Shorthand = new Dictionary <string, string>();
                                foreach (var item in items)
                                {
                                    cs.Shorthand.Add(item.Name, item.Value.ToObject <string>());
                                }
                            }

                            //var common = configSection.Property("Common").Value as JObject;
                            //if (common != null)
                            //{
                            //    var script = common.Property("script").Value;
                            //    if (script != null)
                            //    {
                            //        cs.Script = script.ToObject<string[]>();
                            //    }
                            //    var style = common.Property("style").Value;
                            //    if (style != null)
                            //    {
                            //        cs.Style = style.ToObject<string[]>();
                            //    }
                            //}
                        }
                    }
                    else
                    {//页面
                        PageSection ps = new PageSection();
                        if (config.Pages == null)
                        {
                            config.Pages = new List <PageSection>();
                        }
                        config.Pages.Add(ps);
                        //
                        ps.Name = p.Name;
                        var psSection = p.Value as JObject;
                        if (psSection != null)
                        {
                            if (psSection.Property("path") != null && psSection.Property("path").Value != null)
                            {
                                ps.Path = psSection.Property("path").Value.ToObject <string>();
                            }
                            //if (psSection.Property("title") != null && psSection.Property("title").Value != null)
                            //    ps.Title = psSection.Property("title").Value.ToObject<string>();
                            //if (psSection.Property("plugin") != null && psSection.Property("plugin").Value != null)
                            //    ps.Plugin = psSection.Property("plugin").Value.ToObject<string[]>();
                            //if (psSection.Property("script") != null && psSection.Property("script").Value != null)
                            //    ps.Script = psSection.Property("script").Value.ToObject<string[]>();
                            //if (psSection.Property("style") != null && psSection.Property("style").Value != null)
                            //    ps.Style = psSection.Property("style").Value.ToObject<string[]>();
                            //var param = psSection.Property("param");
                            //if (param != null)
                            //{
                            //    var pObject = param.Value as JObject;
                            //    var items = pObject.Properties();
                            //    ps.Param = new Dictionary<string, string>();
                            //    foreach (var item in items)
                            //    {
                            //        ps.Param.Add(item.Name, item.Value.ToObject<string>());
                            //    }
                            //}
                        }
                    }
                }
                //
                return(config);
            }
Beispiel #53
0
 public EnumKeyAttribute( ConfigSection section, object defaultValue, string description )
     : base( section, defaultValue.GetType(), defaultValue, description ) {
     ValueType = defaultValue.GetType();
 }
 public ColorKeyAttribute(ConfigSection section, string defaultColor, string description)
     : base(section, typeof(string), Color.GetName(defaultColor), description)
 {
 }
Beispiel #55
0
 public IntKeyAttribute( ConfigSection section, int defaultValue, string description )
     : base( section, typeof( int ), defaultValue, description ) {
     MinValue = int.MinValue;
     MaxValue = int.MaxValue;
     PowerOfTwo = false;
     MultipleOf = 0;
     ValidValues = null;
     InvalidValues = null;
 }
 public EnumKeyAttribute(ConfigSection section, object defaultValue, string description)
     : base(section, defaultValue.GetType(), defaultValue, description)
 {
     ValueType = defaultValue.GetType();
 }