public void it_will_throw_an_exception_when_an_anonymous_object_has_a_property_with_the_wrong_type()
 {
     var configReader = new ConfigurationReader(this.configSource).
         SetupConfigOf<IConfigurationAdapter1>(
         new
             {
                 StringProperty = "Default",
                 IntegerProperty = 12,
                 ColorProperty = Color.DimGray,
                 AddressProperty = Assembly.GetExecutingAssembly()  // Arbitrary choise. Just for the test's sake...
             });
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Initialize HotKey79.
        /// </summary>
        /// <param name="configurationReader">Configuration read from file.</param>
        public void Initialize(ConfigurationReader configurationReader)
        {
            if (IsAlreadyRunning())
            {
                throw new ProgramException("Only one instance of HotKey79 is allowed.");
            }

            List<HotKey> hotkeys = configurationReader.GetHotKeys();

            if (hotkeys.Count == 0)
            {
                throw new ProgramException("No command is defined in \"" + configurationReader.GetConfigurationFile() + "\".");
            }
            else
            {
                keyboardHook = new KeyboardHook();
                keyboardHook.KeyPressed += new EventHandler<KeyPressedEventArgs>(KeyboardHookKeyPressed);

                commands = new Dictionary<int, HotKey>();

                foreach (HotKey hotkey in hotkeys)
                {
                    int hotkeyId = keyboardHook.RegisterHotKey(hotkey.GetModifiers(), hotkey.GetKey());
                    commands.Add(hotkeyId, hotkey);
                }
            }
        }
        public void it_should_return_the_default_value_for_the_type()
        {
            var configReader = new ConfigurationReader(this.configSource).SetupConfigOf<IConfigurationAdapter1>();

            Assert.AreEqual(0, configReader.ConfigBrowser.Get<IConfigurationAdapter1>().IntegerProperty);
            Assert.AreEqual(Color.Empty, configReader.ConfigBrowser.Get<IConfigurationAdapter1>().ColorProperty);
        }
        public void it_should_map_the_correct_value_to_per_interface()
        {
            var configReader = new ConfigurationReader(configSource);

            var browser = configReader.SetupConfigOf<IConfigurationAdapter1>().SetupConfigOf<IConfigurationAdapter2>().ConfigBrowser;

            Assert.AreEqual("1prop1", browser.Get<IConfigurationAdapter1>().StringProperty);
            Assert.AreEqual("2prop1", browser.Get<IConfigurationAdapter2>().StringProperty);
        }
        public void it_will_use_the_default_values_when_no_value_was_specified_in_the_configuration()
        {
            var configReader = new ConfigurationReader(this.configSource).SetupConfigOf<IConfigurationAdapter1>(new ConfigurationAdapter1DefaultValues());

            var browser = configReader.ConfigBrowser.Get<IConfigurationAdapter1>();

            Assert.AreEqual("1prop1", browser.StringProperty);
            Assert.AreEqual(12, browser.IntegerProperty);
            Assert.AreEqual(Color.DimGray, browser.ColorProperty);
        }
 public void it_will_throw_an_exception_when_an_anonymous_object_is_missing_a_property_defined_in_the_configuration_adapter_interface()
 {
     var configReader = new ConfigurationReader(this.configSource).
         SetupConfigOf<IConfigurationAdapter1>(
         new
             {
                 StringProperty = "Default",
                 IntegerProperty = 12,
                 ColorProperty = Color.DimGray,
             });
 }
 public void Initialize()
 {
     ConfigurationReader configurationReader = new ConfigurationReader(new BinaryFormatter(), null);
     configuration = configurationReader.Read("config.cfg");
     mockCollisionHandler = new Mock<CollisionHandler>();
     planet = new Planet();
     planet.Mass = 100000;
     // asume 40.0 * 40.0 world, planet is in the center
     planet.Position = new Vector2(20.0f, 20.0f);
     planet.Velocity = new Vector2(0.0f, 0.0f);
     world = new World(new WorldObject[0]);
 }
        public void it_should_use_it_to_convert_type_that_have_no_type_converter()
        {
            var configReader = new ConfigurationReader(this.configSource);

            configReader.
                SetupCustomConverter(source => source.Split(';')).
                SetupCustomConverter((string source) => IPAddress.Parse(source)).
                SetupConfigOf<ICustomConversion>();

            var array = configReader.ConfigBrowser.Get<ICustomConversion>().StringArray;
            Assert.AreEqual(3, array.Count());
            Assert.AreEqual("value3", array.ElementAt(2));

            var ipAddress = configReader.ConfigBrowser.Get<ICustomConversion>().Address;
            Assert.IsNotNull(ipAddress);
            Assert.AreEqual("111.111.111.2", ipAddress.ToString());
        }
        public void it_will_use_default_values_from_an_anonymous_object_when_no_value_was_specified_in_the_configuration()
        {
            var configReader = new ConfigurationReader(this.configSource).
                SetupConfigOf<IConfigurationAdapter1>(
                new
                    {
                        StringProperty = "Default",
                        IntegerProperty = 12,
                        ColorProperty = Color.DimGray,
                        AddressProperty = (Uri) null
                    });

            var browser = configReader.ConfigBrowser.Get<IConfigurationAdapter1>();

            Assert.AreEqual("1prop1", browser.StringProperty);
            Assert.AreEqual(12, browser.IntegerProperty);
            Assert.AreEqual(Color.DimGray, browser.ColorProperty);
        }
Ejemplo n.º 10
0
        public void SaveFileTest()
        {
            string path = "etherduels.conf";
            conf.Path = path;
            conf.Save();

            ConfigurationReader reader = new ConfigurationReader(new BinaryFormatter(), null);
            Configuration secondConf = reader.Read(path);

            if (secondConf == null)
                Assert.Fail("Deserialized config is null");
            if (!secondConf.Equals(conf))
                Assert.Fail("Deserialized config != original conf");

            conf.ToString();

            secondConf.ToString();
        }
        public void it_should_convert_the_string_values_to_the_data_types()
        {
            var configReader = new ConfigurationReader(this.configSource);

            configReader.
                SetupConfigOf<IConfigurationAdapter1>().
                SetupConfigOf<IConfigurationAdapter2>();

            IConfigurationBrowser configurations = configReader.ConfigBrowser;

            var configurationAdapter1 = configurations.Get<IConfigurationAdapter1>();

            Assert.IsNotNull(configurationAdapter1);
            Assert.IsNotNull(configurations.Get<IConfigurationAdapter2>());

            Assert.AreEqual("1prop1", configurationAdapter1.StringProperty);
            Assert.AreEqual(2, configurationAdapter1.IntegerProperty);
            Assert.AreEqual(Color.White, configurationAdapter1.ColorProperty);
            Assert.AreEqual(new Uri("http://localhost"), configurationAdapter1.AddressProperty);
        }
Ejemplo n.º 12
0
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new {id = RouteParameter.Optional}
                );

            var tokenBuilder = new SecurityTokenBuilder();
            var configReader = new ConfigurationReader();

            var jwtHandlerCert = new JwtAuthenticationMessageHandler
            {
                AllowedAudience = configReader.AllowedAudience,
                AllowedAudiences = configReader.AllowedAudiences,
                Issuer = configReader.Issuer,
                SigningToken = tokenBuilder.CreateFromCertificate(configReader.SubjectCertificateName),
                PrincipalTransformer = new SamplePrincipalTransformer()
            };

            var jwtHandlerSharedKey = new JwtAuthenticationMessageHandler
            {
                AllowedAudience = configReader.AllowedAudience,
                Issuer = configReader.Issuer,
                SigningToken = tokenBuilder.CreateFromKey(configReader.SymmetricKey),
                PrincipalTransformer = new SamplePrincipalTransformer(),
                CookieNameToCheckForToken = configReader.CookieNameToCheckForToken
            };

            config.MessageHandlers.Add(jwtHandlerCert);
            config.MessageHandlers.Add(jwtHandlerSharedKey);

            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();

            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();
        }
        public void it_should_read_the_default_values_of_the_second_adapter()
        {
            var configDictionaryToReturn =
                new Dictionary<string, string>
                    {
                        {"ConfigurationAdapter1.IntegerProperty", 2.ToString()},
                        {"ConfigurationAdapter1.StringProperty", "1prop1"},
                        {"ConfigurationAdapter1.ColorProperty", "#FFFFFF"},
                        {"ConfigurationAdapter1.AddressProperty", "http://localhost"}
                    };

            SetupResult.For(this.configSource.GetConfigDictionary()).Return(configDictionaryToReturn);

            this.mocks.ReplayAll();

            var configReader = new ConfigurationReader(configSource);

            configReader.SetupConfigOf<IConfigurationAdapter1>(new DefaultAdapter1Values());
            configReader.SetupConfigOf<IConfigurationAdapter2>(new DefaultAdapter2Values());

            Assert.AreEqual(true, configReader.ConfigBrowser.Get<IConfigurationAdapter2>().BoolProperty);
        }
Ejemplo n.º 14
0
        public void ReadDefaultIntValueFromConstructor()
        {
            var settings = ConfigurationReader <SettingsWithOptionalInt> .ReadFromCollection(new KeyValueConfigurationCollection());

            Assert.AreEqual(SettingsWithOptionalInt.DefaultValue, settings.IntValue);
        }
Ejemplo n.º 15
0
    /// 加载资源映射文件
    private static void LoadConfig()
    {
        string mapText = ConfigurationReader.GetConfigFile(FILE_NAME);

        ConfigurationReader.Load(mapText, configMap, BuildMap);
    }
Ejemplo n.º 16
0
 internal StandardConfigurationLoader(StandardClientOptions options, IConfiguration configuration)
 {
     Options             = options ?? throw new ArgumentNullException(nameof(options));
     Configuration       = configuration ?? throw new ArgumentNullException(nameof(configuration));
     ConfigurationReader = new ConfigurationReader(Configuration);
 }
 public void SetUp()
 {
     _configurationReader = ContextRegistry.GetContext()["ConfigurationReader"] as ConfigurationReader;
 }
Ejemplo n.º 18
0
        private static void Initialize(Type componentType)
        {
            // this is to ensure, that assemblies placed next to the component assembly can be loaded
            // even when they are not strong named.
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            FileInfo componentAssemblyFile = new FileInfo(componentType.Assembly.Location);
            FileInfo assemblyFile          = new FileInfo(componentAssemblyFile.FullName);

            bool     isRunningOutOfProcess = IsRunningOutOfProcess();
            FileInfo configFile            = new FileInfo(componentAssemblyFile.FullName + ".config");

            // no config file and in-proc -> reuse app's context, error otherwise
            if (!configFile.Exists)
            {
                if (!isRunningOutOfProcess)
                {
                    // check for context with component's name
                    if (ContextRegistry.IsContextRegistered(componentType.Name))
                    {
                        Trace.WriteLine(string.Format("configuring COM InProc Server '{0}' using section <spring/context name={1}> from app.config", componentAssemblyFile.FullName, componentType.Name));
                        _appContext = ContextRegistry.GetContext(componentType.Name);
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("configuring COM InProc Server '{0}' using section <spring/context> from file '{1}'", componentAssemblyFile.FullName, configFile.FullName));
                        _appContext = ContextRegistry.GetContext();
                    }
                    return;
                }
                throw ConfigurationUtils.CreateConfigurationException("Spring-exported COM components require <spring/context> section in configuration file '" + configFile.FullName + "'");
            }

            // set and switch to component assembly's directory (affects resolving relative paths during context instantiation!)
            componentDirectory           = componentAssemblyFile.Directory.FullName;
            Environment.CurrentDirectory = componentDirectory;

            if (isRunningOutOfProcess)
            {
#if NET_2_0
                Trace.WriteLine(string.Format("configuring COM OutProc Server '{0}' using '{1}'", componentAssemblyFile.FullName, configFile.FullName));
                // read in config file
                ExeConfigurationSystem comConfig = new ExeConfigurationSystem(assemblyFile.FullName);
                // make the config "global" for this process, replacing any
                // existing configuration that might already have been loaded
                ConfigurationUtils.SetConfigurationSystem(comConfig, true);
                _appContext = ContextRegistry.GetContext();
#else
                _appContext = (IApplicationContext)ConfigurationReader.GetSection(new FileSystemResource(configFile.FullName), "spring/context");
#endif
            }
            else
            {
                Trace.WriteLine(string.Format("configuring COM InProc Server '{0}' using section <spring/context> from file '{1}'", componentAssemblyFile.FullName, configFile.FullName));
                _appContext = (IApplicationContext)ConfigurationReader.GetSection(new FileSystemResource(configFile.FullName), "spring/context");
            }
            if (_appContext == null)
            {
                throw ConfigurationUtils.CreateConfigurationException("Spring-exported COM components require <spring/context> section in configuration file");
            }
            Trace.WriteLine(string.Format("completed configuring COM Component '{0}' using '{1}'", componentAssemblyFile.FullName, configFile.FullName));
        }
Ejemplo n.º 19
0
        public void GoToCrossReferenceXMLPage(string ProfileName)
        {
            string CRId = GetCRTID(ProfileName.ToUpper());

            webDriver.Navigate().GoToUrl(ConfigurationReader.GetValue("CrossReferenceXMLPage") + CRId);
        }
Ejemplo n.º 20
0
    private void ReadConfiguration()
    {
        // TODO-RPB: Can this be broken up into more methods?
        m_configurationReader = gameObject.AddComponent <ConfigurationReader>();
        var configuration = m_configurationReader.GetConfiguration();

        if (configuration == null)
        {
            m_statusText.text = "[ ERROR ] Config file not found... falling back to default values";
            Debug.LogWarning("No configuration file found (unusual), so falling back to default values");
            configuration = new SongSortConfiguration();
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.LaunchSongKeyCodeString))
        {
            m_launchPlayerKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.LaunchSongKeyCodeString);
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.LaunchSongKeyCodeString))
        {
            m_skipSongKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.SkipSongKeyCodeString);
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.LaunchSongKeyCodeString))
        {
            m_holdSongKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.HoldSongKeyCodeString);
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.UndoKeyCodeString))
        {
            m_undoKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.UndoKeyCodeString);
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.TogglePlaybackModeKeyCodeString))
        {
            m_togglePlaybackModeKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.TogglePlaybackModeKeyCodeString);
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.ShowStatisticsKeyCodeString))
        {
            m_showStatisticsKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.ShowStatisticsKeyCodeString);
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.ShowControlsKeyCodeString))
        {
            m_showControlsKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.ShowControlsKeyCodeString);
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.ExitKeyCodeString))
        {
            m_exitKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.ExitKeyCodeString);
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.SeekForwardKeyCodeString))
        {
            m_seekForwardKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.SeekForwardKeyCodeString);
        }

        // RPB: This is optional. If empty, will fall back to the default.
        if (!string.IsNullOrEmpty(configuration.SeekBackwardKeyCodeString))
        {
            m_seekBackwardKeyCode = (KeyCode)System.Enum.Parse(typeof(KeyCode), configuration.SeekBackwardKeyCodeString);
        }

        m_seekIntervalSeconds = configuration.SeekIntervalSeconds;

        if (configuration.SkipBrowserDialogOnOpen)
        {
            m_songFolderSourceSongs = configuration.DefaultSourceDirectory;
        }
        else
        {
            var paths = StandaloneFileBrowser.OpenFolderPanel("Select Source Folder", "", false);

            if (paths == null || paths.Length == 0)
            {
                Application.Quit();
            }

            m_songFolderSourceSongs = paths[0];
        }

        if (configuration.FolderHotkeyMapping == null || configuration.FolderHotkeyMapping.Length == 0)
        {
            Debug.LogWarning("FolderHotkeyMapping not found! Falling back to defaults...");

            var approveMapping = new FolderHotkeyMapping("Approved", true, "RightArrow", "ApproveSound.wav");
            var rejectMapping  = new FolderHotkeyMapping("Rejected", true, "LeftArrow", "ApproveSound.wav");
            configuration.FolderHotkeyMapping = new FolderHotkeyMapping[] { approveMapping, rejectMapping };
        }

        // TODO-RPB: This needs to be error checked like crazy! I can imagine this being fragile
        for (int i = 0; i < configuration.FolderHotkeyMapping.Length; i++)
        {
            m_keyFolderMappings.Add(new FolderHotkeyMappingInternal(configuration.FolderHotkeyMapping[i], m_songFolderSourceSongs));
        }

        for (int i = 0; i < m_keyFolderMappings.Count; i++)
        {
            Directory.CreateDirectory(m_keyFolderMappings[i].AbsoluteFolderPath);

            StartCoroutine(SetAudioClip(m_keyFolderMappings[i]));
        }

        var allFiles = Directory.GetFiles(m_songFolderSourceSongs);

        if (configuration.RandomizeOrder)
        {
            System.Random rnd = new System.Random();
            allFiles = allFiles.OrderBy(x => rnd.Next()).ToArray();
        }

        m_songFilesToProcess = new Queue <string>();

        for (int i = 0; i < allFiles.Length; i++)
        {
            if (Path.GetExtension(allFiles[i]) == ".mp3")
            {
                m_songFilesToProcess.Enqueue(allFiles[i]);
            }
        }
    }
Ejemplo n.º 21
0
        public void EnList()
        {
            TransactionManagerServiceProxy proxyForTM = new TransactionManagerServiceProxy(ConfigurationReader.ReadValue(_context, "Settings", "TM") ?? "fabric:/ServiceFabricApp/TransactionManagerService");

            proxyForTM.Enlist().GetAwaiter().GetResult();
        }
Ejemplo n.º 22
0
        public async Task <bool> ModelUpdate(AffectedEntities model)
        {
            ServiceEventSource.Current.ServiceMessage(_context, "NDS - ModelUpdate");
            var nms = new NetworkModelServiceProxy(ConfigurationReader.ReadValue(_context, "Settings", "NMS") ?? "net.tcp://localhost:22330/NetworkModelServiceSF");
            ScadaStorageProxy storage = new ScadaStorageProxy(ConfigurationReader.ReadValue(_context, "Settings", "Storage"));
            var cimModel = await storage.GetCimModel();

            if (cimModel == null)
            {
                cimModel = new Dictionary <DMSType, Container>();
            }

            model.Insert = model.Insert.Where(x => this.GetDMSType(x) == DMSType.ANALOG || this.GetDMSType(x) == DMSType.DISCRETE ||
                                              this.GetDMSType(x) == DMSType.BREAKER || this.GetDMSType(x) == DMSType.DISCONNECTOR).ToList();
            model.Update = model.Update.Where(x => this.GetDMSType(x) == DMSType.ANALOG || this.GetDMSType(x) == DMSType.DISCRETE ||
                                              this.GetDMSType(x) == DMSType.BREAKER || this.GetDMSType(x) == DMSType.DISCONNECTOR).ToList();
            model.Delete = model.Delete.Where(x => this.GetDMSType(x) == DMSType.ANALOG || this.GetDMSType(x) == DMSType.DISCRETE ||
                                              this.GetDMSType(x) == DMSType.BREAKER || this.GetDMSType(x) == DMSType.DISCONNECTOR).ToList();

            if (model.Insert.Count > 0)
            {
                var dataInsert = await nms.GetValues(model.Insert);

                foreach (var item in dataInsert)
                {
                    var dmsType = GetDMSType(item.GID);
                    if (!cimModel.ContainsKey(dmsType))
                    {
                        cimModel.Add(dmsType, new Container());
                    }
                    cimModel[dmsType].AddEntity(item);
                }
            }
            if (model.Update.Count > 0)
            {
                var dataUpdate = await nms.GetValues(model.Update);

                foreach (var item in dataUpdate)
                {
                    var dmsType = GetDMSType(item.GID);
                    if (!cimModel.ContainsKey(dmsType))
                    {
                        cimModel.Add(dmsType, new Container());
                    }
                    cimModel[dmsType].RemoveEntity(item.GID);
                    cimModel[dmsType].AddEntity(item);
                }
            }
            if (model.Delete.Count > 0)
            {
                var dataDelete = await nms.GetValues(model.Delete);

                foreach (var item in dataDelete)
                {
                    var dmsType = GetDMSType(item.GID);
                    if (!cimModel.ContainsKey(dmsType))
                    {
                        cimModel.Add(dmsType, new Container());
                    }
                    cimModel[dmsType].RemoveEntity(item.GID);
                }
            }

            await storage.SetCimModel(cimModel);

            EnList();
            return(true);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Builds the logger factory adapter.
        /// </summary>
        /// <returns>a factory adapter instance. Is never <c>null</c>.</returns>
        private static ILoggerFactoryAdapter BuildLoggerFactoryAdapter()
        {
            object sectionResult = null;

            ArgUtils.Guard(delegate
            {
                sectionResult = ConfigurationReader.GetSection(COMMON_LOGGING_SECTION);
            }
                           , "Failed obtaining configuration for Common.Logging from configuration section 'common/logging'.");

            // configuration reader returned <null>
            if (sectionResult == null)
            {
                string message = (ConfigurationReader.GetType() == typeof(DefaultConfigurationReader))
                                     ? string.Format("no configuration section <{0}> found - suppressing logging output", COMMON_LOGGING_SECTION)
                                     : string.Format("Custom ConfigurationReader '{0}' returned <null> - suppressing logging output", ConfigurationReader.GetType().FullName);
                Trace.WriteLine(message);
                ILoggerFactoryAdapter defaultFactory = new NoOpLoggerFactoryAdapter();
                return(defaultFactory);
            }

            // ready to use ILoggerFactoryAdapter?
            if (sectionResult is ILoggerFactoryAdapter)
            {
                Trace.WriteLine(string.Format("Using ILoggerFactoryAdapter returned from custom ConfigurationReader '{0}'", ConfigurationReader.GetType().FullName));
                return((ILoggerFactoryAdapter)sectionResult);
            }

            // ensure what's left is a LogSetting instance
            ArgUtils.Guard(delegate
            {
                ArgUtils.AssertIsAssignable <LogSetting>("sectionResult", sectionResult.GetType());
            }
                           , "ConfigurationReader {0} returned unknown settings instance of type {1}"
                           , ConfigurationReader.GetType().FullName, sectionResult.GetType().FullName);

            ILoggerFactoryAdapter adapter = null;

            ArgUtils.Guard(delegate
            {
                adapter = BuildLoggerFactoryAdapterFromLogSettings((LogSetting)sectionResult);
            }
                           , "Failed creating LoggerFactoryAdapter from settings");

            return(adapter);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// The main entry point.
        /// </summary>
        /// <param name="args">Command line parameters.</param>
        public static void Main(string[] args)
        {
            Console.WriteLine(Resources.ProgramTitle, Utility.ReadVersion());
            if (args == null || (args.Length != 3 && args.Length != 4))
            {
                Console.WriteLine(Resources.ProgramUsage);
                Console.WriteLine(Resources.ProgramUsageExample);
            }
            else
            {
                string scenarioName = args[0];
                string traceFile    = args[1];
                string configFile   = args[2];
                string timingsFile  = (args.Length == 4) ? args[3] : null;

                Stream timings = null;

                try
                {
                    if (timingsFile != null)
                    {
                        if (File.Exists(timingsFile))
                        {
                            try
                            {
                                timings = new FileStream(timingsFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                        }
                        else
                        {
                            Console.WriteLine(Resources.TimingsFileDoesNotExist, timingsFile);
                        }
                    }

                    if (Utility.IsValidIdentifier(scenarioName))
                    {
                        try
                        {
                            WcfUnitConfiguration config = ConfigurationReader.Read(configFile);
                            TraceFileProcessor   tfp    = new TraceFileProcessor();
                            tfp.ProcessTraceFile(scenarioName, traceFile, timings, config);
                        }
                        catch (UserException ue)
                        {
                            Console.WriteLine(ue.Message);
                            Exception e = ue.InnerException;
                            while (e != null)
                            {
                                Console.WriteLine(e.Message);
                                e = e.InnerException;
                            }

                            Environment.Exit(1);
                        }
                    }
                    else
                    {
                        Console.WriteLine(Resources.InvalidScenarioName);
                        Environment.Exit(1);
                    }
                }
                finally
                {
                    if (timings != null)
                    {
                        timings.Dispose();
                    }
                }
            }
        }
        /// <summary>
        /// Sends the SMS.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task <SendSMSResponse> SendSMS(SendSMSRequest request, CancellationToken cancellationToken)
        {
            SendSMSResponse response = null;

            using (HttpClient client = new HttpClient())
            {
                // Create the Auth Request
                TheSmsWorksTokenRequest apiTokenRequest = new TheSmsWorksTokenRequest
                {
                    CustomerId = ConfigurationReader.GetValue("TheSMSWorksCustomerId"),
                    Key        = ConfigurationReader.GetValue("TheSMSWorksKey"),
                    Secret     = ConfigurationReader.GetValue("TheSMSWorksSecret")
                };

                String        apiTokenRequestSerialised = JsonConvert.SerializeObject(apiTokenRequest).ToLower();
                StringContent content = new StringContent(apiTokenRequestSerialised, Encoding.UTF8, "application/json");

                // First do the authentication
                var apiTokenHttpResponse = await client.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}auth/token", content, cancellationToken);

                if (apiTokenHttpResponse.IsSuccessStatusCode)
                {
                    TheSmsWorksTokenResponse apiTokenResponse =
                        JsonConvert.DeserializeObject <TheSmsWorksTokenResponse>(await apiTokenHttpResponse.Content
                                                                                 .ReadAsStringAsync());

                    // Now do the actual send
                    TheSmsWorksSendSMSRequest apiSendSmsRequest = new TheSmsWorksSendSMSRequest
                    {
                        Content     = request.Message,
                        Sender      = request.Sender,
                        Destination = request.Destination,
                        Schedule    = string.Empty,
                        Tag         = string.Empty,
                        Ttl         = 0
                    };

                    String apiSendSMSMessageRequestSerialised = JsonConvert.SerializeObject(apiSendSmsRequest).ToLower();
                    content = new StringContent(apiSendSMSMessageRequestSerialised, Encoding.UTF8, "application/json");

                    client.DefaultRequestHeaders.Add("Authorization", apiTokenResponse.Token);
                    var apiSendSMSMessageHttpResponse = await client.PostAsync($"{ConfigurationReader.GetValue("TheSMSWorksBaseAddress")}message/send", content, cancellationToken);

                    if (apiSendSMSMessageHttpResponse.IsSuccessStatusCode)
                    {
                        // Message has been sent
                        TheSmsWorksSendSMSResponse apiTheSmsWorksSendSmsResponse =
                            JsonConvert.DeserializeObject <TheSmsWorksSendSMSResponse>(await apiSendSMSMessageHttpResponse.Content
                                                                                       .ReadAsStringAsync());

                        response = new SendSMSResponse
                        {
                            ApiStatusCode = apiSendSMSMessageHttpResponse.StatusCode,
                            MessageId     = apiTheSmsWorksSendSmsResponse.MessageId,
                            Status        = apiTheSmsWorksSendSmsResponse.Status
                        };
                    }
                    else
                    {
                        response = await HandleAPIError(apiSendSMSMessageHttpResponse);
                    }
                }
                else
                {
                    response = await HandleAPIError(apiTokenHttpResponse);
                }
            }

            return(response);
        }
Ejemplo n.º 26
0
 public void SetUp()
 {
     configurationReader = new ConfigurationReader();
     cfg = configurationReader.Read();
 }
Ejemplo n.º 27
0
        public ActionResult Index()
        {
            Consumer objectConsumer = new Consumer();

            try
            {
                ConfigurationReader configurationReader = new ConfigurationReader();

                if (string.Equals(configurationReader.EmailTurnOn.ToLower(), "true"))
                {
                    EmailSender objEmailSender = new EmailSender(@".\Private$\EmailQueue");
                    MailMessage objMailMessage = new MailMessage();
                    objectConsumer.logEntry = new LogEntry {
                        Message = "Configuration read : ", Severity = TraceEventType.Information
                    };
                    objectConsumer.WriteLog(objectConsumer.logEntry);
                    objMailMessage.From = new MailAddress(configurationReader.EmailFrom);
                    char[] delimiters = new[] { ',', ';' };
                    bool   mailSent   = default(bool);

                    // EmailTo list
                    if (!string.IsNullOrEmpty(configurationReader.EmailTo))
                    {
                        if (configurationReader.EmailTo.Contains(",") || configurationReader.EmailTo.Contains(";"))
                        {
                            string[] emailToList = configurationReader.EmailTo.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                            foreach (var emailToItem in emailToList)
                            {
                                objMailMessage.To.Add(emailToItem);
                            }
                        }
                        else
                        {
                            objMailMessage.To.Add(configurationReader.EmailTo);
                        }
                    }

                    //EmailCC List
                    if (!string.IsNullOrEmpty(configurationReader.EmailCC))
                    {
                        if (configurationReader.EmailCC.Contains(",") || configurationReader.EmailCC.Contains(";"))
                        {
                            string[] emailCCList = configurationReader.EmailCC.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                            foreach (var emailCCItem in emailCCList)
                            {
                                objMailMessage.CC.Add(emailCCItem);
                            }
                        }
                        else
                        {
                            objMailMessage.CC.Add(configurationReader.EmailCC);
                        }
                    }

                    //EmailBCC List
                    if (!string.IsNullOrEmpty(configurationReader.EmailBcc))
                    {
                        if (configurationReader.EmailBcc.Contains(",") || configurationReader.EmailBcc.Contains(";"))
                        {
                            string[] emailBCCList = configurationReader.EmailBcc.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                            foreach (var emailBCCItem in emailBCCList)
                            {
                                objMailMessage.To.Add(emailBCCItem);
                            }
                        }
                        else
                        {
                            objMailMessage.Bcc.Add(configurationReader.EmailBcc);
                        }
                    }

                    objMailMessage.Subject    = "Sample message";
                    objMailMessage.IsBodyHtml = true;
                    objMailMessage.Body       = @"<h1>This is sample</h1><a href=""http://http://www.codeproject.com"">See this link</a>";

                    objEmailSender.QueueMessage(objMailMessage);
                    objectConsumer.logEntry = new LogEntry {
                        Message = "Successfully queued", Severity = TraceEventType.Information
                    };
                    objectConsumer.WriteLog(objectConsumer.logEntry);
                }
            }
            catch (Exception loggingEx)
            {
                //================================================================================================
                objectConsumer.logEntry = new LogEntry {
                    Message = "***************** Exception *****************", Severity = TraceEventType.Error
                };
                objectConsumer.WriteLog(objectConsumer.logEntry);
                objectConsumer.logEntry = new LogEntry {
                    Message = "Could not start the service : " + loggingEx.Message, Severity = TraceEventType.Critical
                };
                objectConsumer.WriteLog(objectConsumer.logEntry);
                objectConsumer.logEntry = new LogEntry {
                    Message = "Inner Exception : " + loggingEx.InnerException, Severity = TraceEventType.Error
                };
                objectConsumer.WriteLog(objectConsumer.logEntry);
                objectConsumer.logEntry = new LogEntry {
                    Message = "Stack Trace : " + loggingEx.StackTrace, Severity = TraceEventType.Error
                };
                objectConsumer.WriteLog(objectConsumer.logEntry);
                //================================================================================================
            }
            return(View());
        }
 public string Resolve(string name)
 {
     return(ConfigurationReader.ReadAppSetting(name));
 }
Ejemplo n.º 29
0
 public void OpenOSTHomePage()
 {
     webDriver.Navigate().GoToUrl(ConfigurationReader.GetValue("OSTHomePageUrl"));
 }
Ejemplo n.º 30
0
 public void Execute()
 {
     Logger.Trace("Starting Network Monitor");
     Start(ConfigurationReader.Read());
 }
        // Adds endpoints from config to KestrelServerOptions.ConfigurationBackedListenOptions and configures some other options.
        // Any endpoints that were removed from the last time endpoints were loaded are returned.
        internal (List <ListenOptions>, List <ListenOptions>) Reload()
        {
            var endpointsToStop  = Options.ConfigurationBackedListenOptions.ToList();
            var endpointsToStart = new List <ListenOptions>();

            Options.ConfigurationBackedListenOptions.Clear();
            DefaultCertificateConfig = null;

            ConfigurationReader = new ConfigurationReader(Configuration);

            LoadDefaultCert(ConfigurationReader);

            foreach (var endpoint in ConfigurationReader.Endpoints)
            {
                var listenOptions = AddressBinder.ParseAddress(endpoint.Url, out var https);

                Options.ApplyEndpointDefaults(listenOptions);

                if (endpoint.Protocols.HasValue)
                {
                    listenOptions.Protocols = endpoint.Protocols.Value;
                }
                else
                {
                    // Ensure endpoint is reloaded if it used the default protocol and the protocol changed.
                    // listenOptions.Protocols should already be set to this by ApplyEndpointDefaults.
                    endpoint.Protocols = ConfigurationReader.EndpointDefaults.Protocols;
                }

                // Compare to UseHttps(httpsOptions => { })
                var httpsOptions = new HttpsConnectionAdapterOptions();
                if (https)
                {
                    httpsOptions.SslProtocols = ConfigurationReader.EndpointDefaults.SslProtocols ?? SslProtocols.None;

                    // Defaults
                    Options.ApplyHttpsDefaults(httpsOptions);

                    if (endpoint.SslProtocols.HasValue)
                    {
                        httpsOptions.SslProtocols = endpoint.SslProtocols.Value;
                    }

                    // Specified
                    httpsOptions.ServerCertificate = LoadCertificate(endpoint.Certificate, endpoint.Name)
                                                     ?? httpsOptions.ServerCertificate;

                    if (httpsOptions.ServerCertificate == null && httpsOptions.ServerCertificateSelector == null)
                    {
                        // Fallback
                        Options.ApplyDefaultCert(httpsOptions);

                        // Ensure endpoint is reloaded if it used the default certificate and the certificate changed.
                        endpoint.Certificate = DefaultCertificateConfig;
                    }
                }

                // Now that defaults have been loaded, we can compare to the currently bound endpoints to see if the config changed.
                // There's no reason to rerun an EndpointConfigurations callback if nothing changed.
                var matchingBoundEndpoints = endpointsToStop.Where(o => o.EndpointConfig == endpoint).ToList();

                if (matchingBoundEndpoints.Count > 0)
                {
                    endpointsToStop.RemoveAll(o => o.EndpointConfig == endpoint);
                    Options.ConfigurationBackedListenOptions.AddRange(matchingBoundEndpoints);
                    continue;
                }

                if (EndpointConfigurations.TryGetValue(endpoint.Name, out var configureEndpoint))
                {
                    var endpointConfig = new EndpointConfiguration(https, listenOptions, httpsOptions, endpoint.ConfigSection);
                    configureEndpoint(endpointConfig);
                }

                // EndpointDefaults or configureEndpoint may have added an https adapter.
                if (https && !listenOptions.IsTls)
                {
                    if (httpsOptions.ServerCertificate == null && httpsOptions.ServerCertificateSelector == null)
                    {
                        throw new InvalidOperationException(CoreStrings.NoCertSpecifiedNoDevelopmentCertificateFound);
                    }

                    listenOptions.UseHttps(httpsOptions);
                }

                listenOptions.EndpointConfig = endpoint;

                endpointsToStart.Add(listenOptions);
                Options.ConfigurationBackedListenOptions.Add(listenOptions);
            }

            return(endpointsToStop, endpointsToStart);
        }
        public void ReadEndpointsSection_ReturnsCollection()
        {
            var config = new ConfigurationBuilder().AddInMemoryCollection(new[]
            {
                new KeyValuePair <string, string>("Endpoints:End1:Url", "http://*:5001"),
                new KeyValuePair <string, string>("Endpoints:End2:Url", "https://*:5002"),
                new KeyValuePair <string, string>("Endpoints:End3:Url", "https://*:5003"),
                new KeyValuePair <string, string>("Endpoints:End3:Certificate:Path", "/path/cert.pfx"),
                new KeyValuePair <string, string>("Endpoints:End3:Certificate:Password", "certpassword"),
                new KeyValuePair <string, string>("Endpoints:End4:Url", "https://*:5004"),
                new KeyValuePair <string, string>("Endpoints:End4:Certificate:Subject", "certsubject"),
                new KeyValuePair <string, string>("Endpoints:End4:Certificate:Store", "certstore"),
                new KeyValuePair <string, string>("Endpoints:End4:Certificate:Location", "cetlocation"),
                new KeyValuePair <string, string>("Endpoints:End4:Certificate:AllowInvalid", "true"),
            }).Build();
            var reader    = new ConfigurationReader(config);
            var endpoints = reader.Endpoints;

            Assert.NotNull(endpoints);
            Assert.Equal(4, endpoints.Count());

            var end1 = endpoints.First();

            Assert.Equal("End1", end1.Name);
            Assert.Equal("http://*:5001", end1.Url);
            Assert.NotNull(end1.ConfigSection);
            Assert.NotNull(end1.Certificate);
            Assert.False(end1.Certificate.ConfigSection.Exists());

            var end2 = endpoints.Skip(1).First();

            Assert.Equal("End2", end2.Name);
            Assert.Equal("https://*:5002", end2.Url);
            Assert.NotNull(end2.ConfigSection);
            Assert.NotNull(end2.Certificate);
            Assert.False(end2.Certificate.ConfigSection.Exists());

            var end3 = endpoints.Skip(2).First();

            Assert.Equal("End3", end3.Name);
            Assert.Equal("https://*:5003", end3.Url);
            Assert.NotNull(end3.ConfigSection);
            Assert.NotNull(end3.Certificate);
            Assert.True(end3.Certificate.ConfigSection.Exists());
            var cert3 = end3.Certificate;

            Assert.True(cert3.IsFileCert);
            Assert.False(cert3.IsStoreCert);
            Assert.Equal("/path/cert.pfx", cert3.Path);
            Assert.Equal("certpassword", cert3.Password);

            var end4 = endpoints.Skip(3).First();

            Assert.Equal("End4", end4.Name);
            Assert.Equal("https://*:5004", end4.Url);
            Assert.NotNull(end4.ConfigSection);
            Assert.NotNull(end4.Certificate);
            Assert.True(end4.Certificate.ConfigSection.Exists());
            var cert4 = end4.Certificate;

            Assert.False(cert4.IsFileCert);
            Assert.True(cert4.IsStoreCert);
            Assert.Equal("certsubject", cert4.Subject);
            Assert.Equal("certstore", cert4.Store);
            Assert.Equal("cetlocation", cert4.Location);
            Assert.True(cert4.AllowInvalid);
        }
        public void it_should_throw_an_exception_stating_the_property_name()
        {
            var configReader = new ConfigurationReader(configSource);

            configReader.SetupConfigOf<IConfigurationAdapter1>();
        }
Ejemplo n.º 34
0
        public void ReadIntoNestedClass()
        {
            var settings = ConfigurationReader <NestedSettings> .ReadFromCollection(new KeyValueConfigurationCollection());

            Assert.NotNull(settings);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Returns a set of random binary partial configurations.
        /// </summary>
        /// <param name="parameters">Parameters for this random sampling. The following paramters are supported:
        /// seed = the seed for the random generator (int required)
        /// numConfigs = the number of configurations that have to be selected.
        ///              To be able ot select a number of configurations equal to the number selected by the OW heuristic or
        ///              the TWise heuristics, two special values can be given for this paramter. To select a number equal to
        ///              the OW heuristics use "asOW" as value and to select a number equal to a TWise heuristics with a t of X
        ///              use "asTWX".
        /// </param>
        /// <returns>A list of random binary partial configuartions.</returns>
        public List <List <BinaryOption> > getRandomConfigs(Dictionary <String, String> parameters)
        {
            configurations.Clear();

            int seed       = 0;
            int numConfigs = varModel.WithAbstractBinaryOptions.Count;

            // parse parameters
            if (parameters.ContainsKey("numConfigs"))
            {
                String numConfigsValue = parameters["numConfigs"];
                if (!int.TryParse(numConfigsValue, out numConfigs))
                {
                    // special constants as parameter (numConfigs = asOW or asTWX
                    if (numConfigsValue.Contains("asOW"))
                    {
                        FeatureWise fw = new FeatureWise();
                        numConfigs = fw.generateFeatureWiseConfigsCSP(varModel).Count;
                    }
                    else if (numConfigsValue.Contains("asTW"))
                    {
                        numConfigsValue = numConfigsValue.Replace("asTW", "").Trim();
                        int.TryParse(numConfigsValue, out numConfigs);
                        TWise tw = new TWise();
                        numConfigs = tw.generateT_WiseVariants_new(varModel, numConfigs).Count;
                    }
                }
            }
            if (parameters.ContainsKey("seed"))
            {
                int.TryParse(parameters["seed"], out seed);
            }

            // build set of all valid binary partial configurations

            List <List <BinaryOption> > allConfigs = new List <List <BinaryOption> >();

            if (parameters.ContainsKey("fromFile"))
            {
                List <Configuration> allConfigurations = ConfigurationReader.readConfigurations(parameters["fromFile"], varModel);
                foreach (Configuration config in allConfigurations)
                {
                    allConfigs.Add(config.BinaryOptions.Keys.ToList());
                }
            }
            else
            {
                allConfigs = ConfigurationBuilder.vg.GenerateAllVariantsFast(varModel);
            }

            //repair wrong parameters
            if (numConfigs >= allConfigs.Count)
            {
                if (numConfigs > allConfigs.Count)
                {
                    GlobalState.logError.logLine("Random Sampling: numConfigs to large for variability model. num set to " + allConfigs.Count);
                }
                configurations = allConfigs;
                return(allConfigs);
            }

            // select random configurations
            Random r = new Random(seed);

            for (int i = 0; i < numConfigs; i++)
            {
                List <BinaryOption> selectedConfig = allConfigs[r.Next(allConfigs.Count)];

                if (configurations.Contains(selectedConfig))
                {
                    i -= 1;
                }
                else
                {
                    configurations.Add(selectedConfig);
                }
            }
            return(configurations);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClientRegistry"/> class.
        /// </summary>
        public ClientRegistry()
        {
            this.AddSingleton <ISecurityServiceClient, SecurityServiceClient>();
            this.AddSingleton <IVoucherManagementClient, VoucherManagementClient>();
            this.AddSingleton <Func <String, String> >(container => serviceName => { return(ConfigurationReader.GetBaseServerUri(serviceName).OriginalString); });
            HttpClientHandler httpClientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message,
                                                             certificate2,
                                                             arg3,
                                                             arg4) =>
                {
                    return(true);
                }
            };
            HttpClient httpClient = new HttpClient(httpClientHandler);

            this.AddSingleton(httpClient);
        }
Ejemplo n.º 37
0
 static BillConfiguration()
 {
     LEGAL_MENTIONS = ConfigurationReader.GetCollection <string>("LegalMentions");
 }
Ejemplo n.º 38
0
        public App()
        {
            InitializeComponent();

            var connection = HealthVaultConnectionFactory.Current.GetOrCreateSodaConnection(ConfigurationReader.ReadConfiguration());

            var navigationService = new NavigationService();
            var mainPage          = new MenuPage
            {
                BindingContext = new MenuViewModel(connection, navigationService),
            };

            var navigationPage = new NavigationPage(mainPage)
            {
                BarBackgroundColor = Color.White, BarTextColor = Color.Black
            };

            navigationService.RegisterNavigateEvents(navigationPage);
            MainPage = navigationPage;
        }
        public static void Dequeue(object Object)
        {
            lock (FileLock)
            {
                var ticketList = new List <Ticket>();
                using (StreamReader reader = new StreamReader(filePath))
                {
                    var data = reader.ReadToEnd();
                    reader.Close();
                    var allRecords = data.Split(new string[] { "(TICKET)" }, StringSplitOptions.None);

                    //Return if there are no records to be synced
                    if (!(allRecords.Length > 1))
                    {
                        return;
                    }

                    //Remove all records from file after reading them
                    File.WriteAllText(filePath, string.Empty);

                    var configurationSettings = ConfigurationReader.GetConfigurationSettings();

                    for (int i = 0; i < allRecords.Length - 1; i++)
                    {
                        var ticketData = allRecords[i].Split(new string[] { "(TP)" }, StringSplitOptions.None);

                        //Draw driver image from Base64 string
                        byte[]       driverImageBytes = Convert.FromBase64String(ticketData[6]);
                        MemoryStream ms1 = new MemoryStream(driverImageBytes, 0, driverImageBytes.Length);
                        ms1.Write(driverImageBytes, 0, driverImageBytes.Length);
                        Image driverImage = Image.FromStream(ms1, true);

                        //Draw vehicle image from Base64 string
                        byte[]       vehicleImageBytes = Convert.FromBase64String(ticketData[7]);
                        MemoryStream ms2 = new MemoryStream(vehicleImageBytes, 0, vehicleImageBytes.Length);
                        ms2.Write(vehicleImageBytes, 0, vehicleImageBytes.Length);
                        Image vehicleImage = Image.FromStream(ms2, true);

                        var ticket = new Ticket()
                        {
                            TicketNumber     = ticketData[0],
                            ValidationNumber = ticketData[1],
                            QRCode           = ticketData[2],
                            VehicleNumber    = ticketData[3],
                            VehicleType      = (VehicleType)int.Parse(ticketData[4]),
                            EntryTime        = ticketData[5],
                            DriverImage      = (Bitmap)driverImage,
                            VehicleImage     = (Bitmap)vehicleImage
                        };
                        ticketList.Add(ticket);
                    }

                    foreach (var ticket in ticketList)
                    {
                        try
                        {
                            parkingDatabaseFactory.SaveVehicleEntry(configurationSettings.TDClientDeviceId, ticket);
                        }
                        catch (Exception)
                        {
                            //Queue all tickets again in case of network Failure
                            Queue(ticket);
                        }
                    }
                }
            }
        }
Ejemplo n.º 40
0
 public void SetUp()
 {
     _configurationReader = new ConfigurationReader("OEEServer.xml", "OEEClientMqConfig.xml", new AsyncClassLogger("ConfigurationReaderTest"));
 }
Ejemplo n.º 41
0
        public void ReadZeroAsDefaultIntValue()
        {
            var settings = ConfigurationReader <SettingsWithInt> .ReadFromCollection(new KeyValueConfigurationCollection());

            Assert.AreEqual(0, settings.IntValue);
        }
Ejemplo n.º 42
0
 public void OpenCrossReferenceListPage(B2BEnvironment b2BEnvironment)
 {
     webDriver.Navigate().GoToUrl(ConfigurationReader.GetValue("CrossReferenceAssociationListPage") + (b2BEnvironment == B2BEnvironment.Production ? "P" : "U"));
 }
 internal KestrelConfigurationLoader(KestrelServerOptions options, IConfiguration configuration)
 {
     Options             = options ?? throw new ArgumentNullException(nameof(options));
     Configuration       = configuration ?? throw new ArgumentNullException(nameof(configuration));
     ConfigurationReader = new ConfigurationReader(Configuration);
 }
        public static void ReadAndRegisterConfiguration()
        {
            var config = new ConfigurationReader().Read("ConfigFiles", Environment.MachineName);

            ObjectFactory.Configure(x => x.For <IAsimovConfig>().Use(config));
        }
 public GetCommand()
 {
     Reader = Defaults.DefaultConfig;
 }
Ejemplo n.º 46
0
    // Adds endpoints from config to KestrelServerOptions.ConfigurationBackedListenOptions and configures some other options.
    // Any endpoints that were removed from the last time endpoints were loaded are returned.
    internal (List <ListenOptions>, List <ListenOptions>) Reload()
    {
        var endpointsToStop  = Options.ConfigurationBackedListenOptions.ToList();
        var endpointsToStart = new List <ListenOptions>();

        Options.ConfigurationBackedListenOptions.Clear();
        DefaultCertificateConfig = null;

        ConfigurationReader = new ConfigurationReader(Configuration);

        LoadDefaultCert();

        foreach (var endpoint in ConfigurationReader.Endpoints)
        {
            var listenOptions = AddressBinder.ParseAddress(endpoint.Url, out var https);

            if (!https)
            {
                ConfigurationReader.ThrowIfContainsHttpsOnlyConfiguration(endpoint);
            }

            Options.ApplyEndpointDefaults(listenOptions);

            if (endpoint.Protocols.HasValue)
            {
                listenOptions.Protocols = endpoint.Protocols.Value;
            }
            else
            {
                // Ensure endpoint is reloaded if it used the default protocol and the protocol changed.
                // listenOptions.Protocols should already be set to this by ApplyEndpointDefaults.
                endpoint.Protocols = ConfigurationReader.EndpointDefaults.Protocols;
            }

            // Compare to UseHttps(httpsOptions => { })
            var httpsOptions = new HttpsConnectionAdapterOptions();

            if (https)
            {
                // Defaults
                Options.ApplyHttpsDefaults(httpsOptions);

                if (endpoint.SslProtocols.HasValue)
                {
                    httpsOptions.SslProtocols = endpoint.SslProtocols.Value;
                }
                else
                {
                    // Ensure endpoint is reloaded if it used the default protocol and the SslProtocols changed.
                    endpoint.SslProtocols = ConfigurationReader.EndpointDefaults.SslProtocols;
                }

                if (endpoint.ClientCertificateMode.HasValue)
                {
                    httpsOptions.ClientCertificateMode = endpoint.ClientCertificateMode.Value;
                }
                else
                {
                    // Ensure endpoint is reloaded if it used the default mode and the ClientCertificateMode changed.
                    endpoint.ClientCertificateMode = ConfigurationReader.EndpointDefaults.ClientCertificateMode;
                }

                // A cert specified directly on the endpoint overrides any defaults.
                var(serverCert, fullChain)          = CertificateConfigLoader.LoadCertificate(endpoint.Certificate, endpoint.Name);
                httpsOptions.ServerCertificate      = serverCert ?? httpsOptions.ServerCertificate;
                httpsOptions.ServerCertificateChain = fullChain ?? httpsOptions.ServerCertificateChain;

                if (httpsOptions.ServerCertificate == null && httpsOptions.ServerCertificateSelector == null)
                {
                    // Fallback
                    Options.ApplyDefaultCert(httpsOptions);

                    // Ensure endpoint is reloaded if it used the default certificate and the certificate changed.
                    endpoint.Certificate = DefaultCertificateConfig;
                }
            }

            // Now that defaults have been loaded, we can compare to the currently bound endpoints to see if the config changed.
            // There's no reason to rerun an EndpointConfigurations callback if nothing changed.
            var matchingBoundEndpoints = endpointsToStop.Where(o => o.EndpointConfig == endpoint).ToList();

            if (matchingBoundEndpoints.Count > 0)
            {
                endpointsToStop.RemoveAll(o => o.EndpointConfig == endpoint);
                Options.ConfigurationBackedListenOptions.AddRange(matchingBoundEndpoints);
                continue;
            }

            if (EndpointConfigurations.TryGetValue(endpoint.Name, out var configureEndpoint))
            {
                var endpointConfig = new EndpointConfiguration(https, listenOptions, httpsOptions, endpoint.ConfigSection);
                configureEndpoint(endpointConfig);
            }

            // EndpointDefaults or configureEndpoint may have added an https adapter.
            if (https && !listenOptions.IsTls)
            {
                if (endpoint.Sni.Count == 0)
                {
                    if (httpsOptions.ServerCertificate == null && httpsOptions.ServerCertificateSelector == null)
                    {
                        throw new InvalidOperationException(CoreStrings.NoCertSpecifiedNoDevelopmentCertificateFound);
                    }

                    listenOptions.UseHttps(httpsOptions);
                }
                else
                {
                    var sniOptionsSelector = new SniOptionsSelector(endpoint.Name, endpoint.Sni, CertificateConfigLoader,
                                                                    httpsOptions, listenOptions.Protocols, HttpsLogger);
                    var tlsCallbackOptions = new TlsHandshakeCallbackOptions()
                    {
                        OnConnection      = SniOptionsSelector.OptionsCallback,
                        HandshakeTimeout  = httpsOptions.HandshakeTimeout,
                        OnConnectionState = sniOptionsSelector,
                    };

                    listenOptions.UseHttps(tlsCallbackOptions);
                }
            }

            listenOptions.EndpointConfig = endpoint;

            endpointsToStart.Add(listenOptions);
            Options.ConfigurationBackedListenOptions.Add(listenOptions);
        }

        return(endpointsToStop, endpointsToStart);
    }