コード例 #1
3
ファイル: Program.cs プロジェクト: itn3000/Sample.CsConfig
 public static void Main(string[] args)
 {
     try
     {
         var configRoot = new ConfigurationBuilder()
             .AddCs("appsettings.csx")
             .Build();
         // root configurations
         foreach (var config in configRoot.GetChildren())
         {
             Console.WriteLine($"{config.Path}/{config.Key} = {config.Value}");
         }
         // subsection configurations
         var subSection = configRoot.GetSection("e");
         foreach (var config in subSection.GetChildren())
         {
             Console.WriteLine($"{config.Path}/{config.Key} = {config.Value}");
         }
         Console.WriteLine("Hello World");
     }
     catch (Exception e)
     {
         Console.WriteLine($"exception:{e.Message},{e.StackTrace}");
     }
     Console.Read();
 }
コード例 #2
0
        private static IServiceProvider getServiceProvider()
        {
            var services = new ServiceCollection();

            var configuration = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                                .AddJsonFile("appsettings.json", reloadOnChange: true, optional: false)
                                .AddInMemoryCollection(new[]
            {
                new KeyValuePair <string, string>("UseInMemoryDatabase", "true"),
            })
                                .Build();

            services.AddSingleton <IConfigurationRoot>(provider => configuration);
            services.Configure <SmtpConfig>(options => configuration.GetSection("SmtpConfig").Bind(options));
            services.Configure <AntiDosConfig>(options => configuration.GetSection("AntiDosConfig").Bind(options));

            services.AddSingleton <ILoggerFactory, LoggerFactory>();
            services.AddSingleton(typeof(ILogger <>), typeof(Logger <>));
            services.AddLogging(builder =>
            {
                builder.AddConsole();
                builder.AddDebug();
                builder.SetMinimumLevel(LogLevel.Trace);
            });

            services.AddDNTCommonWeb();

            var serviceProvider = services.BuildServiceProvider();

            return(serviceProvider);
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: muneebrbaig/AsanaNet
        private static string GetApiToken()
        {
            var configs = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json")
                          .Build();

            return(configs.GetSection("ApiToken").Value);
        }
コード例 #4
0
ファイル: HostingTask.cs プロジェクト: alanedwardes/aeblog
        public async Task DoWork(CancellationToken ctx)
        {
            var configuration = new ConfigurationBuilder()
                .AddGlobalConfigSources()
                .Build();

            var builder = new WebHostBuilder(configuration.GetSection("Hosting"));
            var engine = builder.Build();

            using (engine.Start())
            {
                await Task.Delay(Timeout.Infinite, ctx);
            }
        }
コード例 #5
0
        public void OptionsLifetimesShouldBeReplacedWithScoped()
        {
            MyApplication
                .StartsFrom<DefaultStartup>()
                .WithServices(services =>
                {
                    var configuration = new ConfigurationBuilder()
                        .AddJsonFile("config.json")
                        .Build();

                    services.Configure<CustomOptions>(configuration.GetSection("Options"));
                    services.Configure<CustomSettings>(configuration.GetSection("Settings"));
                });

            var options = TestApplication.Services.GetService<IOptions<CustomOptions>>();
            var settings = TestApplication.Services.GetService<IOptions<CustomSettings>>();

            Assert.NotNull(options);
            Assert.NotNull(settings);

            Assert.Equal(ServiceLifetime.Scoped, TestServiceProvider.GetServiceLifetime(typeof(IOptions<>)));

            MyApplication.StartsFrom<DefaultStartup>();
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: cgyqu/Rpc
        private static void Main()
        {
            //服务路由配置信息获取处(与Echo.Server为强制约束)。
            var configuration = new ConfigurationBuilder()
                .SetBasePath("d:\\")
                .AddJsonFile("routes.txt", false, true)
                .Build();

            //客户端基本服务。
            ISerializer serializer = new JsonSerializer();
            IServiceIdGenerator serviceIdGenerator = new DefaultServiceIdGenerator();
            var serviceRouteProvider = new DefaultServiceRouteProvider(configuration.GetSection("routes"));
            var serviceRouteManager = new DefaultServiceRouteManager(new[] { serviceRouteProvider });
            IAddressResolver addressResolver = new DefaultAddressResolver(serviceRouteManager);
            ITransportClientFactory transportClientFactory = new NettyTransportClientFactory(serializer);
            var remoteInvokeService = new RemoteInvokeService(addressResolver, transportClientFactory, serializer);

            //服务代理相关。
            IServiceProxyGenerater serviceProxyGenerater = new ServiceProxyGenerater(serviceIdGenerator);
            var services = serviceProxyGenerater.GenerateProxys(new[] { typeof(IUserService) }).ToArray();
            IServiceProxyFactory serviceProxyFactory = new ServiceProxyFactory(remoteInvokeService, serializer);

            //创建IUserService的代理。
            var userService = serviceProxyFactory.CreateProxy<IUserService>(services.Single(typeof(IUserService).IsAssignableFrom));

            while (true)
            {
                Task.Run(async () =>
                {
                    try
                    {
                        Console.WriteLine(DateTime.Now);
                        Console.WriteLine($"userService.GetUserName:{await userService.GetUserName(1)}");
                        Console.WriteLine($"userService.GetUserId:{await userService.GetUserId("rabbit")}");
                        Console.WriteLine($"userService.GetUserLastSignInTime:{await userService.GetUserLastSignInTime(1)}");
                        Console.WriteLine($"userService.Exists:{await userService.Exists(1)}");
                        var user = await userService.GetUser(1);
                        Console.WriteLine($"userService.GetUser:name={user.Name},age={user.Age}");
                        Console.WriteLine($"userService.Update:{await userService.Update(1, user)}");
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine("发生了错误。" + exception.Message);
                    }
                }).Wait();
                Console.ReadLine();
            }
        }
コード例 #7
0
ファイル: Injectors.cs プロジェクト: blehnen/DotNetWorkQueue
        private static void AddMetrics(IContainer container, string appName)
        {
            if (_metrics != null)
            {
                container.RegisterNonScopedSingleton <IMetrics>(_metrics);
                return;
            }

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("metricsettings.json")
                                .Build();

            var influxOptions = new MetricsReportingInfluxDbOptions();

            configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions);

            var metricsRoot = new MetricsBuilder()
                              .Configuration.ReadFrom(configuration)
                              .Configuration.Configure(
                options =>
            {
                options.AddServerTag();
                options.AddAppTag(appName);
            })
                              .Report.ToInfluxDb(influxOptions)
                              .Build();


            var metrics = new DotNetWorkQueue.AppMetrics.Metrics(metricsRoot);

            container.RegisterNonScopedSingleton <IMetrics>(metrics);

            var scheduler = new AppMetricsTaskScheduler(
                TimeSpan.FromSeconds(3),
                async() =>
            {
                await Task.WhenAll(metricsRoot.ReportRunner.RunAllAsync());
            });

            scheduler.Start();
            _metricScheduler = scheduler;
            _metrics         = metrics;
        }
コード例 #8
0
        public virtual List <string> Reload()
        {
            List <string> names = new List <string>();
            Dictionary <string, ICacheManagerConfiguration> configs = new Dictionary <string, ICacheManagerConfiguration>();

            string jsonFilePath = CacheProvider.CACHE_CONFIG_FILE;

            if (File.Exists(jsonFilePath))
            {
                string jsonText           = File.ReadAllText(jsonFilePath);
                var    memoryFileProvider = new InMemoryFileProvider(jsonText);
                var    config             = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                                            .AddJsonFile(memoryFileProvider, "fake.json", false, false)
                                            .Build();

                var managerSections = config.GetSection(CacheProvider.CACHE_SECTION_NAME).GetChildren();
                foreach (var managerSection in managerSections)
                {
                    string itemName = managerSection["name"];

                    var cacheConfiguration = config.GetCacheConfiguration(itemName);
                    if (configs.ContainsKey(itemName))
                    {
                        configs.Remove(itemName);
                    }
                    configs.Add(itemName, cacheConfiguration);

                    if (names.Contains(itemName))
                    {
                        names.Remove(itemName);
                    }
                    names.Add(itemName);
                }

                m_configs = configs;
            }

            return(names);
        }
コード例 #9
0
        public void WithOptionsShouldSetCorrectOptions()
        {
            MyApplication
                .StartsFrom<TestStartup>()
                .WithServices(services =>
                {
                    var configuration = new ConfigurationBuilder()
                        .AddJsonFile("config.json")
                        .Build();
                       
                    services.Configure<CustomSettings>(configuration.GetSection("Settings"));
                });

            MyController<OptionsController>
                .Instance()
                .WithOptions(options => options
                    .For<CustomSettings>(settings => settings.Name = "Test"))
                .Calling(c => c.Index())
                .ShouldReturn()
                .Ok();

            MyController<OptionsController>
                .Instance()
                .Calling(c => c.Index())
                .ShouldReturn()
                .BadRequest();

            MyController<OptionsController>
                .Instance()
                .WithOptions(options => options
                    .For<CustomSettings>(settings => settings.Name = "Invalid"))
                .Calling(c => c.Index())
                .ShouldReturn()
                .BadRequest();

            MyApplication.StartsFrom<DefaultStartup>();
        }
コード例 #10
0
        public void WithOptionsShouldSetCorrectOptions()
        {
            MyApplication
                .StartsFrom<DefaultStartup>()
                .WithServices(services =>
                {
                    var configuration = new ConfigurationBuilder()
                        .AddJsonFile("config.json")
                        .Build();

                    services.Configure<CustomSettings>(configuration.GetSection("Settings"));
                });

            MyViewComponent<OptionsComponent>
                .Instance()
                .WithOptions(options => options
                    .For<CustomSettings>(settings => settings.Name = "Test"))
                .InvokedWith(c => c.Invoke())
                .ShouldReturn()
                .View();

            MyViewComponent<OptionsComponent>
                .Instance()
                .InvokedWith(c => c.Invoke())
                .ShouldReturn()
                .Content();

            MyViewComponent<OptionsComponent>
                .Instance()
                .WithOptions(options => options
                    .For<CustomSettings>(settings => settings.Name = "Invalid"))
                .InvokedWith(c => c.Invoke())
                .ShouldReturn()
                .Content();

            MyApplication.StartsFrom<DefaultStartup>();
        }
コード例 #11
0
ファイル: Startup.cs プロジェクト: Websilk/Home
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //load application-wide memory store
            Server server = new Server();

            //use session
            app.UseSession();

            //handle static files
            var options = new StaticFileOptions {ContentTypeProvider = new FileExtensionContentTypeProvider()};
            app.UseStaticFiles(options);

            //exception handling
            var errOptions = new DeveloperExceptionPageOptions();
            errOptions.SourceCodeLineCount = 10;
            app.UseDeveloperExceptionPage();

            //get server info from config.json
            checkForConfig();

            var config = new ConfigurationBuilder()
                .AddJsonFile(server.MapPath("config.json"))
                .AddEnvironmentVariables().Build();

            server.sqlActive = config.GetSection("Data:Active").Value;
            server.sqlConnection = config.GetSection("Data:" + server.sqlActive).Value;
            server.https = config.GetSection("https").Value.ToLower() == "true" ? true : false;

            var isdev = false;
            switch (config.GetSection("Environment").Value)
            {
                case "development": case "dev":
                    server.environment = Server.enumEnvironment.development;
                    isdev = true;
                    break;
                case "staging": case "stage":
                    server.environment = Server.enumEnvironment.staging;
                    break;
                case "production": case "prod":
                    server.environment = Server.enumEnvironment.production;
                    break;
            }

            //configure server security
            server.bcrypt_workfactor = int.Parse(config.GetSection("Encryption:bcrypt_work_factor").Value);
            server.CheckAdminPassword();

            //run Websilk application
            app.Run(async (context) =>
            {
                var requestStart = DateTime.Now;
                DateTime requestEnd;
                TimeSpan tspan;
                var requestType = "";
                var path = cleanPath(context.Request.Path.ToString());
                var paths = path.Split('/').Skip(1).ToArray();
                var extension = "";

                //get request file extension (if exists)
                if(path.IndexOf(".")>= 0)
                {
                    for (int x = path.Length - 1; x >= 0; x += -1)
                    {
                        if (path.Substring(x, 1) == ".")
                        {
                            extension = path.Substring(x + 1); return;
                        }
                    }
                }

                server.requestCount += 1;
                if (isdev)
                {
                    Console.WriteLine("--------------------------------------------");
                    Console.WriteLine("{0} GET {1}", DateTime.Now.ToString("hh:mm:ss"), context.Request.Path);
                }

                if (paths.Length > 1)
                {
                    if(paths[0]=="api")
                    {
                        //run a web service via ajax (e.g. /api/namespace/class/function)
                         IFormCollection form = null;
                        if(context.Request.ContentType != null)
                        {
                            if (context.Request.ContentType.IndexOf("application/x-www-form-urlencoded") >= 0)
                            {
                            }else if (context.Request.ContentType.IndexOf("multipart/form-data") >= 0)
                            {
                                //get files collection from form data
                                form = await context.Request.ReadFormAsync();
                            }
                        }

                        if (cleanNamespace(paths))
                        {
                            //execute web service
                            var ws = new Pipeline.WebService(server, context, paths, form);
                            requestType = "service";
                        }
                    }
                }

                if(requestType == "" && extension == "")
                {
                    //initial page request
                    var r = new Pipeline.PageRequest(server, context);
                    requestType = "page";
                }

                if (isdev)
                {
                    requestEnd = DateTime.Now;
                    tspan = requestEnd - requestStart;
                    server.requestTime += (tspan.Seconds);
                    Console.WriteLine("END GET {0} {1} ms {2}", context.Request.Path, tspan.Milliseconds, requestType);
                    Console.WriteLine("");
                }

            });
        }
コード例 #12
0
ファイル: BaseDBFuentTest.cs プロジェクト: schotime/NPoco
        public void SetUp()
        {
            var types = new[] { typeof(User), typeof(ExtraUserInfo), typeof(UserWithExtraInfo), typeof(Usersss), typeof(House), typeof(Supervisor) };
            var dbFactory = new DatabaseFactory();
            var config = FluentMappingConfiguration.Scan(s =>
            {
                s.Assembly(typeof(User).GetTypeInfo().Assembly);
                s.IncludeTypes(types.Contains);
                s.PrimaryKeysNamed(y => ToLowerIf(y.Name + "Id", false));
                s.TablesNamed(y => ToLowerIf(Inflector.MakePlural(y.Name), false));
                s.Columns.Named(x => ToLowerIf(x.Name, false));
                s.Columns.ForceDateTimesToUtcWhere(x => x.GetMemberInfoType() == typeof(DateTime) || x.GetMemberInfoType() == typeof(DateTime?));
                s.Columns.ResultWhere(y => ColumnInfo.FromMemberInfo(y).ResultColumn);
                s.OverrideMappingsWith(new FluentMappingOverrides());
                s.OverrideMappingsWith(new OneToManyMappings());
            });
            dbFactory.Config().WithFluentConfig(config);

            var configuration = new ConfigurationBuilder()
                .AddJsonFile("config.json")
                .Build();

            var testDBType = Convert.ToInt32(configuration.GetSection("TestDBType").Value);
            switch (testDBType)
            {
                case 1: // SQLite In-Memory
                    TestDatabase = new InMemoryDatabase();
                    Database = dbFactory.Build(new Database(TestDatabase.Connection));
                    break;

                case 2: // SQL Local DB
                case 3: // SQL Server
                    var dataSource = configuration.GetSection("TestDbDataSource").Value;
                    TestDatabase = new SQLLocalDatabase(dataSource);
                    Database = dbFactory.Build(new Database(TestDatabase.Connection, new SqlServer2008DatabaseType()));
                    break;

                case 4: // SQL CE
                case 5: // MySQL
                case 6: // Oracle
                case 7: // Postgres
                    Assert.Fail("Database platform not supported for unit testing");
                    return;
            #if !DNXCORE50
                case 8: // Firebird
                    TestDatabase = new FirebirdDatabase();
                    var db = new Database(TestDatabase.Connection, new FirebirdDatabaseType());
                    db.Mappers.Insert(0, new FirebirdDefaultMapper());
                    Database = dbFactory.Build(db);
                    break;
            #endif

                default:
                    Assert.Fail("Unknown database platform specified");
                    return;
            }

            InsertData();
        }
コード例 #13
0
        public static void Main()
        {
            // **************************************************
            var configurationBuilderTraditional =
                new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                .SetBasePath(basePath: System.IO.Directory.GetCurrentDirectory())
                .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true)
                //.AddEnvironmentVariables()
                .Build();

            string employeeCountString =
                configurationBuilderTraditional
                .GetSection(key: "Settings")
                .GetSection(key: "Company")
                .GetSection(key: "EmployeeCount")
                .Value
            ;

            int employeeCount = 0;

            if (string.IsNullOrEmpty(employeeCountString) == false)
            {
                try
                {
                    employeeCount =
                        System.Convert.ToInt32(employeeCountString);
                }
                catch
                {
                }
            }
            // **************************************************

            // SetBasePath & AddJsonFile & Bind needs:
            // using Microsoft.Extensions.Configuration;

            var configurationBuilder =
                new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                .SetBasePath(basePath: System.IO.Directory.GetCurrentDirectory())
                .AddJsonFile(path: "appsettings.json", optional: true, reloadOnChange: true)
                //.AddEnvironmentVariables()
                .Build();

            var main = new Settings.Main();

            //configurationBuilder
            //	.GetSection(key: "Settings")
            //	.Bind(main);

            configurationBuilder
            .GetSection(key: Settings.Main.KeyName)
            .Bind(main);

            System.Console.WriteLine($"Age: { main.Age }");
            System.Console.WriteLine($"Salary: { main.Salary }$");
            System.Console.WriteLine($"Teacher: { main.IsTeacher }");
            System.Console.WriteLine($"Full Name: { main.FullName }");

            System.Console.WriteLine();
            System.Console.WriteLine($"Courses:");

            foreach (var item in main.Courses)
            {
                System.Console.Write($" { item }");
            }

            System.Console.WriteLine();
            System.Console.WriteLine();
            System.Console.WriteLine($"Company:");
            System.Console.WriteLine($" Name: { main.Company.Name }");
            System.Console.WriteLine($" Employee Count: { main.Company.EmployeeCount }");

            System.Console.WriteLine();
            System.Console.WriteLine();
            System.Console.Write($"Press any key to exit...");
            System.Console.ReadKey();
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: azyobuzin/img.azyobuzi.net
 private IServiceProvider BuildServiceProvider()
 {
     var configuration = new ConfigurationBuilder()
         .AddJsonFile("../../src/ImgAzyobuziNet/appsettings.json")
         .Build();
     var services = new ServiceCollection()
         .Configure<ImgAzyobuziNetOptions>(configuration.GetSection("ImgAzyobuziNet"))
         .AddLogging()
         .AddCaching();
     return services
         .AddInstance(typeof(ITestActivator), new TestActivator(services.BuildServiceProvider()))
         .BuildServiceProvider();
 }
コード例 #15
0
ファイル: BaseDBDecoratedTest.cs プロジェクト: joonhwan/NPoco
        public void SetUp()
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("config.json")
                .Build();

            var testDBType = Convert.ToInt32(configuration.GetSection("TestDBType").Value);
            switch (testDBType)
            {
                case 1: // SQLite In-Memory
                    TestDatabase = new InMemoryDatabase();
                    Database = new Database(TestDatabase.Connection);
                    break;

                case 2: // SQL Local DB
                    TestDatabase = new SQLLocalDatabase();
                    Database = new Database(TestDatabase.Connection, new SqlServer2008DatabaseType() { UseOutputClause = false }, SqlClientFactory.Instance, IsolationLevel.ReadUncommitted); // Need read uncommitted for the transaction tests
                    break;

                case 3: // SQL Server
                case 4: // SQL CE
                case 5: // MySQL
                case 6: // Oracle
                case 7: // Postgres
                    Assert.Fail("Database platform not supported for unit testing");
                    return;
            #if !DNXCORE50
                case 8: // Firebird
                    TestDatabase = new FirebirdDatabase();
                    Database = new Database(TestDatabase.Connection, new FirebirdDatabaseType(), FirebirdClientFactory.Instance, IsolationLevel.ReadUncommitted);
                    break;
            #endif

                default:
                    Assert.Fail("Unknown database platform specified");
                    return;
            }

            // Insert test data
            InsertData();
        }
コード例 #16
0
ファイル: ConstructorTests.cs プロジェクト: schotime/NPoco
        public void SetUp()
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("config.json")
                .Build();

            testDBType = Convert.ToInt32(configuration.GetSection("TestDBType").Value);
            switch (testDBType)
            {
                case 1: // SQLite In-Memory
                    TestDatabase = new InMemoryDatabase();
                    break;

                case 2: // SQL Local DB
                    var dataSource = configuration.GetSection("TestDbDataSource").Value;
                    TestDatabase = new SQLLocalDatabase(dataSource);
                    break;

                case 3: // SQL Server
                case 4: // SQL CE
                case 5: // MySQL
                case 6: // Oracle
                case 7: // Postgres
                    Assert.Fail("Database platform not supported for unit testing");
                    return;
            #if !DNXCORE50
                case 8: // Firebird
                    TestDatabase = new FirebirdDatabase();
                    break;
            #endif

                default:
                    Assert.Fail("Unknown database platform specified: " + testDBType);
                    return;
            }
        }
コード例 #17
0
            public CoinParameters(ICoinService coinService,
                string daemonUrl,
                string rpcUsername,
                string rpcPassword,
                string walletPassword,
                short rpcRequestTimeoutInSeconds)
            {
                var appSettings = new ConfigurationBuilder().AddJsonFile("config.json").Build().GetSection("AppSettings");

                if (!string.IsNullOrWhiteSpace(daemonUrl))
                {
                    DaemonUrl = daemonUrl;
                    UseTestnet = false; //  this will force the CoinParameters.SelectedDaemonUrl dynamic property to automatically pick the daemonUrl defined above
                    IgnoreConfigFiles = true;
                    RpcUsername = rpcUsername;
                    RpcPassword = rpcPassword;
                    WalletPassword = walletPassword;
                }

                if (rpcRequestTimeoutInSeconds > 0)
                {
                    RpcRequestTimeoutInSeconds = rpcRequestTimeoutInSeconds;
                }
                else
                {
                    short rpcRequestTimeoutTryParse = 0;

                    if (short.TryParse(appSettings.GetSection("RpcRequestTimeoutInSeconds").Value, out rpcRequestTimeoutTryParse))
                    {
                        RpcRequestTimeoutInSeconds = rpcRequestTimeoutTryParse;
                    }
                }

                if (IgnoreConfigFiles && (string.IsNullOrWhiteSpace(DaemonUrl) || string.IsNullOrWhiteSpace(RpcUsername) || string.IsNullOrWhiteSpace(RpcPassword)))
                {
                    throw new Exception($"One or more required parameters, as defined in {GetType().Name}, were not found in the configuration file!");
                }

                if (IgnoreConfigFiles && Debugger.IsAttached && string.IsNullOrWhiteSpace(WalletPassword))
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("[WARNING] The wallet password is either null or empty");
                    Console.ResetColor();
                }

                #region Bitcoin

                if (coinService is BitcoinService)
                {
                    if (!IgnoreConfigFiles)
                    {
                        DaemonUrl = appSettings.GetSection("Bitcoin_DaemonUrl").Value;
                        DaemonUrlTestnet = appSettings.GetSection("Bitcoin_DaemonUrl_Testnet").Value;
                        RpcUsername = appSettings.GetSection("Bitcoin_RpcUsername").Value;
                        RpcPassword = appSettings.GetSection("Bitcoin_RpcPassword").Value;
                        WalletPassword = appSettings.GetSection("Bitcoin_WalletPassword").Value;
                    }

                    CoinShortName = "BTC";
                    CoinLongName = "Bitcoin";
                    IsoCurrencyCode = "XBT";

                    TransactionSizeBytesContributedByEachInput = 148;
                    TransactionSizeBytesContributedByEachOutput = 34;
                    TransactionSizeFixedExtraSizeInBytes = 10;

                    FreeTransactionMaximumSizeInBytes = 1000;
                    FreeTransactionMinimumOutputAmountInCoins = 0.01M;
                    FreeTransactionMinimumPriority = 57600000;
                    FeePerThousandBytesInCoins = 0.0001M;
                    MinimumTransactionFeeInCoins = 0.0001M;
                    MinimumNonDustTransactionAmountInCoins = 0.0000543M;

                    TotalCoinSupplyInCoins = 21000000;
                    EstimatedBlockGenerationTimeInMinutes = 10;
                    BlocksHighestPriorityTransactionsReservedSizeInBytes = 50000;

                    BaseUnitName = "Satoshi";
                    BaseUnitsPerCoin = 100000000;
                    CoinsPerBaseUnit = 0.00000001M;
                }

                #endregion

                #region Litecoin

                else if (coinService is LitecoinService)
                {
                    if (!IgnoreConfigFiles)
                    {
                        DaemonUrl = appSettings.GetSection("Litecoin_DaemonUrl").Value;
                        DaemonUrlTestnet = appSettings.GetSection("Litecoin_DaemonUrl_Testnet").Value;
                        RpcUsername = appSettings.GetSection("Litecoin_RpcUsername").Value;
                        RpcPassword = appSettings.GetSection("Litecoin_RpcPassword").Value;
                        WalletPassword = appSettings.GetSection("Litecoin_WalletPassword").Value;
                    }

                    CoinShortName = "LTC";
                    CoinLongName = "Litecoin";
                    IsoCurrencyCode = "XLT";

                    TransactionSizeBytesContributedByEachInput = 148;
                    TransactionSizeBytesContributedByEachOutput = 34;
                    TransactionSizeFixedExtraSizeInBytes = 10;

                    FreeTransactionMaximumSizeInBytes = 5000;
                    FreeTransactionMinimumOutputAmountInCoins = 0.001M;
                    FreeTransactionMinimumPriority = 230400000;
                    FeePerThousandBytesInCoins = 0.001M;
                    MinimumTransactionFeeInCoins = 0.001M;
                    MinimumNonDustTransactionAmountInCoins = 0.001M;

                    TotalCoinSupplyInCoins = 84000000;
                    EstimatedBlockGenerationTimeInMinutes = 2.5;
                    BlocksHighestPriorityTransactionsReservedSizeInBytes = 16000;
                    BlockMaximumSizeInBytes = 250000;

                    BaseUnitName = "Litetoshi";
                    BaseUnitsPerCoin = 100000000;
                    CoinsPerBaseUnit = 0.00000001M;
                }

                #endregion

                #region Dogecoin

                else if (coinService is DogecoinService)
                {
                    if (!IgnoreConfigFiles)
                    {
                        DaemonUrl = appSettings.GetSection("Dogecoin_DaemonUrl").Value;
                        DaemonUrlTestnet = appSettings.GetSection("Dogecoin_DaemonUrl_Testnet").Value;
                        RpcUsername = appSettings.GetSection("Dogecoin_RpcUsername").Value;
                        RpcPassword = appSettings.GetSection("Dogecoin_RpcPassword").Value;
                        WalletPassword = appSettings.GetSection("Dogecoin_WalletPassword").Value;
                    }

                    CoinShortName = "Doge";
                    CoinLongName = "Dogecoin";
                    IsoCurrencyCode = "XDG";
                    TransactionSizeBytesContributedByEachInput = 148;
                    TransactionSizeBytesContributedByEachOutput = 34;
                    TransactionSizeFixedExtraSizeInBytes = 10;
                    FreeTransactionMaximumSizeInBytes = 1; // free txs are not supported from v.1.8+
                    FreeTransactionMinimumOutputAmountInCoins = 1;
                    FreeTransactionMinimumPriority = 230400000;
                    FeePerThousandBytesInCoins = 1;
                    MinimumTransactionFeeInCoins = 1;
                    MinimumNonDustTransactionAmountInCoins = 0.1M;
                    TotalCoinSupplyInCoins = 100000000000;
                    EstimatedBlockGenerationTimeInMinutes = 1;
                    BlocksHighestPriorityTransactionsReservedSizeInBytes = 16000;
                    BlockMaximumSizeInBytes = 500000;
                    BaseUnitName = "Koinu";
                    BaseUnitsPerCoin = 100000000;
                    CoinsPerBaseUnit = 0.00000001M;
                }

                #endregion

                #region Sarcoin

                else if (coinService is SarcoinService)
                {
                    if (!IgnoreConfigFiles)
                    {
                        DaemonUrl = appSettings.GetSection("Sarcoin_DaemonUrl").Value;
                        DaemonUrlTestnet = appSettings.GetSection("Sarcoin_DaemonUrl_Testnet").Value;
                        RpcUsername = appSettings.GetSection("Sarcoin_RpcUsername").Value;
                        RpcPassword = appSettings.GetSection("Sarcoin_RpcPassword").Value;
                        WalletPassword = appSettings.GetSection("Sarcoin_WalletPassword").Value;
                    }

                    CoinShortName = "SAR";
                    CoinLongName = "Sarcoin";
                    IsoCurrencyCode = "SAR";

                    TransactionSizeBytesContributedByEachInput = 148;
                    TransactionSizeBytesContributedByEachOutput = 34;
                    TransactionSizeFixedExtraSizeInBytes = 10;

                    FreeTransactionMaximumSizeInBytes = 0;
                    FreeTransactionMinimumOutputAmountInCoins = 0;
                    FreeTransactionMinimumPriority = 0;
                    FeePerThousandBytesInCoins = 0.00001M;
                    MinimumTransactionFeeInCoins = 0.00001M;
                    MinimumNonDustTransactionAmountInCoins = 0.00001M;

                    TotalCoinSupplyInCoins = 2000000000;
                    EstimatedBlockGenerationTimeInMinutes = 1.5;
                    BlocksHighestPriorityTransactionsReservedSizeInBytes = 50000;

                    BaseUnitName = "Satoshi";
                    BaseUnitsPerCoin = 100000000;
                    CoinsPerBaseUnit = 0.00000001M;
                }

                #endregion

                #region Agnostic coin (cryptocoin)

                else if (coinService is CryptocoinService)
                {
                    CoinShortName = "XXX";
                    CoinLongName = "Generic Cryptocoin Template";
                    IsoCurrencyCode = "XXX";

                    //  Note: The rest of the parameters will have to be defined at run-time
                }

                #endregion

                #region Uknown coin exception

                else
                {
                    throw new Exception("Unknown coin!");
                }

                #endregion

                #region Invalid configuration / Missing parameters

                if (RpcRequestTimeoutInSeconds <= 0)
                {
                    throw new Exception("RpcRequestTimeoutInSeconds must be greater than zero");
                }

                if (string.IsNullOrWhiteSpace(DaemonUrl)
                    || string.IsNullOrWhiteSpace(RpcUsername)
                    || string.IsNullOrWhiteSpace(RpcPassword))
                {
                    throw new Exception($"One or more required parameters, as defined in {GetType().Name}, were not found in the configuration file!");
                }

                #endregion
            }
コード例 #18
0
ファイル: Startup.cs プロジェクト: niros2/PublicRepo
        public static IConfigurationRoot AddConfiguration(this IServiceCollection services)
        {
            // Configuration
            var configuration = new ConfigurationBuilder()
                .AddInMemoryCollection(new Dictionary<string, string>
                {
                    { "username", "Guest" }
                })
                //.AddConfigFile(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
                .AddJsonFile(@"App_Data\config.json")
                .AddJsonFile(@"App_Data\appsettings.json")
                .AddXmlFile(@"App_Data\appsettings.xml")
                .AddEntityFrameworkConfig(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)
                .AddResxFile(@"App_Data\Resource1.resx")
                .AddEnvironmentVariables()
                .Build();

            // Options (see config.json)
            services.Configure<MySettings>(mySettings =>
            {
                mySettings.DateSetting = DateTime.Today;
            });

            services.Configure<MySettings>(configuration);
            //services.AddSingleton<IConfigureOptions<MySettings>>(new ConfigureFromConfigurationOptions<MySettings>(configuration));

            services.Configure<OtherSettings>(configuration.GetSection("otherSettings"));


            // *If* you need access to generic IConfiguration this is **required**
            services.AddSingleton<IConfigurationRoot>(configuration);

            return configuration;
        }
コード例 #19
0
        public void Refresh()
        {
            Dictionary <string, ICacheManager <object> > mgrs = new Dictionary <string, ICacheManager <object> >();

            /*
             * CacheManagerSection section = ConfigurationManager.GetSection(CACHE_SECTION_NAME) as CacheManagerSection;
             *
             * if (section != null && section.CacheManagers != null)
             * {
             *  foreach (var item in section.CacheManagers)
             *  {
             *      if (mgrs.ContainsKey(item.Name)) mgrs.Remove(item.Name);
             *      var cache = CacheFactory.FromConfiguration<object>(item.Name);
             *      if (cache != null) mgrs.Add(item.Name, cache);
             *  }
             * }
             */

            if (DataConfigHelper.CacheConfigLoader != null)
            {
                var cacheNames = DataConfigHelper.CacheConfigLoader.Reload();
                foreach (var cacheName in cacheNames)
                {
                    string itemName           = cacheName;
                    var    cacheConfiguration = DataConfigHelper.CacheConfigLoader.GetCacheConfig(itemName);
                    if (mgrs.ContainsKey(itemName))
                    {
                        mgrs.Remove(itemName);
                    }
                    var cache = CacheFactory.FromConfiguration <object>(cacheConfiguration);
                    if (cache != null)
                    {
                        mgrs.Add(itemName, cache);
                    }
                }
            }
            else
            {
                var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                             //.SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located
                             .AddJsonFile(CACHE_CONFIG_FILE, optional: false, reloadOnChange: true)
                             .Build();

                var managerSections = config.GetSection(CACHE_SECTION_NAME).GetChildren();
                foreach (var managerSection in managerSections)
                {
                    string itemName = managerSection["name"];

                    var cacheConfiguration = config.GetCacheConfiguration(itemName);

                    if (mgrs.ContainsKey(itemName))
                    {
                        mgrs.Remove(itemName);
                    }
                    var cache = CacheFactory.FromConfiguration <object>(cacheConfiguration);
                    if (cache != null)
                    {
                        mgrs.Add(itemName, cache);
                    }
                }
            }

            m_Mgrs = mgrs; // thread-safe (reads and writes of reference types are atomic)
        }