Esempio n. 1
0
        private Setting GetSetting(string section, string setting)
        {
            if (!_configuration.Contains(section))
            {
                _configuration.Add(section);
            }

            if (!_configuration[section].Contains(setting))
            {
                if (defaultGlobalSettings.ContainsKey(setting))
                {
                    //save
                    _configuration[section]
                    .Add(new Setting(setting, defaultGlobalSettings[setting]));

                    Save();
                }
                else if (defaultArraySettings.ContainsKey(setting))
                {
                    //save
                    _configuration[section]
                    .Add(new Setting(setting, defaultArraySettings[setting]));

                    Save();
                }
                else
                {
                    _configuration[section]
                    .Add(new Setting(setting, ""));
                    Save();
                }
            }

            return(_configuration[section][setting]);
        }
Esempio n. 2
0
        private static void TestUnityIntegration()
        {
            var forceFieldConfiguration = new Configuration();

            forceFieldConfiguration.Add <CachingAdvice>(ApplyAdvice.OnEveryMethod);
            forceFieldConfiguration.Add <ExceptionHandlingAdvice>(new ApplyAdviceOnAllRepositories());
            forceFieldConfiguration.Add <LoggerAdvice>(new ApplyAdviceOnAllRepositories());
            forceFieldConfiguration.Add <EmptyAdvice>(ApplyAdvice.OnEveryMethod);

            var unity = new ForceFieldUnityContainer(forceFieldConfiguration);

            unity.RegisterType <ICacheProvider, RamCacheProvider>();
            unity.RegisterType <ILoggingService, LoggingService>();
            unity.RegisterType <IOtherService, OtherService>();
            unity.RegisterType <ICacheConfigurationService, ExampleOfCacheConfigurationService>();
            unity.RegisterType <IPersonRepository, PersonRepository>();

            var repository = unity.Resolve <IPersonRepository>();

            repository.Save(new Person {
                Key = 1, Age = 25, Name = "John"
            });
            repository.GetByName("John");
            repository.GetByName("John");

            var service       = unity.Resolve <IOtherService>();
            var meaningOfLife = service.Bar();
        }
Esempio n. 3
0
    private void Grab()
    {
        var settings = new Configuration();

        settings.Add("Game Options");
        settings.Add("Audio Settings");
        settings.Add("Video Settings");
        settings.Add("Controls");

        #region Video Settings

        settings["Video Settings"]["Antialiasing"].PreComment = "PostProcessing.";
        settings["Video Settings"]["Antialiasing"].IntValue   = uiVideoSettings.antialiasing.value;
        settings["Video Settings"]["Antialiasing"].Comment    = "0 - none, 1 - FastApproximateAntialiasing, 2 - SubpixelMorphologicalAntialiasing, 3 - TemporalAntialiasing.";

        settings["Video Settings"]["Underwater Effects"].BoolValue = uiVideoSettings.underwaterEffects.isOn;
        settings["Video Settings"]["Bloom"].BoolValue             = uiVideoSettings.bloom.isOn;
        settings["Video Settings"]["Auto Exposure"].BoolValue     = uiVideoSettings.autoExposure.isOn;
        settings["Video Settings"]["Color Grading"].BoolValue     = uiVideoSettings.colorGrading.isOn;
        settings["Video Settings"]["Depth Of Field"].BoolValue    = uiVideoSettings.depthOfField.isOn;
        settings["Video Settings"]["Ambient Occlusion"].BoolValue = uiVideoSettings.ambientOcclusion.isOn;
        settings["Video Settings"]["Vignette"].BoolValue          = uiVideoSettings.vignette.isOn;
        settings["Video Settings"]["Motion Blur"].BoolValue       = uiVideoSettings.motionBlur.isOn;

        #endregion

        settingsData = settings;
    }
        private SettingsStore()
        {
            //check commandline
            var args = Environment.GetCommandLineArgs();

            foreach (var arg in args)
            {
                if (arg.Trim().StartsWith("-cfg="))
                {
                    ConfigFileName = arg.Trim().Replace("-cfg=", "").Trim();
                    Logger.Info($"Found -cfg loading: {ConfigFileName}");
                }
            }

            try
            {
                _configuration = Configuration.LoadFromFile(ConfigFileName);
            }
            catch (FileNotFoundException ex)
            {
                Logger.Info($"Did not find client config file at path ${ConfigFileName}, initialising with default config");

                _configuration = new Configuration();
                _configuration.Add(new Section("Position Settings"));
                _configuration.Add(new Section("Client Settings"));
                _configuration.Add(new Section("Network Settings"));

                Save();
            }
            catch (ParserException ex)
            {
                Logger.Error(ex, "Failed to parse client config, potentially corrupted. Creating backing and re-initialising with default config");

                MessageBox.Show("Failed to read client config, it might have become corrupted.\n" +
                                "SRS will create a backup of your current config file (client.cfg.bak) and initialise using default settings.",
                                "Config error",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);

                try
                {
                    File.Copy(ConfigFileName, ConfigFileName + ".bak", true);
                }
                catch (Exception e)
                {
                    Logger.Error(e, "Failed to create backup of corrupted config file, ignoring");
                }

                _configuration = new Configuration();
                _configuration.Add(new Section("Position Settings"));
                _configuration.Add(new Section("Client Settings"));
                _configuration.Add(new Section("Network Settings"));

                Save();
            }

            _inputSettingsStore = new InputSettingsStore(this);
        }
Esempio n. 5
0
        public ServerSettingsStore()
        {
            //check commandline
            var args = Environment.GetCommandLineArgs();

            foreach (var arg in args)
            {
                if (arg.StartsWith("-cfg="))
                {
                    cfgFile = arg.Replace("-cfg=", "").Trim();
                }
            }

            try
            {
                _configuration = Configuration.LoadFromFile(cfgFile);
            }
            catch (FileNotFoundException ex)
            {
                _logger.Info("Did not find server config file, initialising with default config", ex);

                _configuration = new Configuration();
                _configuration.Add(new Section("General Settings"));
                _configuration.Add(new Section("Server Settings"));
                _configuration.Add(new Section("External AWACS Mode Settings"));

                Save();
            }
            catch (ParserException ex)
            {
                _logger.Error(ex, "Failed to parse server config, potentially corrupted. Creating backing and re-initialising with default config");

                MessageBox.Show("Failed to read server config, it might have become corrupted.\n" +
                                "SRS will create a backup of your current config file (server.cfg.bak) and initialise using default settings.",
                                "Config error",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);

                try
                {
                    File.Copy(cfgFile, CFG_BACKUP_FILE_NAME, true);
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Failed to create backup of corrupted config file, ignoring");
                }

                _configuration = new Configuration();
                _configuration.Add(new Section("General Settings"));
                _configuration.Add(new Section("Server Settings"));
                _configuration.Add(new Section("External AWACS Mode Settings"));

                Save();
            }
        }
        Stateprinter CreatePrinter()
        {
            Configuration cfg = ConfigurationHelper.GetStandardConfiguration(" ");

            cfg.Add(new PublicFieldsHarvester());
            cfg.Add(new ToStringAwareHarvester());

            var sut = new Stateprinter(cfg);

            return(sut);
        }
Esempio n. 7
0
        public void Configure_MultipleConfigurationsAdded_ServiceCollectionContains()
        {
            // Arrange
            var configuration = new Configuration();
            var services      = new ServiceCollection();

            // Act
            configuration.Add(services => services.AddTransient <ISagaEventStore, SagaEventStoreMock>());
            configuration.Add(services => services.AddTransient <ISagaEventStore, SagaEventStoreMock>());
            configuration.Configure(services);

            // Assert
            Assert.NotEmpty(services);
        }
Esempio n. 8
0
        public void Load()
        {
            var filePath = Path.Combine(Application.persistentDataPath, _settingFileName);

            try
            {
                if (SteamClient.IsValid &&
                    SteamRemoteStorage.FileExists(_settingFileName))
                {
                    var str = Encoding.UTF8.GetString(SteamRemoteStorage.FileRead(_settingFileName));
                    _config = Configuration.LoadFromString(str);
                }
                else if (File.Exists(filePath))
                {
                    _config = Configuration.LoadFromFile(filePath);
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
            }

            if (_config == null)
            {
                _config = new Configuration();
                _config.Add("Binds");
                _config.Add("UserSettings");
                ExecuteDefaultSettings();
                Save();
            }

            try
            {
                ExecuteUserSettings();
            }
            catch (Exception e)
            {
                Debug.LogError(e.ToString());
            }

            try
            {
                ExecuteConfigBinds();
            }
            catch (Exception e)
            {
                Debug.LogError(e.ToString());
            }
        }
Esempio n. 9
0
 public PropertyGroupParameterEditor()
 {
     Configuration.Add("multiple", "0");
     Configuration.Add("entityType", "PropertyGroup");
     //don't publish the id for a property group, publish it's alias (which is actually just it's lower cased name)
     Configuration.Add("publishBy", "alias");
 }
 public PropertyTypeParameterEditor()
 {
     Configuration.Add("multiple", "0");
     Configuration.Add("entityType", "PropertyType");
     //don't publish the id for a property type, publish it's alias
     Configuration.Add("publishBy", "alias");
 }
        void IConfigurable.Configure(string name, IConfigurationValue value)
        {
            if (value.ShouldBeStoredSecure)
            {
                var type = ConnectionStringType.Custom;
                if (value is CosmosDocumentDatabaseAccessKey)
                {
                    type = ConnectionStringType.DocDb;
                }
                if (value is ServiceBusConnectionString)
                {
                    type = ConnectionStringType.ServiceBus;
                }

                ConnectionStrings.Add(new AppServiceConnectionString
                {
                    Name  = name,
                    Type  = type.ToString(),
                    Value = value
                });
            }
            else
            {
                Settings.Add(new AppServiceSetting(name, value));
            }

            MoveSettingsIntoStore();
        }
Esempio n. 12
0
        private void ParseFile(FileInfo file, Configuration configuration)
        {
            var lines = File.ReadAllLines(file.FullName);
            foreach (var line in lines)
            {
                if (line.IsEmpty())
                {
                    continue;
                }

                if (line.Contains(":"))
                {
                    var splat = line.Split(':');
                    var name = splat.First().Trim();
                    var value = splat.Skip(1).JoinAsString(":").Trim();
                    configuration.Add(new Configuration(name, value));
                    continue;
                }

                var newName = line.Trim();
                var newFile =
                    new FileInfo(Path.Combine(file.Directory.FullName, newName + "." + _subFileExtension));
                var newConfiguration = new Configuration(newName, c => c.BelongingTo(configuration));
                ParseFile(newFile, newConfiguration);
            }
        }
Esempio n. 13
0
        public async Task Render_MergedParametersHierarchy()
        {
            var conf = new Configuration();

            conf.Add("$i1", new Dictionary <string, object>()
            {
                { "a1", "S1" },
                { "a2", "S2" },
                { "a3", "S3" }
            });

            var md = new Metadata();

            md.Add("$i1", new Dictionary <string, object>()
            {
                { "a1", "P1" },
                { "a2", "P2" },
                { "a3", "" }
            });

            var p1 = new PageMock("", "", md);
            var s  = new Site("", "", p1, conf);

            s.Includes.Add(new TemplateMock("i1", "abc", new Metadata()
            {
                { "a1", "T1" }, { "a2", "T2" }, { "a3", "" }, { "a4", "T4" }
            }));

            var res1 = await m_Handler.ResolveAll("{% i1 { a1: I1, a2:, a4: } %}", s, p1, "/page1/");

            Assert.AreEqual("abc_page1.html_a1=I1,a2=P2,a3=S3,a4=T4", res1);
        }
        private WebAssemblyHostEnvironment InitializeEnvironment(IJSUnmarshalledRuntime jsRuntime)
        {
            var applicationEnvironment = jsRuntime.InvokeUnmarshalled <string>("Blazor._internal.getApplicationEnvironment");
            var hostEnvironment        = new WebAssemblyHostEnvironment(applicationEnvironment, WebAssemblyNavigationManager.Instance.BaseUri);

            Services.AddSingleton <IWebAssemblyHostEnvironment>(hostEnvironment);

            var configFiles = new[]
            {
                "appsettings.json",
                $"appsettings.{applicationEnvironment}.json"
            };

            foreach (var configFile in configFiles)
            {
                var appSettingsJson = jsRuntime.InvokeUnmarshalled <string, byte[]>(
                    "Blazor._internal.getConfig", configFile);

                if (appSettingsJson != null)
                {
                    // Perf: Using this over AddJsonStream. This allows the linker to trim out the "File"-specific APIs and assemblies
                    // for Configuration, of where there are several.
                    Configuration.Add <JsonStreamConfigurationSource>(s => s.Stream = new MemoryStream(appSettingsJson));
                }
            }

            return(hostEnvironment);
        }
Esempio n. 15
0
        // Todo:
        // - Could also supply modified/created dates if needed from the FnL...

        /// <summary>
        /// Initializes a new instance of FormAndListDataSource class
        /// </summary>
        public DnnFormAndList()
        {
            Out.Add(Constants.DefaultStreamName, new DataStream(this, Constants.DefaultStreamName, GetEntities, GetList));
            Configuration.Add(ModuleIdKey, FnLModuleIdDefaultToken);
            Configuration.Add(TitleFieldKey, EntityTitleDefaultKeyToken);
            Configuration.Add(ContentTypeKey, ContentTypeDefaultToken);
        }
Esempio n. 16
0
        public ModuleDataSource()
        {
            Out.Add("Default", new DataStream(this, "Default", GetContent));
            Out.Add("ListContent", new DataStream(this, "Default", GetListContent));

            Configuration.Add("ModuleId", "[Module:ModuleID||[Module:ModuleId]]");              // Look for ModuleID and ModuleId
        }
Esempio n. 17
0
 public DnnUserProfileDataSource()
 {
     Out.Add(Constants.DefaultStreamName, new DataStream(this, Constants.DefaultStreamName, GetList));
     Configuration.Add(UserIdsKey, UserIdsDefaultKeyToken);
     Configuration.Add(PropertiesKey, PropertiesDefaultKeyToken);
     Configuration.Add(ContentTypeKey, ContentTypeDefaultToken);
     Configuration.Add(TitleFieldKey, EntityTitleDefaultKeyToken);
 }
 public ConfigurationParameters BelongingTo(Configuration configuration)
 {
     if (configuration != null)
     {
         configuration.Add(Configuration);
     }
     return this;
 }
Esempio n. 19
0
 private ForceFieldUnityContainer CreateContainer()
 {
     var unityAdvisorConfiguration = new Configuration();
     unityAdvisorConfiguration.Add<TestAdvice>(ApplyAdvice.OnEveryMethod);
     var forceFieldUnityContainer = new ForceFieldUnityContainer(unityAdvisorConfiguration);
     forceFieldUnityContainer.RegisterType<ITestInterface, TestInterfaceExtended>();
     return forceFieldUnityContainer;
 }
Esempio n. 20
0
        public void SettingNullValues()
        {
            var sut = new Configuration();

            Assert.Throws <ArgumentNullException>(() => sut.SetCulture(null));
            Assert.Throws <ArgumentNullException>(() => sut.SetIndentIncrement(null));
            Assert.Throws <ArgumentNullException>(() => sut.SetNewlineDefinition(null));
            Assert.Throws <ArgumentNullException>(() => sut.SetOutputFormatter(null));
            Assert.Throws <ArgumentNullException>(() => sut.SetAreEqualsMethod(null));

            Assert.Throws <ArgumentNullException>(() => sut.Add((IFieldHarvester)null));
            Assert.Throws <ArgumentNullException>(() => sut.Add((IValueConverter)null));


            Assert.Throws <ArgumentNullException>(() => sut.Test.SetAreEqualsMethod(null));
            Assert.Throws <ArgumentNullException>(() => sut.Test.SetAutomaticTestRewrite(null));
        }
Esempio n. 21
0
        public void SetControlSetting(InputDevice device)
        {
            RemoveControlSetting(device.InputBind);

            _configuration.Add(new Section(device.InputBind.ToString()));

            //create the sections
            var section = _configuration[device.InputBind.ToString()];

            section.Add(new Setting("name", device.DeviceName.Replace("\0", "")));
            section.Add(new Setting("button", device.Button));
            section.Add(new Setting("value", device.ButtonValue));
            section.Add(new Setting("guid", device.InstanceGuid.ToString()));

            InputDevices[device.InputBind] = device;

            Save();
        }
Esempio n. 22
0
        public void Add_ActionIsNull_ThrowArgumentNull()
        {
            // Arrange
            var configuration = new Configuration();
            Action <IServiceCollection> action = null;

            // Assert
            Assert.Throws <ArgumentNullException>(() => configuration.Add(action));
        }
        public void AddInReverse()
        {
            var config = new Configuration();

            var handler1 = new EnumConverter();

            config.Add(handler1);
            Assert.AreEqual(1, config.ValueConverters.Count);
            Assert.AreEqual(0, config.FieldHarvesters.Count);
            Assert.AreEqual(handler1, config.ValueConverters.First());

            var handler2 = new EnumConverter();

            config.Add(handler2);
            Assert.AreEqual(2, config.ValueConverters.Count);
            Assert.AreEqual(0, config.FieldHarvesters.Count);
            Assert.AreEqual(handler2, config.ValueConverters.First());
        }
        public ServerSettingsStore()
        {
            try
            {
                _configuration = Configuration.LoadFromFile(CFG_FILE_NAME);
            }
            catch (FileNotFoundException ex)
            {
                _logger.Info("Did not find server config file, initialising with default config");

                _configuration = new Configuration();
                _configuration.Add(new Section("General Settings"));
                _configuration.Add(new Section("Server Settings"));
                _configuration.Add(new Section("External AWACS Mode Settings"));

                Save();
            }
            catch (ParserException ex)
            {
                _logger.Error(ex, "Failed to parse server config, potentially corrupted. Creating backing and re-initialising with default config");

                MessageBox.Show("Failed to read server config, it might have become corrupted.\n" +
                                "SRS will create a backup of your current config file (server.cfg.bak) and initialise using default settings.",
                                "Config error",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);

                try
                {
                    File.Copy(CFG_FILE_NAME, CFG_BACKUP_FILE_NAME, true);
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Failed to create backup of corrupted config file, ignoring");
                }

                _configuration = new Configuration();
                _configuration.Add(new Section("General Settings"));
                _configuration.Add(new Section("Server Settings"));
                _configuration.Add(new Section("External AWACS Mode Settings"));

                Save();
            }
        }
Esempio n. 25
0
        public ServerSettings()
        {
            ServerSetting = new bool[Enum.GetValues(typeof(ServerSettingType)).Length];

            try
            {
                _configuration = Configuration.LoadFromFile(CFG_FILE_NAME);
            }
            catch (FileNotFoundException ex)
            {
                _configuration = new Configuration();
                _configuration.Add(new Section("General Settings"));
                _configuration.Add(new Section("Server Settings"));
            }

            foreach (var section in _configuration)
            {
                if (section.Name.Equals("General Settings"))
                {
                    foreach (var setting in section)
                    {
                        try
                        {
                            ServerSettingType settingEnum;
                            if (Enum.TryParse(setting.Name, true, out settingEnum))
                            {
                                ServerSetting[(int)settingEnum] = setting.BoolValue;
                            }
                            else
                            {
                                _logger.Warn("Invalid setting: " + setting.Name);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Warn("Invalid setting: " + setting.Name);
                        }
                    }
                }
            }

            SaveAllGeneral(true);
        }
Esempio n. 26
0
        public void Should_Add_a_user_watching_an_exsisting_pipeline()
        {
            var skypename = "username";
            var pipeline = "somePipe";

            var configuration = new Configuration();
            configuration.Add(pipeline, skypename);
            Assert.That(configuration.Items[0].name, Is.EqualTo(pipeline));
            Assert.That(configuration.Items[0].users[0].skypeName, Is.EqualTo(skypename));
        }
Esempio n. 27
0
        private ForceFieldUnityContainer CreateContainer()
        {
            var unityAdvisorConfiguration = new Configuration();

            unityAdvisorConfiguration.Add <TestAdvice>(ApplyAdvice.OnEveryMethod);
            var forceFieldUnityContainer = new ForceFieldUnityContainer(unityAdvisorConfiguration);

            forceFieldUnityContainer.RegisterType <ITestInterface, TestInterfaceExtended>();
            return(forceFieldUnityContainer);
        }
Esempio n. 28
0
        public static void Save()
        {
            lock (_sync)
            {
                ConfigurationObj.Clear();
                ConfigurationObj.Add(Section.FromObject(nameof(DefaultSettings), Instanse));

                ConfigurationObj.SaveToFile(ConstStrings.CONFIGPATH);
            }
        }
Esempio n. 29
0
 /// <summary>
 /// Create instance and add to the configuration.
 /// If <param name="harvester"/> is null, use the <see cref="AllFieldsAndPropertiesHarvester"/> to harvest the fields.
 /// </summary>
 public ProjectionHarvester(
     Configuration configuration = null,
     IFieldHarvester harvester   = null)
 {
     if (configuration != null)
     {
         configuration.Add(this);
     }
     harvestingStrategy = harvester ?? new AllFieldsAndPropertiesHarvester();
 }
        public void TryFind()
        {
            var config = new Configuration();

            config.Add(new StandardTypesConverter(null));

            IValueConverter h;

            Assert.IsTrue(config.TryGetValueConverter(typeof(decimal), out h));
            Assert.IsTrue(h is StandardTypesConverter);
        }
Esempio n. 31
0
        public void SettingNullValues()
        {
            var sut = new Configuration();

            Assert.Throws <ArgumentNullException>(() => sut.SetCulture(null));
            Assert.Throws <ArgumentNullException>(() => sut.SetIndentIncrement(null));
            Assert.Throws <ArgumentNullException>(() => sut.SetNewlineDefinition(null));
            Assert.Throws <ArgumentNullException>(() => sut.SetOutputFormatter(null));
            Assert.Throws <ArgumentNullException>(() => sut.SetAreEqualsMethod(null));

            Assert.Throws <ArgumentNullException>(() => sut.Add((IFieldHarvester)null));
            Assert.Throws <ArgumentNullException>(() => sut.Add((IValueConverter)null));

            Assert.Throws <ArgumentNullException>(() => sut.AddHandler(null, t => new List <SanitizedFieldInfo>()));
            Assert.Throws <ArgumentNullException>(() => sut.AddHandler(t => true, null));
            Assert.Throws <ArgumentNullException>(() => sut.AddHandler(null, null));

            Assert.Throws <ArgumentNullException>(() => sut.Test.SetAreEqualsMethod((TestFrameworkAreEqualsMethod)null));
            Assert.Throws <ArgumentNullException>(() => sut.Test.SetAutomaticTestRewrite(null));
        }
Esempio n. 32
0
        private static void CreateNewConfig()
        {
            ConfigurationObj = new Configuration();

            Instanse = new DefaultSettings();

            ConfigurationObj.Add(Section.FromObject(nameof(DefaultSettings), Instanse));

            ConfigurationObj.SaveToFile(ConstStrings.CONFIGPATH);

            // var p = Configuration[nameof(DefaultSettings)].ToObject<DefaultSettings>();
        }
Esempio n. 33
0
        public AutomationUploader(IYoutubeUploader uploader, IYoutubeJobContainer archiveContainer, IPlaylistServiceConnectionContainer pscContainer, IYoutubeAccount account, IEnumerable <IObservationConfiguration> configurationsToAdd)
            : this(uploader, archiveContainer, pscContainer)
        {
            LOGGER.Debug($"Creating new instance of AutomationUploader with account with title {account?.Title ?? null}");
            Account = account;

            foreach (var config in configurationsToAdd)
            {
                LOGGER.Debug($"Adding configuration for template '{config.Template.Name}' and path '{config.PathInfo.Fullname}'");
                Configuration.Add(config);
            }
        }
Esempio n. 34
0
        private void SaveBinds()
        {
            _config.RemoveAllNamed("Binds");
            var bindSection = _config.Add("Binds");

            foreach (var bind in Binds.Binds)
            {
                var settingName  = bind.KeyName.ToString();
                var settingValue = bind.Command;
                bindSection.Add(settingName, settingValue);
            }
        }
        public void ImplementsIHaveConfiguration()
        {
            //Arrange
            var containerBuilder = new ContainerBuilder();
            var configuration = new Configuration();
            configuration.Add<TestAdvice>(ApplyAdvice.OnEveryMethod);

            //Act
            var forceFieldContainer = containerBuilder.Build(configuration);

            //Assert
            Assert.IsNotNull(forceFieldContainer as IHaveConfiguration);
        }
Esempio n. 36
0
        public void AllAdvicesShouldBeAutomaticlyRegistered()
        {
            //Arrange
            var configuration = new Configuration();
            configuration.Add<TestAdvice>(ApplyAdvice.OnEveryMethod);
            var container = new ForceFieldUnityContainer(configuration);

            //Act
            var resolvedAdvice = container.Resolve<TestAdvice>();

            //Assert
            Assert.IsNotNull(resolvedAdvice);
        }
Esempio n. 37
0
        private static void TestUnityIntegration()
        {
            var forceFieldConfiguration = new Configuration();
            forceFieldConfiguration.Add<CachingAdvice>(ApplyAdvice.OnEveryMethod);
            forceFieldConfiguration.Add<ExceptionHandlingAdvice>(new ApplyAdviceOnAllRepositories());
            forceFieldConfiguration.Add<LoggerAdvice>(new ApplyAdviceOnAllRepositories());
            forceFieldConfiguration.Add<EmptyAdvice>(ApplyAdvice.OnEveryMethod);

            var unity = new ForceFieldUnityContainer(forceFieldConfiguration);
            unity.RegisterType<ICacheProvider, RamCacheProvider>();
            unity.RegisterType<ILoggingService, LoggingService>();
            unity.RegisterType<IOtherService, OtherService>();
            unity.RegisterType<ICacheConfigurationService, ExampleOfCacheConfigurationService>();
            unity.RegisterType<IPersonRepository, PersonRepository>();

            var repository = unity.Resolve<IPersonRepository>();
            repository.Save(new Person { Key = 1, Age = 25, Name = "John" });
            repository.GetByName("John");
            repository.GetByName("John");

            var service = unity.Resolve<IOtherService>();
            var meaningOfLife = service.Bar();
        }
        public void ResolveComponentReturnsAProxy()
        {
            //Arrange
            var containerBuilder = new ContainerBuilder();
            containerBuilder.Register(c => new TestInterfaceExtended()).As<ITestInterface>();
            var configuration = new Configuration();
            configuration.Add<TestAdvice>(ApplyAdvice.OnEveryMethod);
            var forceFieldContainer = containerBuilder.Build(configuration);

            //Act
            var resolvedInterface = forceFieldContainer.Resolve<ITestInterface>();

            //Assert
            Assert.IsNotNull(resolvedInterface as IDynamicProxy);
        }
Esempio n. 39
0
        /// <summary>
        /// Parse a configuration command user.name='hola' user.password=what
        /// </summary>
        /// <param name="configCommand"></param>
        /// <returns></returns>
        public static IEnumerable<IConfiguration> ParseConfiguration(string configCommand)
        {
            Dictionary<string, IConfiguration> result = new Dictionary<string, IConfiguration>();
            MatchCollection matches = CommandExpression.Matches(configCommand);

            foreach (Match match in matches)
            {
                string config = match.Value;
                int firstDotIndex = config.IndexOf('.');

                // getting the category name of the command
                string category = config.Substring(0, firstDotIndex);

                //geting the property without the dot(.)
                string property = config.Substring(firstDotIndex + 1, (config.Length - firstDotIndex) - 1);

                var propertyInfo = ParseProperty(property);

                if (result.ContainsKey(category))
                {
                    result[category].Add(propertyInfo.Key, propertyInfo.Value);
                }
                else
                {
                    Configuration c = new Configuration(category);
                    c.Add(propertyInfo.Key, propertyInfo.Value);

                    result.Add(category, c);
                }
            }

            foreach (var item in result)
            {
                yield return item.Value;
            }
        }
        public ActionResult Edit([Bind(Include = "ClassroomId,CourseId,DataCenterId,UserId,Start,Name")] Classroom classroom, string sessionId)
        {
            if (ModelState.IsValid)
            {
                DataCenter dc = this.db.Query<DataCenter>().Where(d => d.DataCenterId == classroom.DataCenterId).FirstOrDefault();
                if (dc != null)
                {
                    Course crs = this.db.Query<Course>().Where(c => c.CourseId == classroom.CourseId).FirstOrDefault();
                    if (crs != null)
                    {
                        Project projectObject = new Project(this.st);
                        if (classroom.ClassroomId == 0)
                        {
                            projectObject.name = crs.Name + "-" + classroom.Start.ToShortDateString();
                            projectObject.region = dc.Region;
                            projectObject.Add();
                            if (projectObject.id != null)
                            {
                                classroom.Project = projectObject.id;
                                this.db.Add<Classroom>(classroom);
                                Log.Write(this.db, ControllerContext.HttpContext, new Log() { Message = LogMessages.create, Detail = "Classroom created for " + crs.Name + " on " + classroom.JSDate });
                            }
                        }
                        else
                        {
                            this.db.Update<Classroom>(classroom);
                            Log.Write(this.db, ControllerContext.HttpContext, new Log() { Message = LogMessages.update, Detail = "Classroom updated for  " + crs.Name + " on " + classroom.JSDate });
                        }

                        List<SeatTemp> sts = this.db.Query<SeatTemp>().Where(st => st.SessionId == sessionId).ToList();
                        List<int> stids = sts.Select(s => s.SeatId).ToList();
                        List<Seat> seatsToRemove = this.db.Query<Seat>().Where(s => !stids.Contains(s.SeatId)).ToList();
                        Configuration configuration = new Configuration(this.st);
                        foreach (Seat s in seatsToRemove)
                        {
                            this.db.Remove<Seat>(s);
                            configuration.Id = s.ConfigurationId;
                            configuration.Delete();
                        }

                        foreach (SeatTemp st in sts)
                        {
                            Seat s = st.ToSeat();
                            if (s.SeatId == 0)
                            {
                                if (s.ClassroomId == 0)
                                {
                                    s.ClassroomId = classroom.ClassroomId;
                                }

                                User usr = this.db.Query<User>().Where(u => u.UserId == s.UserId).FirstOrDefault();
                                configuration.Name = usr.EmailAddress + "-" + crs.Name;
                                configuration.Add(classroom.Project, classroom.Course.Template, dc.GateWayBackboneId, dc.Region);
                                if (configuration.Id != null)
                                {
                                    s.ConfigurationId = configuration.Id;
                                    this.db.Add<Seat>(s);
                                }
                            }

                            this.db.Remove<SeatTemp>(st);
                        }

                        this.db.SaveChanges();
                    }
                }

                return this.RedirectToAction("Index", "Home");
            }

            ViewBag.Session = sessionId;
            this.PopulateTemp(classroom.ClassroomId, ViewBag.Session);
            ViewBag.CourseId = new SelectList(this.db.Query<Course>(), "CourseId", "Name", classroom.CourseId);
            ViewBag.UserId = new SelectList(this.db.Query<User>(), "UserId", "EmailAddress", classroom.UserId);
            return this.View(classroom);
        }
Esempio n. 41
0
        public static Configuration GetDefault(string rootPath)
        {
            Configuration res = new Configuration();
            res.DefaultConfiguration = "Default";

            MappingInfo mapping = GetDefaultMapping(rootPath, "Default");
            res.Add(mapping);

            return res;
        }