public void ShouldBeAbleToConfigure()
 {
     Assert.Null(instanceGetter());
     var configuration = new DefaultConfiguration();
     Configuration.Configure(configuration);
     var configured = Configuration.Instance;
     Assert.Same(configuration, configured);
 }
        public void ComputedShouldRegisterPropertyAsDecompileable()
        {
            Assert.Null(InstanceGetter());
            var configuration = new DefaultConfiguration();
            Configuration.Configure(configuration);

            default(EntityTypeConfiguration<TestClass>).Computed(x => x.Property);

            Assert.IsTrue(configuration.ShouldDecompile(typeof(TestClass).GetProperty(nameof(TestClass.Property))));
        }
        public void ComputedShouldThrowExceptionIfUnsupportedMemberInfo()
        {
            Assert.Null(InstanceGetter());
            var configuration = new DefaultConfiguration();
            Configuration.Configure(configuration);

            Assert.That(() =>
            {
                default(EntityTypeConfiguration<TestClass>).Computed(x=>x.Field);
            }, Throws.InvalidOperationException);
        }
        public void ComputedShouldThrowExceptionIfUnsupportedExpression()
        {
            Assert.Null(InstanceGetter());
            var configuration = new DefaultConfiguration();
            Configuration.Configure(configuration);

            Assert.That(() =>
            {
                default(EntityTypeConfiguration<TestClass>).Computed(x => x.Property == 0);
            }, Throws.ArgumentException);
        }
Example #5
0
        public static ConfigurationPropertyHolder set_up_configuration_and_build_the_container(string[] args)
        {
            ConfigurationPropertyHolder configuration = new DefaultConfiguration();
            parse_arguments_and_set_up_configuration(configuration, args);
            if (configuration.Debug)
            {
                change_log_to_debug_level();
            }

            ApplicationConfiguraton.set_defaults_if_properties_are_not_set(configuration);
            ApplicationConfiguraton.build_the_container(configuration);

            return configuration;
        }
Example #6
0
        public TransactionRequest(
                Order order,
                PaymentMethod paymentMethod,
                CreateTransactionOptions options,
                IConfiguration configuration = null)
        {
            if (configuration == null) configuration = new DefaultConfiguration();

            _configuration = configuration;
            _paymentMethod = paymentMethod;
            _options = options;
            _order = order;

            UniqueKey = Guid.NewGuid();
        }
        /// <summary>
        /// <para>
        /// Saves the given object definition in NESTED hierarchical structure.
        /// </para>
        /// </summary>
        ///
        /// <param name="key">
        /// The key of the object definition.
        /// </param>
        /// <param name="definition">
        /// The object definition to be saved.
        /// </param>
        private void SaveNestedObjectDefinition(string key, ObjectDefinition definition)
        {
            // The root config of the definition
            IConfiguration objectConfig = AddRootConfig(ConfigObject, key);

            // Write all simple attributes of the definition
            AddNewNestedConfig(objectConfig, ConfigAppDomain, definition.AppDomain);
            AddNewNestedConfig(objectConfig, ConfigAssembly, definition.Assembly);
            AddNewNestedConfig(objectConfig, ConfigTypeName, definition.TypeName);
            AddNewNestedConfig(objectConfig, ConfigIgnoreCase, definition.IgnoreCase);
            AddNewNestedConfig(objectConfig, ConfigInstantiationLifetime, definition.InstantiationLifetime);
            AddNewNestedConfig(objectConfig, ConfigMethodName, definition.MethodName);

            // Get the method call definitions
            MethodCallDefinition[] methods = definition.MethodCalls;
            if (methods.Length > 0)
            {
                // The methods config
                IConfiguration methodsConfig = new DefaultConfiguration(ConfigMethods);

                // Write each method call definition
                int index = 0;
                foreach (MethodCallDefinition method in methods)
                {
                    SaveNestedMethodDefinition(methodsConfig, ConfigMethod + (++index), method);
                }

                // Add the methods config into root config
                objectConfig.AddChild(AbstractConfiguration.Synchronized(methodsConfig));
            }

            if (definition.ParamTypes.Length > 0)
            {
                // Write the parameter definitions of the object
                SaveNestedParameters(objectConfig, definition.ParamTypes, definition.ParamValues);
            }
        }
        /// <summary>
        /// <para>
        /// Converts the parameters configuration in FLAT structure into NESTED structure.
        /// </para>
        /// </summary>
        ///
        /// <param name="key">
        /// The key of the parameters definition.
        /// </param>
        ///
        /// <returns>
        /// The parameters configuration in NESTED structure.
        /// </returns>
        ///
        /// <exception cref="ConfigurationAPISourceException">
        /// If exceptions occur while retrieving the definition info, but may also indicate
        /// incomplete definition info (missing type name), parsing errors if the source
        /// uses string representations or some other errors.
        /// </exception>
        private IConfiguration ConvertParametersConfig(string key)
        {
            IConfiguration parametersConfig = GetChildByName(
                configuration, ConfigNamespace, key + "." + ConfigParameters, false);

            // No parameters configured
            if (parametersConfig == null)
            {
                return null;
            }

            // The new NESTED configuration
            IConfiguration nestedConfig = new DefaultConfiguration(ConfigParameters);

            IConfiguration[] parameters = parametersConfig.Children;

            // Sort the child nodes by name, since the parameters are ordered
            Array.Sort(parameters, new ConfigurationComparer());

            for (int i = 0; i < parameters.Length; ++i)
            {
                if (IsNodeMatch(parameters[i].Name, ConfigProperty))
                {
                    // The new config for the parameter
                    IConfiguration parameter = new DefaultConfiguration(ConfigParameter + "_" + (i + 1));

                    // Type name of the parameter
                    string typeWithDesc = GetSimpleAttribute(parameters[i], ConfigName, true);
                    string type = typeWithDesc.Substring(typeWithDesc.IndexOf(":") + 1).Trim();

                    // Add the type into the new config
                    parameter.SetSimpleAttribute(ConfigType, type);

                    IConfiguration[] valueConfigs = parameters[i].Children;

                    // Sort the child nodes by name, since the array values are ordered
                    Array.Sort(valueConfigs, new ConfigurationComparer());

                    // Convert parameter values
                    object[] values = new object[valueConfigs.Length];
                    for (int j = 0; j < values.Length; ++j)
                    {
                        if (IsNodeMatch(valueConfigs[j].Name, ConfigValue))
                        {
                            values[j] = GetSimpleAttribute(valueConfigs[j], ConfigNodeValue, true);
                        }
                    }

                    parameter.SetAttribute(ConfigValue, values);

                    nestedConfig.AddChild(parameter);
                }
            }

            return nestedConfig;
        }
        /// <summary>
        /// <para>
        /// Converts the method configuration in FLAT structure into NESTED structure.
        /// </para>
        /// </summary>
        ///
        /// <param name="objectKey">
        /// The key of the object definition.
        /// </param>
        /// <param name="methodsConfig">
        /// The method configuration in FLAT structure.
        /// </param>
        ///
        /// <returns>
        /// The method configuration in NESTED structure.
        /// </returns>
        ///
        /// <exception cref="ConfigurationAPISourceException">
        /// If exceptions occur while retrieving the definition info, but may also indicate
        /// incomplete definition info (missing type name), parsing errors if the source
        /// uses string representations or some other errors.
        /// </exception>
        private IConfiguration ConvertMethodsConfig(string objectKey, IConfiguration methodsConfig)
        {
            IConfiguration nestedConfig = new DefaultConfiguration(ConfigMethods);

            // All method keys
            object[] methodKeys = GetChildrenValues(methodsConfig);

            int index = 0;
            foreach (object methodKeyObj in methodKeys)
            {
                string methodKey = methodKeyObj as string;

                // The NESTED config of the method
                IConfiguration newMethodConfig = new DefaultConfiguration(ConfigMethod + "_" + (++index));

                // Get the FLAT config of the method
                string fullKey = objectKey + "." + methodKey;
                IConfiguration methodConfig =
                    GetChildByName(configuration, ConfigNamespace, fullKey, true);

                // Convert the method attributes
                foreach (IConfiguration methodAttr in methodConfig.Children)
                {
                    string attrName = GetSimpleAttribute(methodAttr, ConfigName, false);
                    if (attrName != null && Array.IndexOf(MethodAttributes, attrName) != -1)
                    {
                        newMethodConfig.AddChild(ConvertConfigNode(methodAttr, attrName));
                    }
                }

                // Convert the parameters attributes
                IConfiguration paramsConfig = ConvertParametersConfig(fullKey);
                if (paramsConfig != null)
                {
                    newMethodConfig.AddChild(paramsConfig);
                }

                nestedConfig.AddChild(newMethodConfig);
            }
            return nestedConfig;
        }
        protected void SetUp()
        {
            namedMsg = new NamedMessage(MESSAGE, NAMEDMESSAGE, new List<string>(PARAMETER_NAMES),
                Level.ERROR);

            config = new DefaultConfiguration("default");
            config.SetSimpleAttribute("logger_name", LOGNAME);
            config.SetSimpleAttribute("default_level", DEFAULT_LEVEL.ToString());
            config.SetSimpleAttribute("config_file", CONFIG_FILE);

            IConfiguration msgsConfig = new DefaultConfiguration("NamedMessages");

            IConfiguration msgConfig = new DefaultConfiguration(NAMEDMESSAGE);
            msgConfig.SetSimpleAttribute("text", MESSAGE);
            msgConfig.SetSimpleAttribute("default_level", Level.DEBUG);
            msgConfig.SetAttribute("parameters", new object[] {PARAMETER_NAMES[0], PARAMETER_NAMES[1]});
            msgsConfig.AddChild(msgConfig);

            config.AddChild(msgsConfig);

            logger = new Log4NETImpl(config);
        }
Example #11
0
        /// <summary>
        /// <para>
        /// Create a new instance of Log4NETImpl with default logger name.
        /// </para>
        /// </summary>
        public Log4NETImpl()
            : base(Process.GetCurrentProcess().ProcessName)
        {
            try
            {
                string loggerFilename = ConfigurationManager.AppSettings["DEFAULT_LOG4NET_FILENAME"];
                if (loggerFilename == null)
                {
                    loggerFilename = DEFAULT_CONFIG_FILE;
                }

                DefaultConfiguration config = new DefaultConfiguration("log4net");
                config.SetSimpleAttribute(CONFIG_FILE, loggerFilename);
                InitializeZeroConfiguration(ZeroConfigurationOption.Certification, config);

                // check if the configuration file exists, before attempting to load it
                FileInfo file = new FileInfo(loggerFilename);

                if (!file.Exists)
                {
                    throw new ConfigException("Unable to load '" + loggerFilename + "' for Log4NET");
                }

                // configure the log4net implementation
                XmlConfigurator.Configure(file);

                // get the log4net implementation to use for the life of this class
                log = log4net.LogManager.GetLogger(Logname);

                if (log == null)
                {
                    throw new ConfigException("Unable to create '" + Logname + "' using log4net.");
                }
            }
            catch (ConfigException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new ConfigException("Unable to initialize log4net", e);
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 100;
            IWebHost host      = null;
            var      processor = new ConsoleLoggerProcessor();
            CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor);

            using var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(loggerProvider);
            var logger = loggerFactory.CreateLogger("Configuration");

            try
            {
                // This is the only way that LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called
                var conf = new DefaultConfiguration()
                {
                    Logger = logger
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }
                Logs.Configure(loggerFactory);
                new BTCPayServerOptions().LoadArgs(conf);
                Logs.Configure(null);
                /////

                host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseConfiguration(conf)
                       .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical);
                    l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical);
                    l.AddFilter("OpenIddict.Server.OpenIddictServerProvider", LogLevel.Error);
                    l.AddProvider(new CustomConsoleLogProvider(processor));
                })
                       .UseStartup <Startup>()
                       .Build();
                host.StartWithTasksAsync().GetAwaiter().GetResult();
                var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var url in urls)
                {
                    logger.LogInformation("Listening on " + url);
                }
                host.WaitForShutdown();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            finally
            {
                processor.Dispose();
                if (host == null)
                {
                    Logs.Configuration.LogError("Configuration error");
                }
                if (host != null)
                {
                    host.Dispose();
                }
                Serilog.Log.CloseAndFlush();
                loggerProvider.Dispose();
            }
        }
Example #13
0
        public static ServiceRegistry CreateTestingServicesRegistryForDev()
        {
            CoreClient coreClient = new CoreClient(DefaultConfiguration.GetAppSetting("CoreHostName", "localhost"), DefaultConfiguration.GetAppSetting("CorePort", "9101").ToInt());

            return(GetServiceRegistry(coreClient));
        }
Example #14
0
        public static void Main(string[] args)
        {
            bool firstProcess = false;

            // chromely starts multiple child processes
            // we only want to start the asp core on the first process
            //
            // ideally it would be nice if chromely allowed things to be passed to
            // the child processes through args

            Mutex mutex = null;

            try
            {
                // if this succeeds we are not the first process
                mutex = Mutex.OpenExisting("BlazorTestMutex");
            }
            catch
            {
                // must be first process
                mutex        = new Mutex(false, "BlazorTestMutex");
                firstProcess = true;
            }

            int port = -1;

            if (firstProcess)
            {
                // try to find first available local port to host blazor on
                for (int i = StartScan; i < EndScan; i++)
                {
                    if (IsPortAvailable(i))
                    {
                        port = i;
                        break;
                    }
                }

                if (port != -1)
                {
                    // start the kestrel server in a background thread
                    var blazorTask = new Task(() => CreateHostBuilder(args, port).Build().Run(), TaskCreationOptions.LongRunning);
                    blazorTask.Start();

                    // wait till its up
                    while (IsPortAvailable(port))
                    {
                        Thread.Sleep(1);
                    }
                }

                // used to pass the port number to chromely child processes
                MemoryMappedFile         mmf      = MemoryMappedFile.CreateNew("BlazorTestMap", 4);
                MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
                accessor.Write(0, (int)port);
            }
            else
            {
                // fetch port number
                MemoryMappedFile         mmf      = MemoryMappedFile.CreateOrOpen("BlazorTestMap", 4);
                MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
                port = accessor.ReadInt32(0);
            }

            if (port != -1)
            {
                // start up chromely
                var core   = typeof(IChromelyConfiguration).Assembly;
                var config = DefaultConfiguration.CreateForRuntimePlatform();
                config.CefDownloadOptions     = new CefDownloadOptions(true, true);
                config.WindowOptions.Position = new WindowPosition(1, 2);
                config.WindowOptions.Size     = new WindowSize(1000, 600);
                config.StartUrl      = $"https://127.0.0.1:{port}";
                config.DebuggingMode = true;
                config.WindowOptions.RelativePathToIconFile = "chromely.ico";

                try
                {
                    var builder = AppBuilder.Create();
                    builder = builder.UseApp <TestApp>();
                    builder = builder.UseConfiguration <DefaultConfiguration>(config);
                    builder = builder.Build();
                    builder.Run(args);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }

            mutex.ReleaseMutex();
        }
Example #15
0
 static SecureChannel()
 {
     InitializeDatabase();
     Debug = DefaultConfiguration.GetAppSetting($"{nameof(SecureChannel)}.Debug", "false").IsAffirmative();
 }
        /// <summary>
        /// <para>
        /// Adds a new flat configuration node with given name attribute and values
        /// </para>
        /// </summary>
        ///
        /// <param name="parent">
        /// The parent configuration of the new node.
        /// </param>
        /// <param name="name">
        /// The name of the new configuration.
        /// </param>
        /// <param name="values">
        /// The values of the new configuration.
        /// </param>
        /// <param name="propertyIndex">
        /// The index of the new node.
        /// </param>
        ///
        /// <returns>
        /// The configuration created.
        /// </returns>
        private static void AddNewFlatConfig(IConfiguration parent,
            int propertyIndex, string name, params object[] values)
        {
            if (values[0] == null)
            {
                return;
            }

            // The property node
            IConfiguration child = new DefaultConfiguration(ConfigProperty + "_" + propertyIndex);
            child.SetSimpleAttribute(ConfigName, name);

            // The value nodes
            int index = 0;
            foreach (object value in values)
            {
                if (value != null)
                {
                    IConfiguration valueNode = new DefaultConfiguration(ConfigValue + "_" + (++index));
                    valueNode.SetSimpleAttribute(ConfigNodeValue, value.ToString());

                    child.AddChild(AbstractConfiguration.Synchronized(valueNode));
                }
            }

            // Add the new property node
            parent.AddChild(AbstractConfiguration.Synchronized(child));
        }
 /// <summary>
 /// <para>
 /// Converts a property-value configuration into NESETED structure.
 /// </para>
 /// </summary>
 ///
 /// <param name="config">
 /// The property configuration with values child.
 /// </param>
 /// <param name="name">
 /// The name of the new node.
 /// </param>
 ///
 /// <returns>
 /// The NESTED configuration created.
 /// </returns>
 private static IConfiguration ConvertConfigNode(IConfiguration config, string name)
 {
     IConfiguration nestedConfig = new DefaultConfiguration(name);
     nestedConfig.SetAttribute(ConfigValue, GetChildrenValues(config));
     return nestedConfig;
 }
        public void Start()
        {
            if (!Directory.Exists(_Directory))
            {
                Directory.CreateDirectory(_Directory);
            }
            string chain          = NBXplorerDefaultSettings.GetFolderName(NetworkType.Regtest);
            string chainDirectory = Path.Combine(_Directory, chain);

            if (!Directory.Exists(chainDirectory))
            {
                Directory.CreateDirectory(chainDirectory);
            }


            StringBuilder config = new StringBuilder();

            config.AppendLine($"{chain.ToLowerInvariant()}=1");
            config.AppendLine($"port={Port}");
            config.AppendLine($"chains=btc,ltc");

            config.AppendLine($"btc.explorer.url={NBXplorerUri.AbsoluteUri}");
            config.AppendLine($"btc.explorer.cookiefile=0");

            config.AppendLine($"ltc.explorer.url={LTCNBXplorerUri.AbsoluteUri}");
            config.AppendLine($"ltc.explorer.cookiefile=0");

            config.AppendLine($"btc.lightning={IntegratedLightning.AbsoluteUri}");

            if (Postgres != null)
            {
                config.AppendLine($"postgres=" + Postgres);
            }
            var confPath = Path.Combine(chainDirectory, "settings.config");

            File.WriteAllText(confPath, config.ToString());

            ServerUri = new Uri("http://" + HostName + ":" + Port + "/");

            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
            var conf = new DefaultConfiguration()
            {
                Logger = Logs.LogProvider.CreateLogger("Console")
            }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath });

            _Host = new WebHostBuilder()
                    .UseConfiguration(conf)
                    .ConfigureServices(s =>
            {
                s.AddLogging(l =>
                {
                    l.SetMinimumLevel(LogLevel.Information)
                    .AddFilter("Microsoft", LogLevel.Error)
                    .AddFilter("Hangfire", LogLevel.Error)
                    .AddProvider(Logs.LogProvider);
                });
            })
                    .UseKestrel()
                    .UseStartup <Startup>()
                    .Build();
            _Host.Start();
            InvoiceRepository = (InvoiceRepository)_Host.Services.GetService(typeof(InvoiceRepository));

            var rateProvider = (BTCPayRateProviderFactory)_Host.Services.GetService(typeof(BTCPayRateProviderFactory));

            rateProvider.DirectProviders.Clear();

            var coinAverageMock = new MockRateProvider();

            coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
            {
                Exchange     = "coinaverage",
                CurrencyPair = CurrencyPair.Parse("BTC_USD"),
                Value        = 5000m
            });
            coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
            {
                Exchange     = "coinaverage",
                CurrencyPair = CurrencyPair.Parse("BTC_CAD"),
                Value        = 4500m
            });
            coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
            {
                Exchange     = "coinaverage",
                CurrencyPair = CurrencyPair.Parse("LTC_USD"),
                Value        = 500m
            });
            rateProvider.DirectProviders.Add("coinaverage", coinAverageMock);
        }
Example #19
0
 private DirectoryInfo GetDataDir()
 {
     return(new DirectoryInfo(Configuration.GetDataDir(DefaultConfiguration.GetNetworkType(Configuration))));
 }
        protected void SetUp()
        {
            IList<string> param = new List<string>();
            param.Add("param1");
            param.Add("param2");

            namedMsg = new NamedMessage("text1", NAME1, param, Level.ERROR);

            msgs = new Dictionary<string, NamedMessage>();
            msgs.Add(NAME1, namedMsg);
            msgs.Add(NAME2, new NamedMessage("text2", NAME2, new List<string>(), Level.WARN));

            config = new DefaultConfiguration("default");
            config.SetSimpleAttribute("logger_name", LOGNAME);
            config.SetSimpleAttribute("default_level", LEVEL.ToString());

            IConfiguration msgsConfig = new DefaultConfiguration("NamedMessages");

            IConfiguration msgConfig = new DefaultConfiguration(NAME1);
            msgConfig.SetSimpleAttribute("text", "text1");
            msgConfig.SetSimpleAttribute("default_level", Level.ERROR);
            msgConfig.SetAttribute("parameters", new object[] {"param1", "param2"});
            msgsConfig.AddChild(msgConfig);

            msgConfig = new DefaultConfiguration(NAME2);
            msgConfig.SetSimpleAttribute("text", "text2");
            msgConfig.SetSimpleAttribute("default_level", Level.WARN);
            msgsConfig.AddChild(msgConfig);

            config.AddChild(msgsConfig);

            logger = new SimpleLogger(LOGNAME, LEVEL, msgs);
        }
Example #21
0
        public void TestDemoLogManager()
        {
            // create the logger from the specified namespaces, one for each of the
            // configured namespaces.
            CM.AppSettings[TestHelper.DEFAULT_LOGGER_CLASS_APP_SETTING_NAME]
                = "TopCoder.LoggingWrapper.Log4NETImpl";
            // logger1 is a Log4NETImpl instance
            Logger logger1 = LogManager.CreateLogger();

            CM.AppSettings[TestHelper.DEFAULT_LOGGER_CLASS_APP_SETTING_NAME]
                = "TopCoder.LoggingWrapper.DiagnosticImpl";
            // logger2 is a DiagnosticImpl instance
            Logger logger2 = LogManager.CreateLogger();

            CM.AppSettings[TestHelper.DEFAULT_LOGGER_CLASS_APP_SETTING_NAME]
                = "TopCoder.LoggingWrapper.ELSImpl";
            // logger3 is an ELSImpl instance
            Logger logger3 = LogManager.CreateLogger();

            CM.AppSettings[TestHelper.DEFAULT_LOGGER_CLASS_APP_SETTING_NAME]
                   = "TopCoder.LoggingWrapper.EnterpriseLibraryLogger";
            // logger4 is an EnterpriseLibraryLogger instance
            Logger logger4 = LogManager.CreateLogger();

            // create the logger from the Default Namespace
            // If the namespace is not specified, the namespace defaults to
            // TopCoder.LoggingWrapper.LogManager.
            Logger logger = LogManager.CreateLogger();

            // It is also possible to create a logger from a non-file based
            // configuration
            IConfiguration config = new DefaultConfiguration("default");
            config.SetSimpleAttribute("logger_class", "TopCoder.LoggingWrapper.DiagnosticImpl");
            config.SetSimpleAttribute("logger_name", "LogTest");
            config.SetSimpleAttribute("default_level", "INFO");
            config.SetSimpleAttribute("source", "source of demo");
            logger = LogManager.CreateLogger(config);
        }
Example #22
0
        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 100;
            IWebHost host      = null;
            var      processor = new ConsoleLoggerProcessor();
            CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor);

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);
            var logger = loggerFactory.CreateLogger("Configuration");

            try
            {
                var conf = new DefaultConfiguration()
                {
                    Logger = logger
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }

                host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseConfiguration(conf)
                       .UseApplicationInsights()
                       .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical);
                    l.AddProvider(new CustomConsoleLogProvider(processor));
                })
                       .UseStartup <Startup>()
                       .Build();
                host.StartAsync().GetAwaiter().GetResult();
                var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var url in urls)
                {
                    logger.LogInformation("Listening on " + url);
                }
                host.WaitForShutdown();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            finally
            {
                processor.Dispose();
                if (host != null)
                {
                    host.Dispose();
                }
                loggerProvider.Dispose();
            }
        }
        protected void SetUp()
        {
            namedMsg = new NamedMessage(MESSAGE, NAMEDMESSAGE, new List<string>(PARAMETER_NAMES),
                Level.ERROR);

            config = new DefaultConfiguration("default");
            config.SetSimpleAttribute("logger_name", LOGGER_NAME);
            config.SetSimpleAttribute("default_level", DEFAULT_LEVEL.ToString());

            IConfiguration msgsConfig = new DefaultConfiguration("NamedMessages");

            IConfiguration msgConfig = new DefaultConfiguration(NAMEDMESSAGE);
            msgConfig.SetSimpleAttribute("text", MESSAGE);
            msgConfig.SetSimpleAttribute("default_level", Level.DEBUG.ToString());
            msgConfig.SetAttribute("parameters", new object[] {PARAMETER_NAMES[0], PARAMETER_NAMES[1]});
            msgsConfig.AddChild(msgConfig);

            config.AddChild(msgsConfig);

            simpleLogger = new SimpleLogger(config);

            anotherLogger = new AnotherSimpleLogger(EXCEPTION_LOGGER_NAME);

            logger = new ExceptionSafeLogger(simpleLogger, anotherLogger);
        }
        public async Task StartAsync()
        {
            if (!Directory.Exists(_Directory))
            {
                Directory.CreateDirectory(_Directory);
            }
            string chain          = NBXplorerDefaultSettings.GetFolderName(NetworkType.Regtest);
            string chainDirectory = Path.Combine(_Directory, chain);

            if (!Directory.Exists(chainDirectory))
            {
                Directory.CreateDirectory(chainDirectory);
            }

            StringBuilder config = new StringBuilder();

            config.AppendLine($"{chain.ToLowerInvariant()}=1");
            if (InContainer)
            {
                config.AppendLine($"bind=0.0.0.0");
            }
            config.AppendLine($"port={Port}");
            config.AppendLine($"chains={string.Join(',', Chains)}");
            if (Chains.Contains("BTC", StringComparer.OrdinalIgnoreCase))
            {
                config.AppendLine($"btc.explorer.url={NBXplorerUri.AbsoluteUri}");
                config.AppendLine($"btc.explorer.cookiefile=0");
            }

            if (UseLightning)
            {
                config.AppendLine($"btc.lightning={IntegratedLightning.AbsoluteUri}");
                var localLndBackupFile = Path.Combine(_Directory, "walletunlock.json");
                File.Copy(TestUtils.GetTestDataFullPath("LndSeedBackup/walletunlock.json"), localLndBackupFile, true);
                config.AppendLine($"btc.external.lndseedbackup={localLndBackupFile}");
            }

            if (Chains.Contains("LTC", StringComparer.OrdinalIgnoreCase))
            {
                config.AppendLine($"ltc.explorer.url={LTCNBXplorerUri.AbsoluteUri}");
                config.AppendLine($"ltc.explorer.cookiefile=0");
            }
            if (Chains.Contains("LBTC", StringComparer.OrdinalIgnoreCase))
            {
                config.AppendLine($"lbtc.explorer.url={LBTCNBXplorerUri.AbsoluteUri}");
                config.AppendLine($"lbtc.explorer.cookiefile=0");
            }
            config.AppendLine("allow-admin-registration=1");

            config.AppendLine($"torrcfile={TestUtils.GetTestDataFullPath("Tor/torrc")}");
            config.AppendLine($"debuglog=debug.log");


            if (!string.IsNullOrEmpty(SSHPassword) && string.IsNullOrEmpty(SSHKeyFile))
            {
                config.AppendLine($"sshpassword={SSHPassword}");
            }
            if (!string.IsNullOrEmpty(SSHKeyFile))
            {
                config.AppendLine($"sshkeyfile={SSHKeyFile}");
            }
            if (!string.IsNullOrEmpty(SSHConnection))
            {
                config.AppendLine($"sshconnection={SSHConnection}");
            }

            if (TestDatabase == TestDatabases.MySQL && !String.IsNullOrEmpty(MySQL))
            {
                config.AppendLine($"mysql=" + MySQL);
            }
            else if (!String.IsNullOrEmpty(Postgres))
            {
                config.AppendLine($"postgres=" + Postgres);
            }
            var confPath = Path.Combine(chainDirectory, "settings.config");
            await File.WriteAllTextAsync(confPath, config.ToString());

            ServerUri              = new Uri("http://" + HostName + ":" + Port + "/");
            HttpClient             = new HttpClient();
            HttpClient.BaseAddress = ServerUri;
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
            var conf = new DefaultConfiguration()
            {
                Logger = Logs.LogProvider.CreateLogger("Console")
            }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath, "--disable-registration", "false" });

            _Host = new WebHostBuilder()
                    .UseConfiguration(conf)
                    .UseContentRoot(FindBTCPayServerDirectory())
                    .UseWebRoot(Path.Combine(FindBTCPayServerDirectory(), "wwwroot"))
                    .ConfigureServices(s =>
            {
                s.AddLogging(l =>
                {
                    l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical);
                    l.SetMinimumLevel(LogLevel.Information)
                    .AddFilter("Microsoft", LogLevel.Error)
                    .AddFilter("Hangfire", LogLevel.Error)
                    .AddProvider(Logs.LogProvider);
                });
            })
                    .UseKestrel()
                    .UseStartup <Startup>()
                    .Build();
            await _Host.StartWithTasksAsync();

            var urls = _Host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;

            foreach (var url in urls)
            {
                Logs.Tester.LogInformation("Listening on " + url);
            }
            Logs.Tester.LogInformation("Server URI " + ServerUri);

            InvoiceRepository = (InvoiceRepository)_Host.Services.GetService(typeof(InvoiceRepository));
            StoreRepository   = (StoreRepository)_Host.Services.GetService(typeof(StoreRepository));
            Networks          = (BTCPayNetworkProvider)_Host.Services.GetService(typeof(BTCPayNetworkProvider));

            if (MockRates)
            {
                var rateProvider = (RateProviderFactory)_Host.Services.GetService(typeof(RateProviderFactory));
                rateProvider.Providers.Clear();

                var coinAverageMock = new MockRateProvider();
                coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_USD"), new BidAsk(5000m)));
                coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_CAD"), new BidAsk(4500m)));
                coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_LTC"), new BidAsk(162m)));
                coinAverageMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("LTC_USD"), new BidAsk(500m)));
                rateProvider.Providers.Add("coingecko", coinAverageMock);

                var bitflyerMock = new MockRateProvider();
                bitflyerMock.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_JPY"), new BidAsk(700000m)));
                rateProvider.Providers.Add("bitflyer", bitflyerMock);

                var quadrigacx = new MockRateProvider();
                quadrigacx.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("BTC_CAD"), new BidAsk(6000m)));
                rateProvider.Providers.Add("quadrigacx", quadrigacx);

                var bittrex = new MockRateProvider();
                bittrex.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("DOGE_BTC"), new BidAsk(0.004m)));
                rateProvider.Providers.Add("bittrex", bittrex);


                var bitfinex = new MockRateProvider();
                bitfinex.ExchangeRates.Add(new PairRate(CurrencyPair.Parse("UST_BTC"), new BidAsk(0.000136m)));
                rateProvider.Providers.Add("bitfinex", bitfinex);
            }


            Logs.Tester.LogInformation("Waiting site is operational...");
            await WaitSiteIsOperational();

            Logs.Tester.LogInformation("Site is now operational");
        }
        /// <summary>
        /// <para>
        /// Add a configuration into the root configuration.
        /// </para>
        /// </summary>
        ///
        /// <remarks>
        /// The name is the the "prefix_number".
        /// </remarks>
        ///
        /// <param name="prefix">
        /// The prefix of the configuration name.
        /// </param>
        /// <param name="name">
        /// The name attributes of the configuration.
        /// </param>
        ///
        /// <returns>
        /// The configuration created.
        /// </returns>
        private IConfiguration AddRootConfig(string prefix, string name)
        {
            while (true)
            {
                try
                {
                    IConfiguration config = new DefaultConfiguration(GetNextConfigName(configuration, prefix));
                    config.SetSimpleAttribute(ConfigName, name);

                    // Exception may be thrown if the same name is used by other threads.
                    configuration.AddChild(AbstractConfiguration.Synchronized(config));

                    return config;
                }
                catch
                {
                    // Ignore exceptions and try other names
                }
            }
        }
 internal static string FileName() => $"{DefaultConfiguration.AppDomain()}{DefaultConfiguration.LocalizationPathTemplate}.json";
        /// <summary>
        /// <para>
        /// Converts the object configuration in FLAT structure into NESTED structure.
        /// </para>
        /// </summary>
        ///
        /// <param name="key">
        /// The key of the object definition.
        /// </param>
        ///
        /// <returns>
        /// The object configuration in NESTED structure.
        /// </returns>
        ///
        /// <exception cref="ConfigurationAPISourceException">
        /// If exceptions occur while retrieving the definition info, but may also indicate
        /// incomplete definition info (missing type name), parsing errors if the source
        /// uses string representations or some other errors.
        /// </exception>
        private IConfiguration ConvertObjectDefinition(string key)
        {
            IConfiguration objectConfig = GetChildByName(configuration, ConfigNamespace, key, true);

            // The nested config
            IConfiguration nestedConfig = new DefaultConfiguration(ConfigObject);
            nestedConfig.SetSimpleAttribute(ConfigName, key);

            foreach (IConfiguration child in objectConfig.Children)
            {
                string name = GetSimpleAttribute(child, ConfigName, false);

                if (name != null && Array.IndexOf(ObjectAttributes, name) != -1)
                {
                    // Simple object attributes
                    nestedConfig.AddChild(ConvertConfigNode(child, name));
                }
                else if (name == ConfigMethods)
                {
                    // Method list of the object definition
                    nestedConfig.AddChild(ConvertMethodsConfig(key, child));
                }
            }

            // Convert parameter definitions
            IConfiguration paramsConfig = ConvertParametersConfig(key);
            if (paramsConfig != null)
            {
                nestedConfig.AddChild(paramsConfig);
            }

            return nestedConfig;
        }
 public void MoveToStatus_InvalidStatus_ShouldThrowArgumentException()
 {
     Assert.That(() => DefaultConfiguration.MoveToStatus((PCConfigurationStatus)1234),
                 Throws.InstanceOf <ArgumentException>());
 }
        /// <summary>
        /// <para>
        /// Saves the given method definition in NESTED hierarchical structure.
        /// </para>
        /// </summary>
        ///
        /// <param name="name">
        /// The method unique name.
        /// </param>
        /// <param name="definition">
        /// The method definition to be saved.
        /// </param>
        /// <param name="parent">
        /// The methods configuration.
        /// </param>
        private void SaveNestedMethodDefinition(IConfiguration parent, string name, MethodCallDefinition definition)
        {
            // The config of the definition
            IConfiguration methodConfig = new DefaultConfiguration(name);

            // Write all simple attributes of the definition
            AddNewNestedConfig(methodConfig, ConfigIgnoreCase, definition.IgnoreCase);
            AddNewNestedConfig(methodConfig, ConfigMethodName, definition.MethodName);
            AddNewNestedConfig(methodConfig, ConfigIsProperty, definition.IsProperty);

            if (definition.ParamTypes.Length > 0)
            {
                // Write the parameter definitions of the method
                SaveNestedParameters(methodConfig, definition.ParamTypes, definition.ParamValues);
            }

            // Add the new method configuration into methods config
            parent.AddChild(AbstractConfiguration.Synchronized(methodConfig));
        }
 public void Constructor_JustCreated_ShouldHaveZeroPrice()
 {
     Assert.That(DefaultConfiguration.CalculatePrice(), Is.EqualTo(0));
 }
        /// <summary>
        /// <para>
        /// Saves the given parameters in NESTED hierarchical structure.
        /// </para>
        /// </summary>
        ///
        /// <param name="types">
        /// The parameter types.
        /// </param>
        /// <param name="values">
        /// The parameter values.
        /// </param>
        /// <param name="parent">
        /// The object configuration.
        /// </param>
        private void SaveNestedParameters(IConfiguration parent, string[] types, object[] values)
        {
            IConfiguration paramsConfig = new DefaultConfiguration(ConfigParameters);

            for (int i = 0; i < types.Length; ++i)
            {
                string childName = ConfigParameter + "_" + (i + 1);
                IConfiguration paramConfig;
                if (types[i] == NullType)
                {
                    // null parameter
                    paramConfig = AddNewNestedConfig(paramsConfig, childName, String.Empty);
                }
                else
                {
                    Array array = values[i] as Array;
                    if (array == null)
                    {
                        // Simple parameter
                        paramConfig = AddNewNestedConfig(paramsConfig, childName, values[i]);
                    }
                    else
                    {
                        // Array parameter
                        paramConfig = AddNewNestedConfig(paramsConfig, childName, ToStringArray(array));
                    }
                }

                // Add the type of the parameter
                paramConfig.SetSimpleAttribute(ConfigType, types[i]);
            }

            parent.AddChild(AbstractConfiguration.Synchronized(paramsConfig));
        }
 public void WithName_ConfigurationNotPublished_ShouldNotChangePublicName()
 {
     DefaultConfiguration.WithName("initial name");
     Assert.That(DefaultConfiguration.PublicName, Is.Null);
 }
        /// <summary>
        /// <para>
        /// Adds a new nested configuration node with given name and values
        /// </para>
        /// </summary>
        ///
        /// <param name="parent">
        /// The parent configuration of the new node.
        /// </param>
        /// <param name="name">
        /// The name of the new configuration.
        /// </param>
        /// <param name="values">
        /// The values of the new configuration.
        /// </param>
        ///
        /// <returns>
        /// The configuration created.
        /// </returns>
        private static IConfiguration AddNewNestedConfig(IConfiguration parent,
            string name, params object[] values)
        {
            if (values[0] == null)
            {
                return null;
            }

            IConfiguration child = new DefaultConfiguration(name);
            child.SetAttribute(ConfigValue, ToStringArray(values));

            parent.AddChild(AbstractConfiguration.Synchronized(child));
            return child;
        }
 public void WithComponent_NullComponent_ShouldThrowArgumentNullException()
 {
     Assert.That(() => DefaultConfiguration.WithComponent(null), Throws.InstanceOf <ArgumentNullException>());
 }
        public void Start()
        {
            if (!Directory.Exists(_Directory))
            {
                Directory.CreateDirectory(_Directory);
            }
            string chain          = NBXplorerDefaultSettings.GetFolderName(NetworkType.Regtest);
            string chainDirectory = Path.Combine(_Directory, chain);

            if (!Directory.Exists(chainDirectory))
            {
                Directory.CreateDirectory(chainDirectory);
            }


            StringBuilder config = new StringBuilder();

            config.AppendLine($"{chain.ToLowerInvariant()}=1");
            config.AppendLine($"port={Port}");
            config.AppendLine($"chains=btc,ltc");

            config.AppendLine($"btc.explorer.url={NBXplorerUri.AbsoluteUri}");
            config.AppendLine($"btc.explorer.cookiefile=0");

            config.AppendLine($"ltc.explorer.url={LTCNBXplorerUri.AbsoluteUri}");
            config.AppendLine($"ltc.explorer.cookiefile=0");

            config.AppendLine($"btc.lightning={IntegratedLightning.AbsoluteUri}");

            if (TestDatabase == TestDatabases.MySQL && !String.IsNullOrEmpty(MySQL))
            {
                config.AppendLine($"mysql=" + MySQL);
            }
            else if (!String.IsNullOrEmpty(Postgres))
            {
                config.AppendLine($"postgres=" + Postgres);
            }
            var confPath = Path.Combine(chainDirectory, "settings.config");

            File.WriteAllText(confPath, config.ToString());

            ServerUri = new Uri("http://" + HostName + ":" + Port + "/");

            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
            var conf = new DefaultConfiguration()
            {
                Logger = Logs.LogProvider.CreateLogger("Console")
            }.CreateConfiguration(new[] { "--datadir", _Directory, "--conf", confPath });

            _Host = new WebHostBuilder()
                    .UseConfiguration(conf)
                    .ConfigureServices(s =>
            {
                s.AddLogging(l =>
                {
                    l.SetMinimumLevel(LogLevel.Information)
                    .AddFilter("Microsoft", LogLevel.Error)
                    .AddFilter("Hangfire", LogLevel.Error)
                    .AddProvider(Logs.LogProvider);
                });
            })
                    .UseKestrel()
                    .UseStartup <Startup>()
                    .Build();
            _Host.Start();
            InvoiceRepository = (InvoiceRepository)_Host.Services.GetService(typeof(InvoiceRepository));
            StoreRepository   = (StoreRepository)_Host.Services.GetService(typeof(StoreRepository));
            var dashBoard = (NBXplorerDashboard)_Host.Services.GetService(typeof(NBXplorerDashboard));

            while (!dashBoard.IsFullySynched())
            {
                Thread.Sleep(10);
            }

            if (MockRates)
            {
                var rateProvider = (RateProviderFactory)_Host.Services.GetService(typeof(RateProviderFactory));
                rateProvider.Providers.Clear();

                var coinAverageMock = new MockRateProvider();
                coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "coinaverage",
                    CurrencyPair = CurrencyPair.Parse("BTC_USD"),
                    BidAsk       = new BidAsk(5000m)
                });
                coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "coinaverage",
                    CurrencyPair = CurrencyPair.Parse("BTC_CAD"),
                    BidAsk       = new BidAsk(4500m)
                });
                coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "coinaverage",
                    CurrencyPair = CurrencyPair.Parse("LTC_BTC"),
                    BidAsk       = new BidAsk(0.001m)
                });
                coinAverageMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "coinaverage",
                    CurrencyPair = CurrencyPair.Parse("LTC_USD"),
                    BidAsk       = new BidAsk(500m)
                });
                rateProvider.Providers.Add("coinaverage", coinAverageMock);

                var bitflyerMock = new MockRateProvider();
                bitflyerMock.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "bitflyer",
                    CurrencyPair = CurrencyPair.Parse("BTC_JPY"),
                    BidAsk       = new BidAsk(700000m)
                });
                rateProvider.Providers.Add("bitflyer", bitflyerMock);

                var quadrigacx = new MockRateProvider();
                quadrigacx.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "quadrigacx",
                    CurrencyPair = CurrencyPair.Parse("BTC_CAD"),
                    BidAsk       = new BidAsk(6000m)
                });
                rateProvider.Providers.Add("quadrigacx", quadrigacx);

                var bittrex = new MockRateProvider();
                bittrex.ExchangeRates.Add(new Rating.ExchangeRate()
                {
                    Exchange     = "bittrex",
                    CurrencyPair = CurrencyPair.Parse("DOGE_BTC"),
                    BidAsk       = new BidAsk(0.004m)
                });
                rateProvider.Providers.Add("bittrex", bittrex);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MultipleMediaPickerParameterEditor"/> class.
 /// </summary>
 public MultipleMediaPickerParameterEditor(
     IDataValueEditorFactory dataValueEditorFactory)
     : base(dataValueEditorFactory)
 {
     DefaultConfiguration.Add("multiPicker", "1");
 }